aboutsummaryrefslogtreecommitdiff
path: root/src/Sema.zig
blob: 8b476d4542a140edb6d9212fc178d771b0dbf028 (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
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
//! Semantic analysis of ZIR instructions.
//! Shared to every Block. Stored on the stack.
//! State used for compiling a ZIR into AIR.
//! Transforms untyped ZIR instructions into semantically-analyzed AIR instructions.
//! Does type checking, comptime control flow, and safety-check generation.
//! This is the the heart of the Zig compiler.

mod: *Module,
/// Alias to `mod.gpa`.
gpa: Allocator,
/// Points to the temporary arena allocator of the Sema.
/// This arena will be cleared when the sema is destroyed.
arena: Allocator,
/// Points to the arena allocator for the owner_decl.
/// This arena will persist until the decl is invalidated.
perm_arena: Allocator,
code: Zir,
air_instructions: std.MultiArrayList(Air.Inst) = .{},
air_extra: std.ArrayListUnmanaged(u32) = .{},
air_values: std.ArrayListUnmanaged(Value) = .{},
/// Maps ZIR to AIR.
inst_map: InstMap = .{},
/// When analyzing an inline function call, owner_decl is the Decl of the caller
/// and `src_decl` of `Block` is the `Decl` of the callee.
/// This `Decl` owns the arena memory of this `Sema`.
owner_decl: *Decl,
owner_decl_index: Decl.Index,
/// For an inline or comptime function call, this will be the root parent function
/// which contains the callsite. Corresponds to `owner_decl`.
owner_func: ?*Module.Fn,
/// The function this ZIR code is the body of, according to the source code.
/// This starts out the same as `owner_func` and then diverges in the case of
/// an inline or comptime function call.
func: ?*Module.Fn,
/// Used to restore the error return trace when returning a non-error from a function.
error_return_trace_index_on_fn_entry: Air.Inst.Ref = .none,
/// When semantic analysis needs to know the return type of the function whose body
/// is being analyzed, this `Type` should be used instead of going through `func`.
/// This will correctly handle the case of a comptime/inline function call of a
/// generic function which uses a type expression for the return type.
/// The type will be `void` in the case that `func` is `null`.
fn_ret_ty: Type,
branch_quota: u32 = default_branch_quota,
branch_count: u32 = 0,
/// Populated when returning `error.ComptimeBreak`. Used to communicate the
/// break instruction up the stack to find the corresponding Block.
comptime_break_inst: Zir.Inst.Index = undefined,
/// This field is updated when a new source location becomes active, so that
/// instructions which do not have explicitly mapped source locations still have
/// access to the source location set by the previous instruction which did
/// contain a mapped source location.
src: LazySrcLoc = .{ .token_offset = 0 },
decl_val_table: std.AutoHashMapUnmanaged(Decl.Index, Air.Inst.Ref) = .{},
/// When doing a generic function instantiation, this array collects a
/// `Value` object for each parameter that is comptime-known and thus elided
/// from the generated function. This memory is allocated by a parent `Sema` and
/// owned by the values arena of the Sema owner_decl.
comptime_args: []TypedValue = &.{},
/// Marks the function instruction that `comptime_args` applies to so that we
/// don't accidentally apply it to a function prototype which is used in the
/// type expression of a generic function parameter.
comptime_args_fn_inst: Zir.Inst.Index = 0,
/// When `comptime_args` is provided, this field is also provided. It was used as
/// the key in the `monomorphed_funcs` set. The `func` instruction is supposed
/// to use this instead of allocating a fresh one. This avoids an unnecessary
/// extra hash table lookup in the `monomorphed_funcs` set.
/// Sema will set this to null when it takes ownership.
preallocated_new_func: ?*Module.Fn = null,
/// The key is `constant` AIR instructions to types that must be fully resolved
/// after the current function body analysis is done.
/// TODO: after upgrading to use InternPool change the key here to be an
/// InternPool value index.
types_to_resolve: std.ArrayListUnmanaged(Air.Inst.Ref) = .{},
/// These are lazily created runtime blocks from block_inline instructions.
/// They are created when an break_inline passes through a runtime condition, because
/// Sema must convert comptime control flow to runtime control flow, which means
/// breaking from a block.
post_hoc_blocks: std.AutoHashMapUnmanaged(Air.Inst.Index, *LabeledBlock) = .{},
/// Populated with the last compile error created.
err: ?*Module.ErrorMsg = null,
/// True when analyzing a generic instantiation. Used to suppress some errors.
is_generic_instantiation: bool = false,
/// Set to true when analyzing a func type instruction so that nested generic
/// function types will emit generic poison instead of a partial type.
no_partial_func_ty: bool = false,

unresolved_inferred_allocs: std.AutoHashMapUnmanaged(Air.Inst.Index, void) = .{},

const std = @import("std");
const math = std.math;
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.sema);

const Sema = @This();
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const TypedValue = @import("TypedValue.zig");
const Air = @import("Air.zig");
const Zir = @import("Zir.zig");
const Module = @import("Module.zig");
const trace = @import("tracy.zig").trace;
const Namespace = Module.Namespace;
const CompileError = Module.CompileError;
const SemaError = Module.SemaError;
const Decl = Module.Decl;
const CaptureScope = Module.CaptureScope;
const WipCaptureScope = Module.WipCaptureScope;
const LazySrcLoc = Module.LazySrcLoc;
const RangeSet = @import("RangeSet.zig");
const target_util = @import("target.zig");
const Package = @import("Package.zig");
const crash_report = @import("crash_report.zig");
const build_options = @import("build_options");
const Compilation = @import("Compilation.zig");

pub const default_branch_quota = 1000;
pub const default_reference_trace_len = 2;

/// Stores the mapping from `Zir.Inst.Index -> Air.Inst.Ref`, which is used by sema to resolve
/// instructions during analysis.
/// Instead of a hash table approach, InstMap is simply a slice that is indexed into using the
/// zir instruction index and a start offset. An index is not pressent in the map if the value
/// at the index is `Air.Inst.Ref.none`.
/// `ensureSpaceForInstructions` can be called to force InstMap to have a mapped range that
/// includes all instructions in a slice. After calling this function, `putAssumeCapacity*` can
/// be called safely for any of the instructions passed in.
pub const InstMap = struct {
    items: []Air.Inst.Ref = &[_]Air.Inst.Ref{},
    start: Zir.Inst.Index = 0,

    pub fn deinit(map: InstMap, allocator: mem.Allocator) void {
        allocator.free(map.items);
    }

    pub fn get(map: InstMap, key: Zir.Inst.Index) ?Air.Inst.Ref {
        if (!map.contains(key)) return null;
        return map.items[key - map.start];
    }

    pub fn putAssumeCapacity(
        map: *InstMap,
        key: Zir.Inst.Index,
        ref: Air.Inst.Ref,
    ) void {
        map.items[key - map.start] = ref;
    }

    pub fn putAssumeCapacityNoClobber(
        map: *InstMap,
        key: Zir.Inst.Index,
        ref: Air.Inst.Ref,
    ) void {
        assert(!map.contains(key));
        map.putAssumeCapacity(key, ref);
    }

    pub const GetOrPutResult = struct {
        value_ptr: *Air.Inst.Ref,
        found_existing: bool,
    };

    pub fn getOrPutAssumeCapacity(
        map: *InstMap,
        key: Zir.Inst.Index,
    ) GetOrPutResult {
        const index = key - map.start;
        return GetOrPutResult{
            .value_ptr = &map.items[index],
            .found_existing = map.items[index] != .none,
        };
    }

    pub fn remove(map: InstMap, key: Zir.Inst.Index) bool {
        if (!map.contains(key)) return false;
        map.items[key - map.start] = .none;
        return true;
    }

    pub fn contains(map: InstMap, key: Zir.Inst.Index) bool {
        return map.items[key - map.start] != .none;
    }

    pub fn ensureSpaceForInstructions(
        map: *InstMap,
        allocator: mem.Allocator,
        insts: []const Zir.Inst.Index,
    ) !void {
        const min_max = mem.minMax(Zir.Inst.Index, insts);
        const start = min_max.min;
        const end = min_max.max;
        if (map.start <= start and end < map.items.len + map.start)
            return;

        const old_start = if (map.items.len == 0) start else map.start;
        var better_capacity = map.items.len;
        var better_start = old_start;
        while (true) {
            const extra_capacity = better_capacity / 2 + 16;
            better_capacity += extra_capacity;
            better_start -|= @intCast(Zir.Inst.Index, extra_capacity / 2);
            if (better_start <= start and end < better_capacity + better_start)
                break;
        }

        const start_diff = old_start - better_start;
        const new_items = try allocator.alloc(Air.Inst.Ref, better_capacity);
        mem.set(Air.Inst.Ref, new_items[0..start_diff], .none);
        mem.copy(Air.Inst.Ref, new_items[start_diff..], map.items);
        mem.set(Air.Inst.Ref, new_items[start_diff + map.items.len ..], .none);

        allocator.free(map.items);
        map.items = new_items;
        map.start = @intCast(Zir.Inst.Index, better_start);
    }
};

/// This is the context needed to semantically analyze ZIR instructions and
/// produce AIR instructions.
/// This is a temporary structure stored on the stack; references to it are valid only
/// during semantic analysis of the block.
pub const Block = struct {
    parent: ?*Block,
    /// Shared among all child blocks.
    sema: *Sema,
    /// The namespace to use for lookups from this source block
    /// When analyzing fields, this is different from src_decl.src_namespace.
    namespace: *Namespace,
    /// The AIR instructions generated for this block.
    instructions: std.ArrayListUnmanaged(Air.Inst.Index),
    // `param` instructions are collected here to be used by the `func` instruction.
    params: std.ArrayListUnmanaged(Param) = .{},

    wip_capture_scope: *CaptureScope,

    label: ?*Label = null,
    inlining: ?*Inlining,
    /// If runtime_index is not 0 then one of these is guaranteed to be non null.
    runtime_cond: ?LazySrcLoc = null,
    runtime_loop: ?LazySrcLoc = null,
    /// This Decl is the Decl according to the Zig source code corresponding to this Block.
    /// This can vary during inline or comptime function calls. See `Sema.owner_decl`
    /// for the one that will be the same for all Block instances.
    src_decl: Decl.Index,
    /// Non zero if a non-inline loop or a runtime conditional have been encountered.
    /// Stores to comptime variables are only allowed when var.runtime_index <= runtime_index.
    runtime_index: Value.RuntimeIndex = .zero,
    inline_block: Zir.Inst.Index = 0,

    comptime_reason: ?*const ComptimeReason = null,
    // TODO is_comptime and comptime_reason should probably be merged together.
    is_comptime: bool,
    is_typeof: bool = false,
    is_coerce_result_ptr: bool = false,

    /// Keep track of the active error return trace index around blocks so that we can correctly
    /// pop the error trace upon block exit.
    error_return_trace_index: Air.Inst.Ref = .none,

    /// when null, it is determined by build mode, changed by @setRuntimeSafety
    want_safety: ?bool = null,

    /// What mode to generate float operations in, set by @setFloatMode
    float_mode: std.builtin.FloatMode = .Strict,

    c_import_buf: ?*std.ArrayList(u8) = null,

    /// type of `err` in `else => |err|`
    switch_else_err_ty: ?Type = null,

    /// Value for switch_capture in an inline case
    inline_case_capture: Air.Inst.Ref = .none,

    const ComptimeReason = union(enum) {
        c_import: struct {
            block: *Block,
            src: LazySrcLoc,
        },
        comptime_ret_ty: struct {
            block: *Block,
            func: Air.Inst.Ref,
            func_src: LazySrcLoc,
            return_ty: Type,
        },

        fn explain(cr: ComptimeReason, sema: *Sema, msg: ?*Module.ErrorMsg) !void {
            const parent = msg orelse return;
            const prefix = "expression is evaluated at comptime because ";
            switch (cr) {
                .c_import => |ci| {
                    try sema.errNote(ci.block, ci.src, parent, prefix ++ "it is inside a @cImport", .{});
                },
                .comptime_ret_ty => |rt| {
                    const src_loc = if (try sema.funcDeclSrc(rt.func)) |fn_decl| blk: {
                        var src_loc = fn_decl.srcLoc();
                        src_loc.lazy = .{ .node_offset_fn_type_ret_ty = 0 };
                        break :blk src_loc;
                    } else blk: {
                        const src_decl = sema.mod.declPtr(rt.block.src_decl);
                        break :blk rt.func_src.toSrcLoc(src_decl);
                    };
                    if (rt.return_ty.tag() == .generic_poison) {
                        return sema.mod.errNoteNonLazy(src_loc, parent, prefix ++ "the generic function was instantiated with a comptime-only return type", .{});
                    }
                    try sema.mod.errNoteNonLazy(
                        src_loc,
                        parent,
                        prefix ++ "the function returns a comptime-only type '{}'",
                        .{rt.return_ty.fmt(sema.mod)},
                    );
                    try sema.explainWhyTypeIsComptime(rt.block, rt.func_src, parent, src_loc, rt.return_ty);
                },
            }
        }
    };

    const Param = struct {
        /// `noreturn` means `anytype`.
        ty: Type,
        is_comptime: bool,
        name: []const u8,
    };

    /// This `Block` maps a block ZIR instruction to the corresponding
    /// AIR instruction for break instruction analysis.
    pub const Label = struct {
        zir_block: Zir.Inst.Index,
        merges: Merges,
    };

    /// This `Block` indicates that an inline function call is happening
    /// and return instructions should be analyzed as a break instruction
    /// to this AIR block instruction.
    /// It is shared among all the blocks in an inline or comptime called
    /// function.
    pub const Inlining = struct {
        func: ?*Module.Fn,
        comptime_result: Air.Inst.Ref,
        merges: Merges,
    };

    pub const Merges = struct {
        block_inst: Air.Inst.Index,
        /// Separate array list from break_inst_list so that it can be passed directly
        /// to resolvePeerTypes.
        results: std.ArrayListUnmanaged(Air.Inst.Ref),
        /// Keeps track of the break instructions so that the operand can be replaced
        /// if we need to add type coercion at the end of block analysis.
        /// Same indexes, capacity, length as `results`.
        br_list: std.ArrayListUnmanaged(Air.Inst.Index),
    };

    /// For debugging purposes.
    pub fn dump(block: *Block, mod: Module) void {
        Zir.dumpBlock(mod, block);
    }

    pub fn makeSubBlock(parent: *Block) Block {
        return .{
            .parent = parent,
            .sema = parent.sema,
            .src_decl = parent.src_decl,
            .namespace = parent.namespace,
            .instructions = .{},
            .wip_capture_scope = parent.wip_capture_scope,
            .label = null,
            .inlining = parent.inlining,
            .is_comptime = parent.is_comptime,
            .comptime_reason = parent.comptime_reason,
            .is_typeof = parent.is_typeof,
            .runtime_cond = parent.runtime_cond,
            .runtime_loop = parent.runtime_loop,
            .runtime_index = parent.runtime_index,
            .want_safety = parent.want_safety,
            .float_mode = parent.float_mode,
            .c_import_buf = parent.c_import_buf,
            .switch_else_err_ty = parent.switch_else_err_ty,
            .error_return_trace_index = parent.error_return_trace_index,
        };
    }

    pub fn wantSafety(block: *const Block) bool {
        return block.want_safety orelse switch (block.sema.mod.optimizeMode()) {
            .Debug => true,
            .ReleaseSafe => true,
            .ReleaseFast => false,
            .ReleaseSmall => false,
        };
    }

    pub fn getFileScope(block: *Block) *Module.File {
        return block.namespace.file_scope;
    }

    fn addTy(
        block: *Block,
        tag: Air.Inst.Tag,
        ty: Type,
    ) error{OutOfMemory}!Air.Inst.Ref {
        return block.addInst(.{
            .tag = tag,
            .data = .{ .ty = ty },
        });
    }

    fn addTyOp(
        block: *Block,
        tag: Air.Inst.Tag,
        ty: Type,
        operand: Air.Inst.Ref,
    ) error{OutOfMemory}!Air.Inst.Ref {
        return block.addInst(.{
            .tag = tag,
            .data = .{ .ty_op = .{
                .ty = try block.sema.addType(ty),
                .operand = operand,
            } },
        });
    }

    fn addBitCast(block: *Block, ty: Type, operand: Air.Inst.Ref) Allocator.Error!Air.Inst.Ref {
        return block.addInst(.{
            .tag = .bitcast,
            .data = .{ .ty_op = .{
                .ty = try block.sema.addType(ty),
                .operand = operand,
            } },
        });
    }

    fn addNoOp(block: *Block, tag: Air.Inst.Tag) error{OutOfMemory}!Air.Inst.Ref {
        return block.addInst(.{
            .tag = tag,
            .data = .{ .no_op = {} },
        });
    }

    fn addUnOp(
        block: *Block,
        tag: Air.Inst.Tag,
        operand: Air.Inst.Ref,
    ) error{OutOfMemory}!Air.Inst.Ref {
        return block.addInst(.{
            .tag = tag,
            .data = .{ .un_op = operand },
        });
    }

    fn addBr(
        block: *Block,
        target_block: Air.Inst.Index,
        operand: Air.Inst.Ref,
    ) error{OutOfMemory}!Air.Inst.Ref {
        return block.addInst(.{
            .tag = .br,
            .data = .{ .br = .{
                .block_inst = target_block,
                .operand = operand,
            } },
        });
    }

    fn addBinOp(
        block: *Block,
        tag: Air.Inst.Tag,
        lhs: Air.Inst.Ref,
        rhs: Air.Inst.Ref,
    ) error{OutOfMemory}!Air.Inst.Ref {
        return block.addInst(.{
            .tag = tag,
            .data = .{ .bin_op = .{
                .lhs = lhs,
                .rhs = rhs,
            } },
        });
    }

    fn addStructFieldPtr(
        block: *Block,
        struct_ptr: Air.Inst.Ref,
        field_index: u32,
        ptr_field_ty: Type,
    ) !Air.Inst.Ref {
        const ty = try block.sema.addType(ptr_field_ty);
        const tag: Air.Inst.Tag = switch (field_index) {
            0 => .struct_field_ptr_index_0,
            1 => .struct_field_ptr_index_1,
            2 => .struct_field_ptr_index_2,
            3 => .struct_field_ptr_index_3,
            else => {
                return block.addInst(.{
                    .tag = .struct_field_ptr,
                    .data = .{ .ty_pl = .{
                        .ty = ty,
                        .payload = try block.sema.addExtra(Air.StructField{
                            .struct_operand = struct_ptr,
                            .field_index = field_index,
                        }),
                    } },
                });
            },
        };
        return block.addInst(.{
            .tag = tag,
            .data = .{ .ty_op = .{
                .ty = ty,
                .operand = struct_ptr,
            } },
        });
    }

    fn addStructFieldVal(
        block: *Block,
        struct_val: Air.Inst.Ref,
        field_index: u32,
        field_ty: Type,
    ) !Air.Inst.Ref {
        return block.addInst(.{
            .tag = .struct_field_val,
            .data = .{ .ty_pl = .{
                .ty = try block.sema.addType(field_ty),
                .payload = try block.sema.addExtra(Air.StructField{
                    .struct_operand = struct_val,
                    .field_index = field_index,
                }),
            } },
        });
    }

    fn addSliceElemPtr(
        block: *Block,
        slice: Air.Inst.Ref,
        elem_index: Air.Inst.Ref,
        elem_ptr_ty: Type,
    ) !Air.Inst.Ref {
        return block.addInst(.{
            .tag = .slice_elem_ptr,
            .data = .{ .ty_pl = .{
                .ty = try block.sema.addType(elem_ptr_ty),
                .payload = try block.sema.addExtra(Air.Bin{
                    .lhs = slice,
                    .rhs = elem_index,
                }),
            } },
        });
    }

    fn addPtrElemPtr(
        block: *Block,
        array_ptr: Air.Inst.Ref,
        elem_index: Air.Inst.Ref,
        elem_ptr_ty: Type,
    ) !Air.Inst.Ref {
        const ty_ref = try block.sema.addType(elem_ptr_ty);
        return block.addPtrElemPtrTypeRef(array_ptr, elem_index, ty_ref);
    }

    fn addPtrElemPtrTypeRef(
        block: *Block,
        array_ptr: Air.Inst.Ref,
        elem_index: Air.Inst.Ref,
        elem_ptr_ty: Air.Inst.Ref,
    ) !Air.Inst.Ref {
        return block.addInst(.{
            .tag = .ptr_elem_ptr,
            .data = .{ .ty_pl = .{
                .ty = elem_ptr_ty,
                .payload = try block.sema.addExtra(Air.Bin{
                    .lhs = array_ptr,
                    .rhs = elem_index,
                }),
            } },
        });
    }

    fn addCmpVector(block: *Block, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref, cmp_op: std.math.CompareOperator) !Air.Inst.Ref {
        return block.addInst(.{
            .tag = if (block.float_mode == .Optimized) .cmp_vector_optimized else .cmp_vector,
            .data = .{ .ty_pl = .{
                .ty = try block.sema.addType(
                    try Type.vector(block.sema.arena, block.sema.typeOf(lhs).vectorLen(), Type.bool),
                ),
                .payload = try block.sema.addExtra(Air.VectorCmp{
                    .lhs = lhs,
                    .rhs = rhs,
                    .op = Air.VectorCmp.encodeOp(cmp_op),
                }),
            } },
        });
    }

    fn addAggregateInit(
        block: *Block,
        aggregate_ty: Type,
        elements: []const Air.Inst.Ref,
    ) !Air.Inst.Ref {
        const sema = block.sema;
        const ty_ref = try sema.addType(aggregate_ty);
        try sema.air_extra.ensureUnusedCapacity(sema.gpa, elements.len);
        const extra_index = @intCast(u32, sema.air_extra.items.len);
        sema.appendRefsAssumeCapacity(elements);

        return block.addInst(.{
            .tag = .aggregate_init,
            .data = .{ .ty_pl = .{
                .ty = ty_ref,
                .payload = extra_index,
            } },
        });
    }

    fn addUnionInit(
        block: *Block,
        union_ty: Type,
        field_index: u32,
        init: Air.Inst.Ref,
    ) !Air.Inst.Ref {
        return block.addInst(.{
            .tag = .union_init,
            .data = .{ .ty_pl = .{
                .ty = try block.sema.addType(union_ty),
                .payload = try block.sema.addExtra(Air.UnionInit{
                    .field_index = field_index,
                    .init = init,
                }),
            } },
        });
    }

    pub fn addInst(block: *Block, inst: Air.Inst) error{OutOfMemory}!Air.Inst.Ref {
        return Air.indexToRef(try block.addInstAsIndex(inst));
    }

    pub fn addInstAsIndex(block: *Block, inst: Air.Inst) error{OutOfMemory}!Air.Inst.Index {
        const sema = block.sema;
        const gpa = sema.gpa;

        try sema.air_instructions.ensureUnusedCapacity(gpa, 1);
        try block.instructions.ensureUnusedCapacity(gpa, 1);

        const result_index = @intCast(Air.Inst.Index, sema.air_instructions.len);
        sema.air_instructions.appendAssumeCapacity(inst);
        block.instructions.appendAssumeCapacity(result_index);
        return result_index;
    }

    /// Insert an instruction into the block at `index`. Moves all following
    /// instructions forward in the block to make room. Operation is O(N).
    pub fn insertInst(block: *Block, index: Air.Inst.Index, inst: Air.Inst) error{OutOfMemory}!Air.Inst.Ref {
        return Air.indexToRef(try block.insertInstAsIndex(index, inst));
    }

    pub fn insertInstAsIndex(block: *Block, index: Air.Inst.Index, inst: Air.Inst) error{OutOfMemory}!Air.Inst.Index {
        const sema = block.sema;
        const gpa = sema.gpa;

        try sema.air_instructions.ensureUnusedCapacity(gpa, 1);

        const result_index = @intCast(Air.Inst.Index, sema.air_instructions.len);
        sema.air_instructions.appendAssumeCapacity(inst);

        try block.instructions.insert(gpa, index, result_index);
        return result_index;
    }

    fn addUnreachable(block: *Block, safety_check: bool) !void {
        if (safety_check and block.wantSafety()) {
            try block.sema.safetyPanic(block, .unreach);
        } else {
            _ = try block.addNoOp(.unreach);
        }
    }

    pub fn startAnonDecl(block: *Block) !WipAnonDecl {
        return WipAnonDecl{
            .block = block,
            .new_decl_arena = std.heap.ArenaAllocator.init(block.sema.gpa),
            .finished = false,
        };
    }

    pub const WipAnonDecl = struct {
        block: *Block,
        new_decl_arena: std.heap.ArenaAllocator,
        finished: bool,

        pub fn arena(wad: *WipAnonDecl) Allocator {
            return wad.new_decl_arena.allocator();
        }

        pub fn deinit(wad: *WipAnonDecl) void {
            if (!wad.finished) {
                wad.new_decl_arena.deinit();
            }
            wad.* = undefined;
        }

        /// `alignment` value of 0 means to use ABI alignment.
        pub fn finish(wad: *WipAnonDecl, ty: Type, val: Value, alignment: u32) !Decl.Index {
            const sema = wad.block.sema;
            // Do this ahead of time because `createAnonymousDecl` depends on calling
            // `type.hasRuntimeBits()`.
            _ = try sema.typeHasRuntimeBits(ty);
            const new_decl_index = try sema.mod.createAnonymousDecl(wad.block, .{
                .ty = ty,
                .val = val,
            });
            const new_decl = sema.mod.declPtr(new_decl_index);
            new_decl.@"align" = alignment;
            errdefer sema.mod.abortAnonDecl(new_decl_index);
            try new_decl.finalizeNewArena(&wad.new_decl_arena);
            wad.finished = true;
            return new_decl_index;
        }
    };
};

const LabeledBlock = struct {
    block: Block,
    label: Block.Label,

    fn destroy(lb: *LabeledBlock, gpa: Allocator) void {
        lb.block.instructions.deinit(gpa);
        lb.label.merges.results.deinit(gpa);
        lb.label.merges.br_list.deinit(gpa);
        gpa.destroy(lb);
    }
};

pub fn deinit(sema: *Sema) void {
    const gpa = sema.gpa;
    sema.air_instructions.deinit(gpa);
    sema.air_extra.deinit(gpa);
    sema.air_values.deinit(gpa);
    sema.inst_map.deinit(gpa);
    sema.decl_val_table.deinit(gpa);
    sema.types_to_resolve.deinit(gpa);
    {
        var it = sema.post_hoc_blocks.iterator();
        while (it.next()) |entry| {
            const labeled_block = entry.value_ptr.*;
            labeled_block.destroy(gpa);
        }
        sema.post_hoc_blocks.deinit(gpa);
    }
    sema.unresolved_inferred_allocs.deinit(gpa);
    sema.* = undefined;
}

/// Returns only the result from the body that is specified.
/// Only appropriate to call when it is determined at comptime that this body
/// has no peers.
fn resolveBody(
    sema: *Sema,
    block: *Block,
    body: []const Zir.Inst.Index,
    /// This is the instruction that a break instruction within `body` can
    /// use to return from the body.
    body_inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const break_data = (try sema.analyzeBodyBreak(block, body)) orelse
        return Air.Inst.Ref.unreachable_value;
    // For comptime control flow, we need to detect when `analyzeBody` reports
    // that we need to break from an outer block. In such case we
    // use Zig's error mechanism to send control flow up the stack until
    // we find the corresponding block to this break.
    if (block.is_comptime and break_data.block_inst != body_inst) {
        sema.comptime_break_inst = break_data.inst;
        return error.ComptimeBreak;
    }
    return try sema.resolveInst(break_data.operand);
}

fn analyzeBodyRuntimeBreak(sema: *Sema, block: *Block, body: []const Zir.Inst.Index) !void {
    _ = sema.analyzeBodyInner(block, body) catch |err| switch (err) {
        error.ComptimeBreak => {
            const zir_datas = sema.code.instructions.items(.data);
            const break_data = zir_datas[sema.comptime_break_inst].@"break";
            try sema.addRuntimeBreak(block, .{
                .block_inst = break_data.block_inst,
                .operand = break_data.operand,
                .inst = sema.comptime_break_inst,
            });
        },
        else => |e| return e,
    };
}

pub fn analyzeBody(
    sema: *Sema,
    block: *Block,
    body: []const Zir.Inst.Index,
) !void {
    _ = sema.analyzeBodyInner(block, body) catch |err| switch (err) {
        error.ComptimeBreak => unreachable, // unexpected comptime control flow
        else => |e| return e,
    };
}

const BreakData = struct {
    block_inst: Zir.Inst.Index,
    operand: Zir.Inst.Ref,
    inst: Zir.Inst.Index,
};

pub fn analyzeBodyBreak(
    sema: *Sema,
    block: *Block,
    body: []const Zir.Inst.Index,
) CompileError!?BreakData {
    const break_inst = sema.analyzeBodyInner(block, body) catch |err| switch (err) {
        error.ComptimeBreak => sema.comptime_break_inst,
        else => |e| return e,
    };
    if (block.instructions.items.len != 0 and
        sema.typeOf(Air.indexToRef(block.instructions.items[block.instructions.items.len - 1])).isNoReturn())
        return null;
    const break_data = sema.code.instructions.items(.data)[break_inst].@"break";
    return BreakData{
        .block_inst = break_data.block_inst,
        .operand = break_data.operand,
        .inst = break_inst,
    };
}

/// ZIR instructions which are always `noreturn` return this. This matches the
/// return type of `analyzeBody` so that we can tail call them.
/// Only appropriate to return when the instruction is known to be NoReturn
/// solely based on the ZIR tag.
const always_noreturn: CompileError!Zir.Inst.Index = @as(Zir.Inst.Index, undefined);

/// This function is the main loop of `Sema` and it can be used in two different ways:
/// * The traditional way where there are N breaks out of the block and peer type
///   resolution is done on the break operands. In this case, the `Zir.Inst.Index`
///   part of the return value will be `undefined`, and callsites should ignore it,
///   finding the block result value via the block scope.
/// * The "flat" way. There is only 1 break out of the block, and it is with a `break_inline`
///   instruction. In this case, the `Zir.Inst.Index` part of the return value will be
///   the break instruction. This communicates both which block the break applies to, as
///   well as the operand. No block scope needs to be created for this strategy.
fn analyzeBodyInner(
    sema: *Sema,
    block: *Block,
    body: []const Zir.Inst.Index,
) CompileError!Zir.Inst.Index {
    // No tracy calls here, to avoid interfering with the tail call mechanism.

    try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);

    const parent_capture_scope = block.wip_capture_scope;

    var wip_captures = WipCaptureScope{
        .finalized = true,
        .scope = parent_capture_scope,
        .perm_arena = sema.perm_arena,
        .gpa = sema.gpa,
    };
    defer if (wip_captures.scope != parent_capture_scope) {
        wip_captures.deinit();
    };

    const map = &sema.inst_map;
    const tags = sema.code.instructions.items(.tag);
    const datas = sema.code.instructions.items(.data);

    var orig_captures: usize = parent_capture_scope.captures.count();

    var crash_info = crash_report.prepAnalyzeBody(sema, block, body);
    crash_info.push();
    defer crash_info.pop();

    var dbg_block_begins: u32 = 0;

    // We use a while(true) loop here to avoid a redundant way of breaking out of
    // the loop. The only way to break out of the loop is with a `noreturn`
    // instruction.
    var i: usize = 0;
    const result = while (true) {
        crash_info.setBodyIndex(i);
        const inst = body[i];
        std.log.scoped(.sema_zir).debug("sema ZIR {s} %{d}", .{
            sema.mod.declPtr(block.src_decl).src_namespace.file_scope.sub_file_path, inst,
        });
        const air_inst: Air.Inst.Ref = switch (tags[inst]) {
            // zig fmt: off
            .alloc                        => try sema.zirAlloc(block, inst),
            .alloc_inferred               => try sema.zirAllocInferred(block, inst, Type.initTag(.inferred_alloc_const)),
            .alloc_inferred_mut           => try sema.zirAllocInferred(block, inst, Type.initTag(.inferred_alloc_mut)),
            .alloc_inferred_comptime      => try sema.zirAllocInferredComptime(inst, Type.initTag(.inferred_alloc_const)),
            .alloc_inferred_comptime_mut  => try sema.zirAllocInferredComptime(inst, Type.initTag(.inferred_alloc_mut)),
            .alloc_mut                    => try sema.zirAllocMut(block, inst),
            .alloc_comptime_mut           => try sema.zirAllocComptime(block, inst),
            .make_ptr_const               => try sema.zirMakePtrConst(block, inst),
            .anyframe_type                => try sema.zirAnyframeType(block, inst),
            .array_cat                    => try sema.zirArrayCat(block, inst),
            .array_mul                    => try sema.zirArrayMul(block, inst),
            .array_type                   => try sema.zirArrayType(block, inst),
            .array_type_sentinel          => try sema.zirArrayTypeSentinel(block, inst),
            .vector_type                  => try sema.zirVectorType(block, inst),
            .as                           => try sema.zirAs(block, inst),
            .as_node                      => try sema.zirAsNode(block, inst),
            .as_shift_operand             => try sema.zirAsShiftOperand(block, inst),
            .bit_and                      => try sema.zirBitwise(block, inst, .bit_and),
            .bit_not                      => try sema.zirBitNot(block, inst),
            .bit_or                       => try sema.zirBitwise(block, inst, .bit_or),
            .bitcast                      => try sema.zirBitcast(block, inst),
            .suspend_block                => try sema.zirSuspendBlock(block, inst),
            .bool_not                     => try sema.zirBoolNot(block, inst),
            .bool_br_and                  => try sema.zirBoolBr(block, inst, false),
            .bool_br_or                   => try sema.zirBoolBr(block, inst, true),
            .c_import                     => try sema.zirCImport(block, inst),
            .call                         => try sema.zirCall(block, inst),
            .closure_get                  => try sema.zirClosureGet(block, inst),
            .cmp_lt                       => try sema.zirCmp(block, inst, .lt),
            .cmp_lte                      => try sema.zirCmp(block, inst, .lte),
            .cmp_eq                       => try sema.zirCmpEq(block, inst, .eq, Air.Inst.Tag.fromCmpOp(.eq, block.float_mode == .Optimized)),
            .cmp_gte                      => try sema.zirCmp(block, inst, .gte),
            .cmp_gt                       => try sema.zirCmp(block, inst, .gt),
            .cmp_neq                      => try sema.zirCmpEq(block, inst, .neq, Air.Inst.Tag.fromCmpOp(.neq, block.float_mode == .Optimized)),
            .coerce_result_ptr            => try sema.zirCoerceResultPtr(block, inst),
            .decl_ref                     => try sema.zirDeclRef(block, inst),
            .decl_val                     => try sema.zirDeclVal(block, inst),
            .load                         => try sema.zirLoad(block, inst),
            .elem_ptr                     => try sema.zirElemPtr(block, inst),
            .elem_ptr_node                => try sema.zirElemPtrNode(block, inst),
            .elem_ptr_imm                 => try sema.zirElemPtrImm(block, inst),
            .elem_val                     => try sema.zirElemVal(block, inst),
            .elem_val_node                => try sema.zirElemValNode(block, inst),
            .elem_type_index              => try sema.zirElemTypeIndex(block, inst),
            .enum_literal                 => try sema.zirEnumLiteral(block, inst),
            .enum_to_int                  => try sema.zirEnumToInt(block, inst),
            .int_to_enum                  => try sema.zirIntToEnum(block, inst),
            .err_union_code               => try sema.zirErrUnionCode(block, inst),
            .err_union_code_ptr           => try sema.zirErrUnionCodePtr(block, inst),
            .err_union_payload_unsafe     => try sema.zirErrUnionPayload(block, inst),
            .err_union_payload_unsafe_ptr => try sema.zirErrUnionPayloadPtr(block, inst),
            .error_union_type             => try sema.zirErrorUnionType(block, inst),
            .error_value                  => try sema.zirErrorValue(block, inst),
            .field_ptr                    => try sema.zirFieldPtr(block, inst, false),
            .field_ptr_init               => try sema.zirFieldPtr(block, inst, true),
            .field_ptr_named              => try sema.zirFieldPtrNamed(block, inst),
            .field_val                    => try sema.zirFieldVal(block, inst),
            .field_val_named              => try sema.zirFieldValNamed(block, inst),
            .field_call_bind              => try sema.zirFieldCallBind(block, inst),
            .func                         => try sema.zirFunc(block, inst, false),
            .func_inferred                => try sema.zirFunc(block, inst, true),
            .func_fancy                   => try sema.zirFuncFancy(block, inst),
            .import                       => try sema.zirImport(block, inst),
            .indexable_ptr_len            => try sema.zirIndexablePtrLen(block, inst),
            .int                          => try sema.zirInt(block, inst),
            .int_big                      => try sema.zirIntBig(block, inst),
            .float                        => try sema.zirFloat(block, inst),
            .float128                     => try sema.zirFloat128(block, inst),
            .int_type                     => try sema.zirIntType(block, inst),
            .is_non_err                   => try sema.zirIsNonErr(block, inst),
            .is_non_err_ptr               => try sema.zirIsNonErrPtr(block, inst),
            .ret_is_non_err               => try sema.zirRetIsNonErr(block, inst),
            .is_non_null                  => try sema.zirIsNonNull(block, inst),
            .is_non_null_ptr              => try sema.zirIsNonNullPtr(block, inst),
            .merge_error_sets             => try sema.zirMergeErrorSets(block, inst),
            .negate                       => try sema.zirNegate(block, inst),
            .negate_wrap                  => try sema.zirNegateWrap(block, inst),
            .optional_payload_safe        => try sema.zirOptionalPayload(block, inst, true),
            .optional_payload_safe_ptr    => try sema.zirOptionalPayloadPtr(block, inst, true),
            .optional_payload_unsafe      => try sema.zirOptionalPayload(block, inst, false),
            .optional_payload_unsafe_ptr  => try sema.zirOptionalPayloadPtr(block, inst, false),
            .optional_type                => try sema.zirOptionalType(block, inst),
            .ptr_type                     => try sema.zirPtrType(block, inst),
            .ref                          => try sema.zirRef(block, inst),
            .ret_err_value_code           => try sema.zirRetErrValueCode(inst),
            .shr                          => try sema.zirShr(block, inst, .shr),
            .shr_exact                    => try sema.zirShr(block, inst, .shr_exact),
            .slice_end                    => try sema.zirSliceEnd(block, inst),
            .slice_sentinel               => try sema.zirSliceSentinel(block, inst),
            .slice_start                  => try sema.zirSliceStart(block, inst),
            .str                          => try sema.zirStr(block, inst),
            .switch_block                 => try sema.zirSwitchBlock(block, inst),
            .switch_cond                  => try sema.zirSwitchCond(block, inst, false),
            .switch_cond_ref              => try sema.zirSwitchCond(block, inst, true),
            .switch_capture               => try sema.zirSwitchCapture(block, inst, false, false),
            .switch_capture_ref           => try sema.zirSwitchCapture(block, inst, false, true),
            .switch_capture_multi         => try sema.zirSwitchCapture(block, inst, true, false),
            .switch_capture_multi_ref     => try sema.zirSwitchCapture(block, inst, true, true),
            .switch_capture_tag           => try sema.zirSwitchCaptureTag(block, inst),
            .type_info                    => try sema.zirTypeInfo(block, inst),
            .size_of                      => try sema.zirSizeOf(block, inst),
            .bit_size_of                  => try sema.zirBitSizeOf(block, inst),
            .typeof                       => try sema.zirTypeof(block, inst),
            .typeof_builtin               => try sema.zirTypeofBuiltin(block, inst),
            .typeof_log2_int_type         => try sema.zirTypeofLog2IntType(block, inst),
            .xor                          => try sema.zirBitwise(block, inst, .xor),
            .struct_init_empty            => try sema.zirStructInitEmpty(block, inst),
            .struct_init                  => try sema.zirStructInit(block, inst, false),
            .struct_init_ref              => try sema.zirStructInit(block, inst, true),
            .struct_init_anon             => try sema.zirStructInitAnon(block, inst, false),
            .struct_init_anon_ref         => try sema.zirStructInitAnon(block, inst, true),
            .array_init                   => try sema.zirArrayInit(block, inst, false),
            .array_init_ref               => try sema.zirArrayInit(block, inst, true),
            .array_init_anon              => try sema.zirArrayInitAnon(block, inst, false),
            .array_init_anon_ref          => try sema.zirArrayInitAnon(block, inst, true),
            .union_init                   => try sema.zirUnionInit(block, inst),
            .field_type                   => try sema.zirFieldType(block, inst),
            .field_type_ref               => try sema.zirFieldTypeRef(block, inst),
            .ptr_to_int                   => try sema.zirPtrToInt(block, inst),
            .align_of                     => try sema.zirAlignOf(block, inst),
            .bool_to_int                  => try sema.zirBoolToInt(block, inst),
            .embed_file                   => try sema.zirEmbedFile(block, inst),
            .error_name                   => try sema.zirErrorName(block, inst),
            .tag_name                     => try sema.zirTagName(block, inst),
            .type_name                    => try sema.zirTypeName(block, inst),
            .frame_type                   => try sema.zirFrameType(block, inst),
            .frame_size                   => try sema.zirFrameSize(block, inst),
            .float_to_int                 => try sema.zirFloatToInt(block, inst),
            .int_to_float                 => try sema.zirIntToFloat(block, inst),
            .int_to_ptr                   => try sema.zirIntToPtr(block, inst),
            .float_cast                   => try sema.zirFloatCast(block, inst),
            .int_cast                     => try sema.zirIntCast(block, inst),
            .ptr_cast                     => try sema.zirPtrCast(block, inst),
            .truncate                     => try sema.zirTruncate(block, inst),
            .align_cast                   => try sema.zirAlignCast(block, inst),
            .has_decl                     => try sema.zirHasDecl(block, inst),
            .has_field                    => try sema.zirHasField(block, inst),
            .byte_swap                    => try sema.zirByteSwap(block, inst),
            .bit_reverse                  => try sema.zirBitReverse(block, inst),
            .bit_offset_of                => try sema.zirBitOffsetOf(block, inst),
            .offset_of                    => try sema.zirOffsetOf(block, inst),
            .splat                        => try sema.zirSplat(block, inst),
            .reduce                       => try sema.zirReduce(block, inst),
            .shuffle                      => try sema.zirShuffle(block, inst),
            .atomic_load                  => try sema.zirAtomicLoad(block, inst),
            .atomic_rmw                   => try sema.zirAtomicRmw(block, inst),
            .mul_add                      => try sema.zirMulAdd(block, inst),
            .builtin_call                 => try sema.zirBuiltinCall(block, inst),
            .field_parent_ptr             => try sema.zirFieldParentPtr(block, inst),
            .@"resume"                    => try sema.zirResume(block, inst),
            .@"await"                     => try sema.zirAwait(block, inst),
            .array_base_ptr               => try sema.zirArrayBasePtr(block, inst),
            .field_base_ptr               => try sema.zirFieldBasePtr(block, inst),
            .for_len                      => try sema.zirForLen(block, inst),

            .clz       => try sema.zirBitCount(block, inst, .clz,      Value.clz),
            .ctz       => try sema.zirBitCount(block, inst, .ctz,      Value.ctz),
            .pop_count => try sema.zirBitCount(block, inst, .popcount, Value.popCount),

            .sqrt  => try sema.zirUnaryMath(block, inst, .sqrt, Value.sqrt),
            .sin   => try sema.zirUnaryMath(block, inst, .sin, Value.sin),
            .cos   => try sema.zirUnaryMath(block, inst, .cos, Value.cos),
            .tan   => try sema.zirUnaryMath(block, inst, .tan, Value.tan),
            .exp   => try sema.zirUnaryMath(block, inst, .exp, Value.exp),
            .exp2  => try sema.zirUnaryMath(block, inst, .exp2, Value.exp2),
            .log   => try sema.zirUnaryMath(block, inst, .log, Value.log),
            .log2  => try sema.zirUnaryMath(block, inst, .log2, Value.log2),
            .log10 => try sema.zirUnaryMath(block, inst, .log10, Value.log10),
            .fabs  => try sema.zirUnaryMath(block, inst, .fabs, Value.fabs),
            .floor => try sema.zirUnaryMath(block, inst, .floor, Value.floor),
            .ceil  => try sema.zirUnaryMath(block, inst, .ceil, Value.ceil),
            .round => try sema.zirUnaryMath(block, inst, .round, Value.round),
            .trunc => try sema.zirUnaryMath(block, inst, .trunc_float, Value.trunc),

            .error_set_decl      => try sema.zirErrorSetDecl(block, inst, .parent),
            .error_set_decl_anon => try sema.zirErrorSetDecl(block, inst, .anon),
            .error_set_decl_func => try sema.zirErrorSetDecl(block, inst, .func),

            .add       => try sema.zirArithmetic(block, inst, .add,        true),
            .addwrap   => try sema.zirArithmetic(block, inst, .addwrap,    true),
            .add_sat   => try sema.zirArithmetic(block, inst, .add_sat,    true),
            .add_unsafe=> try sema.zirArithmetic(block, inst, .add_unsafe, false),
            .mul       => try sema.zirArithmetic(block, inst, .mul,        true),
            .mulwrap   => try sema.zirArithmetic(block, inst, .mulwrap,    true),
            .mul_sat   => try sema.zirArithmetic(block, inst, .mul_sat,    true),
            .sub       => try sema.zirArithmetic(block, inst, .sub,        true),
            .subwrap   => try sema.zirArithmetic(block, inst, .subwrap,    true),
            .sub_sat   => try sema.zirArithmetic(block, inst, .sub_sat,    true),

            .div       => try sema.zirDiv(block, inst),
            .div_exact => try sema.zirDivExact(block, inst),
            .div_floor => try sema.zirDivFloor(block, inst),
            .div_trunc => try sema.zirDivTrunc(block, inst),

            .mod_rem   => try sema.zirModRem(block, inst),
            .mod       => try sema.zirMod(block, inst),
            .rem       => try sema.zirRem(block, inst),

            .max => try sema.zirMinMax(block, inst, .max),
            .min => try sema.zirMinMax(block, inst, .min),

            .shl       => try sema.zirShl(block, inst, .shl),
            .shl_exact => try sema.zirShl(block, inst, .shl_exact),
            .shl_sat   => try sema.zirShl(block, inst, .shl_sat),

            .ret_ptr  => try sema.zirRetPtr(block),
            .ret_type => try sema.addType(sema.fn_ret_ty),

            // Instructions that we know to *always* be noreturn based solely on their tag.
            // These functions match the return type of analyzeBody so that we can
            // tail call them here.
            .compile_error  => break sema.zirCompileError(block, inst),
            .ret_implicit   => break sema.zirRetImplicit(block, inst),
            .ret_node       => break sema.zirRetNode(block, inst),
            .ret_load       => break sema.zirRetLoad(block, inst),
            .ret_err_value  => break sema.zirRetErrValue(block, inst),
            .@"unreachable" => break sema.zirUnreachable(block, inst),
            .panic          => break sema.zirPanic(block, inst, false),
            .panic_comptime => break sema.zirPanic(block, inst, true),
            .trap           => break sema.zirTrap(block, inst),
            // zig fmt: on

            .extended => ext: {
                const extended = datas[inst].extended;
                break :ext switch (extended.opcode) {
                    // zig fmt: off
                    .variable              => try sema.zirVarExtended(       block, extended),
                    .struct_decl           => try sema.zirStructDecl(        block, extended, inst),
                    .enum_decl             => try sema.zirEnumDecl(          block, extended, inst),
                    .union_decl            => try sema.zirUnionDecl(         block, extended, inst),
                    .opaque_decl           => try sema.zirOpaqueDecl(        block, extended, inst),
                    .this                  => try sema.zirThis(              block, extended),
                    .ret_addr              => try sema.zirRetAddr(           block, extended),
                    .builtin_src           => try sema.zirBuiltinSrc(        block, extended),
                    .error_return_trace    => try sema.zirErrorReturnTrace(  block),
                    .frame                 => try sema.zirFrame(             block, extended),
                    .frame_address         => try sema.zirFrameAddress(      block, extended),
                    .alloc                 => try sema.zirAllocExtended(     block, extended),
                    .builtin_extern        => try sema.zirBuiltinExtern(     block, extended),
                    .@"asm"                => try sema.zirAsm(               block, extended, false),
                    .asm_expr              => try sema.zirAsm(               block, extended, true),
                    .typeof_peer           => try sema.zirTypeofPeer(        block, extended),
                    .compile_log           => try sema.zirCompileLog(               extended),
                    .add_with_overflow     => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
                    .sub_with_overflow     => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
                    .mul_with_overflow     => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
                    .shl_with_overflow     => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
                    .c_undef               => try sema.zirCUndef(            block, extended),
                    .c_include             => try sema.zirCInclude(          block, extended),
                    .c_define              => try sema.zirCDefine(           block, extended),
                    .wasm_memory_size      => try sema.zirWasmMemorySize(    block, extended),
                    .wasm_memory_grow      => try sema.zirWasmMemoryGrow(    block, extended),
                    .prefetch              => try sema.zirPrefetch(          block, extended),
                    .field_call_bind_named => try sema.zirFieldCallBindNamed(block, extended),
                    .err_set_cast          => try sema.zirErrSetCast(        block, extended),
                    .await_nosuspend       => try sema.zirAwaitNosuspend(    block, extended),
                    .select                => try sema.zirSelect(            block, extended),
                    .error_to_int          => try sema.zirErrorToInt(        block, extended),
                    .int_to_error          => try sema.zirIntToError(        block, extended),
                    .reify                 => try sema.zirReify(             block, extended, inst),
                    .builtin_async_call    => try sema.zirBuiltinAsyncCall(  block, extended),
                    .cmpxchg               => try sema.zirCmpxchg(           block, extended),
                    .addrspace_cast        => try sema.zirAddrSpaceCast(     block, extended),
                    .c_va_arg              => try sema.zirCVaArg(            block, extended),
                    .c_va_copy             => try sema.zirCVaCopy(           block, extended),
                    .c_va_end              => try sema.zirCVaEnd(            block, extended),
                    .c_va_start            => try sema.zirCVaStart(          block, extended),
                    .const_cast,           => try sema.zirConstCast(         block, extended),
                    .volatile_cast,        => try sema.zirVolatileCast(      block, extended),
                    // zig fmt: on

                    .fence => {
                        try sema.zirFence(block, extended);
                        i += 1;
                        continue;
                    },
                    .set_float_mode => {
                        try sema.zirSetFloatMode(block, extended);
                        i += 1;
                        continue;
                    },
                    .set_align_stack => {
                        try sema.zirSetAlignStack(block, extended);
                        i += 1;
                        continue;
                    },
                    .set_cold => {
                        try sema.zirSetCold(block, extended);
                        i += 1;
                        continue;
                    },
                    .breakpoint => {
                        if (!block.is_comptime) {
                            _ = try block.addNoOp(.breakpoint);
                        }
                        i += 1;
                        continue;
                    },
                };
            },

            // Instructions that we know can *never* be noreturn based solely on
            // their tag. We avoid needlessly checking if they are noreturn and
            // continue the loop.
            // We also know that they cannot be referenced later, so we avoid
            // putting them into the map.
            .dbg_stmt => {
                try sema.zirDbgStmt(block, inst);
                i += 1;
                continue;
            },
            .dbg_var_ptr => {
                try sema.zirDbgVar(block, inst, .dbg_var_ptr);
                i += 1;
                continue;
            },
            .dbg_var_val => {
                try sema.zirDbgVar(block, inst, .dbg_var_val);
                i += 1;
                continue;
            },
            .dbg_block_begin => {
                dbg_block_begins += 1;
                try sema.zirDbgBlockBegin(block);
                i += 1;
                continue;
            },
            .dbg_block_end => {
                dbg_block_begins -= 1;
                try sema.zirDbgBlockEnd(block);
                i += 1;
                continue;
            },
            .ensure_err_union_payload_void => {
                try sema.zirEnsureErrUnionPayloadVoid(block, inst);
                i += 1;
                continue;
            },
            .ensure_result_non_error => {
                try sema.zirEnsureResultNonError(block, inst);
                i += 1;
                continue;
            },
            .ensure_result_used => {
                try sema.zirEnsureResultUsed(block, inst);
                i += 1;
                continue;
            },
            .set_eval_branch_quota => {
                try sema.zirSetEvalBranchQuota(block, inst);
                i += 1;
                continue;
            },
            .atomic_store => {
                try sema.zirAtomicStore(block, inst);
                i += 1;
                continue;
            },
            .store => {
                try sema.zirStore(block, inst);
                i += 1;
                continue;
            },
            .store_node => {
                try sema.zirStoreNode(block, inst);
                i += 1;
                continue;
            },
            .store_to_block_ptr => {
                try sema.zirStoreToBlockPtr(block, inst);
                i += 1;
                continue;
            },
            .store_to_inferred_ptr => {
                try sema.zirStoreToInferredPtr(block, inst);
                i += 1;
                continue;
            },
            .resolve_inferred_alloc => {
                try sema.zirResolveInferredAlloc(block, inst);
                i += 1;
                continue;
            },
            .validate_array_init_ty => {
                try sema.validateArrayInitTy(block, inst);
                i += 1;
                continue;
            },
            .validate_struct_init_ty => {
                try sema.validateStructInitTy(block, inst);
                i += 1;
                continue;
            },
            .validate_struct_init => {
                try sema.zirValidateStructInit(block, inst, false);
                i += 1;
                continue;
            },
            .validate_struct_init_comptime => {
                try sema.zirValidateStructInit(block, inst, true);
                i += 1;
                continue;
            },
            .validate_array_init => {
                try sema.zirValidateArrayInit(block, inst, false);
                i += 1;
                continue;
            },
            .validate_array_init_comptime => {
                try sema.zirValidateArrayInit(block, inst, true);
                i += 1;
                continue;
            },
            .validate_deref => {
                try sema.zirValidateDeref(block, inst);
                i += 1;
                continue;
            },
            .@"export" => {
                try sema.zirExport(block, inst);
                i += 1;
                continue;
            },
            .export_value => {
                try sema.zirExportValue(block, inst);
                i += 1;
                continue;
            },
            .set_runtime_safety => {
                try sema.zirSetRuntimeSafety(block, inst);
                i += 1;
                continue;
            },
            .param => {
                try sema.zirParam(block, inst, false);
                i += 1;
                continue;
            },
            .param_comptime => {
                try sema.zirParam(block, inst, true);
                i += 1;
                continue;
            },
            .param_anytype => {
                try sema.zirParamAnytype(block, inst, false);
                i += 1;
                continue;
            },
            .param_anytype_comptime => {
                try sema.zirParamAnytype(block, inst, true);
                i += 1;
                continue;
            },
            .closure_capture => {
                try sema.zirClosureCapture(block, inst);
                i += 1;
                continue;
            },
            .memcpy => {
                try sema.zirMemcpy(block, inst);
                i += 1;
                continue;
            },
            .memset => {
                try sema.zirMemset(block, inst);
                i += 1;
                continue;
            },
            .check_comptime_control_flow => {
                if (!block.is_comptime) {
                    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
                    const src = inst_data.src();
                    const inline_block = Zir.refToIndex(inst_data.operand).?;

                    var check_block = block;
                    const target_runtime_index = while (true) {
                        if (check_block.inline_block == inline_block) {
                            break check_block.runtime_index;
                        }
                        check_block = check_block.parent.?;
                    };

                    if (@enumToInt(target_runtime_index) < @enumToInt(block.runtime_index)) {
                        const runtime_src = block.runtime_cond orelse block.runtime_loop.?;
                        const msg = msg: {
                            const msg = try sema.errMsg(block, src, "comptime control flow inside runtime block", .{});
                            errdefer msg.destroy(sema.gpa);

                            try sema.errNote(block, runtime_src, msg, "runtime control flow here", .{});
                            break :msg msg;
                        };
                        return sema.failWithOwnedErrorMsg(msg);
                    }
                }
                i += 1;
                continue;
            },
            .save_err_ret_index => {
                try sema.zirSaveErrRetIndex(block, inst);
                i += 1;
                continue;
            },
            .restore_err_ret_index => {
                try sema.zirRestoreErrRetIndex(block, inst);
                i += 1;
                continue;
            },

            // Special case instructions to handle comptime control flow.
            .@"break" => {
                if (block.is_comptime) {
                    break inst; // same as break_inline
                } else {
                    break sema.zirBreak(block, inst);
                }
            },
            .break_inline => {
                if (block.is_comptime) {
                    break inst;
                } else {
                    sema.comptime_break_inst = inst;
                    return error.ComptimeBreak;
                }
            },
            .repeat => {
                if (block.is_comptime) {
                    // Send comptime control flow back to the beginning of this block.
                    const src = LazySrcLoc.nodeOffset(datas[inst].node);
                    try sema.emitBackwardBranch(block, src);
                    if (wip_captures.scope.captures.count() != orig_captures) {
                        try wip_captures.reset(parent_capture_scope);
                        block.wip_capture_scope = wip_captures.scope;
                        orig_captures = 0;
                    }
                    i = 0;
                    continue;
                } else {
                    break always_noreturn;
                }
            },
            .repeat_inline => {
                // Send comptime control flow back to the beginning of this block.
                const src = LazySrcLoc.nodeOffset(datas[inst].node);
                try sema.emitBackwardBranch(block, src);
                if (wip_captures.scope.captures.count() != orig_captures) {
                    try wip_captures.reset(parent_capture_scope);
                    block.wip_capture_scope = wip_captures.scope;
                    orig_captures = 0;
                }
                i = 0;
                continue;
            },
            .loop => blk: {
                if (!block.is_comptime) break :blk try sema.zirLoop(block, inst);
                // Same as `block_inline`. TODO https://github.com/ziglang/zig/issues/8220
                const inst_data = datas[inst].pl_node;
                const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
                const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
                const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
                    break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            .block => blk: {
                if (!block.is_comptime) break :blk try sema.zirBlock(block, inst);
                // Same as `block_inline`. TODO https://github.com/ziglang/zig/issues/8220
                const inst_data = datas[inst].pl_node;
                const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
                const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
                // If this block contains a function prototype, we need to reset the
                // current list of parameters and restore it later.
                // Note: this probably needs to be resolved in a more general manner.
                const prev_params = block.params;
                block.params = .{};
                defer {
                    block.params.deinit(sema.gpa);
                    block.params = prev_params;
                }
                const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
                    break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            .block_inline => blk: {
                // Directly analyze the block body without introducing a new block.
                // However, in the case of a corresponding break_inline which reaches
                // through a runtime conditional branch, we must retroactively emit
                // a block, so we remember the block index here just in case.
                const block_index = block.instructions.items.len;
                const inst_data = datas[inst].pl_node;
                const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
                const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
                const gpa = sema.gpa;

                const opt_break_data = b: {
                    // Create a temporary child block so that this inline block is properly
                    // labeled for any .restore_err_ret_index instructions
                    var child_block = block.makeSubBlock();

                    // If this block contains a function prototype, we need to reset the
                    // current list of parameters and restore it later.
                    // Note: this probably needs to be resolved in a more general manner.
                    child_block.inline_block =
                        if (tags[inline_body[inline_body.len - 1]] == .repeat_inline) inline_body[0] else inst;

                    var label: Block.Label = .{
                        .zir_block = inst,
                        .merges = undefined,
                    };
                    child_block.label = &label;
                    defer child_block.params.deinit(gpa);

                    // Write these instructions directly into the parent block
                    child_block.instructions = block.instructions;
                    defer block.instructions = child_block.instructions;

                    break :b try sema.analyzeBodyBreak(&child_block, inline_body);
                };

                // A runtime conditional branch that needs a post-hoc block to be
                // emitted communicates this by mapping the block index into the inst map.
                if (map.get(inst)) |new_block_ref| ph: {
                    // Comptime control flow populates the map, so we don't actually know
                    // if this is a post-hoc runtime block until we check the
                    // post_hoc_block map.
                    const new_block_inst = Air.refToIndex(new_block_ref) orelse break :ph;
                    const labeled_block = sema.post_hoc_blocks.get(new_block_inst) orelse
                        break :ph;

                    // In this case we need to move all the instructions starting at
                    // block_index from the current block into this new one.

                    if (opt_break_data) |break_data| {
                        // This is a comptime break which we now change to a runtime break
                        // since it crosses a runtime branch.
                        // It may pass through our currently being analyzed block_inline or it
                        // may point directly to it. In the latter case, this modifies the
                        // block that we are about to look up in the post_hoc_blocks map below.
                        try sema.addRuntimeBreak(block, break_data);
                    } else {
                        // Here the comptime control flow ends with noreturn; however
                        // we have runtime control flow continuing after this block.
                        // This branch is therefore handled by the `i += 1; continue;`
                        // logic below.
                    }

                    try labeled_block.block.instructions.appendSlice(gpa, block.instructions.items[block_index..]);
                    block.instructions.items.len = block_index;

                    const block_result = try sema.analyzeBlockBody(block, inst_data.src(), &labeled_block.block, &labeled_block.label.merges);
                    {
                        // Destroy the ad-hoc block entry so that it does not interfere with
                        // the next iteration of comptime control flow, if any.
                        labeled_block.destroy(gpa);
                        assert(sema.post_hoc_blocks.remove(new_block_inst));
                    }
                    map.putAssumeCapacity(inst, block_result);
                    i += 1;
                    continue;
                }

                const break_data = opt_break_data orelse break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            .condbr => blk: {
                if (!block.is_comptime) break sema.zirCondbr(block, inst);
                // Same as condbr_inline. TODO https://github.com/ziglang/zig/issues/8220
                const inst_data = datas[inst].pl_node;
                const cond_src: LazySrcLoc = .{ .node_offset_if_cond = inst_data.src_node };
                const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
                const then_body = sema.code.extra[extra.end..][0..extra.data.then_body_len];
                const else_body = sema.code.extra[extra.end + then_body.len ..][0..extra.data.else_body_len];
                const cond = sema.resolveInstConst(block, cond_src, extra.data.condition, "condition in comptime branch must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and block.comptime_reason != null) try block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
                const inline_body = if (cond.val.toBool()) then_body else else_body;

                try sema.maybeErrorUnwrapCondbr(block, inline_body, extra.data.condition, cond_src);
                const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
                    break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            .condbr_inline => blk: {
                const inst_data = datas[inst].pl_node;
                const cond_src: LazySrcLoc = .{ .node_offset_if_cond = inst_data.src_node };
                const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
                const then_body = sema.code.extra[extra.end..][0..extra.data.then_body_len];
                const else_body = sema.code.extra[extra.end + then_body.len ..][0..extra.data.else_body_len];
                const cond = sema.resolveInstConst(block, cond_src, extra.data.condition, "condition in comptime branch must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and block.comptime_reason != null) try block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
                const inline_body = if (cond.val.toBool()) then_body else else_body;

                try sema.maybeErrorUnwrapCondbr(block, inline_body, extra.data.condition, cond_src);
                const old_runtime_index = block.runtime_index;
                defer block.runtime_index = old_runtime_index;
                const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
                    break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            .@"try" => blk: {
                if (!block.is_comptime) break :blk try sema.zirTry(block, inst);
                const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
                const src = inst_data.src();
                const operand_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
                const extra = sema.code.extraData(Zir.Inst.Try, inst_data.payload_index);
                const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
                const err_union = try sema.resolveInst(extra.data.operand);
                const err_union_ty = sema.typeOf(err_union);
                if (err_union_ty.zigTypeTag() != .ErrorUnion) {
                    return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
                        err_union_ty.fmt(sema.mod),
                    });
                }
                const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
                assert(is_non_err != .none);
                const is_non_err_tv = sema.resolveInstConst(block, operand_src, is_non_err, "try operand inside comptime block must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and block.comptime_reason != null) try block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
                if (is_non_err_tv.val.toBool()) {
                    break :blk try sema.analyzeErrUnionPayload(block, src, err_union_ty, err_union, operand_src, false);
                }
                const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
                    break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            //.try_inline => blk: {
            //    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
            //    const src = inst_data.src();
            //    const operand_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
            //    const extra = sema.code.extraData(Zir.Inst.Try, inst_data.payload_index);
            //    const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
            //    const operand = try sema.resolveInst(extra.data.operand);
            //    const operand_ty = sema.typeOf(operand);
            //    const is_ptr = operand_ty.zigTypeTag() == .Pointer;
            //    const err_union = if (is_ptr)
            //        try sema.analyzeLoad(block, src, operand, operand_src)
            //    else
            //        operand;
            //    const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
            //    assert(is_non_err != .none);
            //    const is_non_err_tv = try sema.resolveInstConst(block, operand_src, is_non_err);
            //    if (is_non_err_tv.val.toBool()) {
            //        if (is_ptr) {
            //            break :blk try sema.analyzeErrUnionPayloadPtr(block, src, operand, false, false);
            //        } else {
            //            const err_union_ty = sema.typeOf(err_union);
            //            break :blk try sema.analyzeErrUnionPayload(block, src, err_union_ty, operand, operand_src, false);
            //        }
            //    }
            //    const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
            //        break always_noreturn;
            //    if (inst == break_data.block_inst) {
            //        break :blk try sema.resolveInst(break_data.operand);
            //    } else {
            //        break break_data.inst;
            //    }
            //},
            .try_ptr => blk: {
                if (!block.is_comptime) break :blk try sema.zirTryPtr(block, inst);
                const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
                const src = inst_data.src();
                const operand_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
                const extra = sema.code.extraData(Zir.Inst.Try, inst_data.payload_index);
                const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
                const operand = try sema.resolveInst(extra.data.operand);
                const err_union = try sema.analyzeLoad(block, src, operand, operand_src);
                const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
                assert(is_non_err != .none);
                const is_non_err_tv = sema.resolveInstConst(block, operand_src, is_non_err, "try operand inside comptime block must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and block.comptime_reason != null) try block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
                if (is_non_err_tv.val.toBool()) {
                    break :blk try sema.analyzeErrUnionPayloadPtr(block, src, operand, false, false);
                }
                const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
                    break always_noreturn;
                if (inst == break_data.block_inst) {
                    break :blk try sema.resolveInst(break_data.operand);
                } else {
                    break break_data.inst;
                }
            },
            //.try_ptr_inline => blk: {
            //    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
            //    const src = inst_data.src();
            //    const operand_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
            //    const extra = sema.code.extraData(Zir.Inst.Try, inst_data.payload_index);
            //    const inline_body = sema.code.extra[extra.end..][0..extra.data.body_len];
            //    const operand = try sema.resolveInst(extra.data.operand);
            //    const err_union = try sema.analyzeLoad(block, src, operand, operand_src);
            //    const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
            //    assert(is_non_err != .none);
            //    const is_non_err_tv = try sema.resolveInstConst(block, operand_src, is_non_err);
            //    if (is_non_err_tv.val.toBool()) {
            //        break :blk try sema.analyzeErrUnionPayloadPtr(block, src, operand, false, false);
            //    }
            //    const break_data = (try sema.analyzeBodyBreak(block, inline_body)) orelse
            //        break always_noreturn;
            //    if (inst == break_data.block_inst) {
            //        break :blk try sema.resolveInst(break_data.operand);
            //    } else {
            //        break break_data.inst;
            //    }
            //},
            .@"defer" => blk: {
                const inst_data = sema.code.instructions.items(.data)[inst].@"defer";
                const defer_body = sema.code.extra[inst_data.index..][0..inst_data.len];
                const break_inst = sema.analyzeBodyInner(block, defer_body) catch |err| switch (err) {
                    error.ComptimeBreak => sema.comptime_break_inst,
                    else => |e| return e,
                };
                if (break_inst != defer_body[defer_body.len - 1]) break always_noreturn;
                break :blk Air.Inst.Ref.void_value;
            },
            .defer_err_code => blk: {
                const inst_data = sema.code.instructions.items(.data)[inst].defer_err_code;
                const extra = sema.code.extraData(Zir.Inst.DeferErrCode, inst_data.payload_index).data;
                const defer_body = sema.code.extra[extra.index..][0..extra.len];
                const err_code = try sema.resolveInst(inst_data.err_code);
                sema.inst_map.putAssumeCapacity(extra.remapped_err_code, err_code);
                const break_inst = sema.analyzeBodyInner(block, defer_body) catch |err| switch (err) {
                    error.ComptimeBreak => sema.comptime_break_inst,
                    else => |e| return e,
                };
                if (break_inst != defer_body[defer_body.len - 1]) break always_noreturn;
                break :blk Air.Inst.Ref.void_value;
            },
        };
        if (sema.typeOf(air_inst).isNoReturn())
            break always_noreturn;
        map.putAssumeCapacity(inst, air_inst);
        i += 1;
    };

    // balance out dbg_block_begins in case of early noreturn
    const noreturn_inst = block.instructions.popOrNull();
    while (dbg_block_begins > 0) {
        dbg_block_begins -= 1;
        if (block.is_comptime or sema.mod.comp.bin_file.options.strip) continue;

        _ = try block.addInst(.{
            .tag = .dbg_block_end,
            .data = undefined,
        });
    }
    if (noreturn_inst) |some| try block.instructions.append(sema.gpa, some);

    if (!wip_captures.finalized) {
        try wip_captures.finalize();
        block.wip_capture_scope = parent_capture_scope;
    }

    return result;
}

pub fn resolveInst(sema: *Sema, zir_ref: Zir.Inst.Ref) !Air.Inst.Ref {
    var i: usize = @enumToInt(zir_ref);

    // First section of indexes correspond to a set number of constant values.
    if (i < Zir.Inst.Ref.typed_value_map.len) {
        // We intentionally map the same indexes to the same values between ZIR and AIR.
        return zir_ref;
    }
    i -= Zir.Inst.Ref.typed_value_map.len;

    // Finally, the last section of indexes refers to the map of ZIR=>AIR.
    const inst = sema.inst_map.get(@intCast(u32, i)).?;
    const ty = sema.typeOf(inst);
    if (ty.tag() == .generic_poison) return error.GenericPoison;
    return inst;
}

fn resolveConstBool(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    reason: []const u8,
) !bool {
    const air_inst = try sema.resolveInst(zir_ref);
    const wanted_type = Type.bool;
    const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
    const val = try sema.resolveConstValue(block, src, coerced_inst, reason);
    return val.toBool();
}

pub fn resolveConstString(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    reason: []const u8,
) ![]u8 {
    const air_inst = try sema.resolveInst(zir_ref);
    const wanted_type = Type.initTag(.const_slice_u8);
    const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
    const val = try sema.resolveConstValue(block, src, coerced_inst, reason);
    return val.toAllocatedBytes(wanted_type, sema.arena, sema.mod);
}

pub fn resolveType(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) !Type {
    const air_inst = try sema.resolveInst(zir_ref);
    const ty = try sema.analyzeAsType(block, src, air_inst);
    if (ty.tag() == .generic_poison) return error.GenericPoison;
    return ty;
}

fn analyzeAsType(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    air_inst: Air.Inst.Ref,
) !Type {
    const wanted_type = Type.initTag(.type);
    const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
    const val = try sema.resolveConstValue(block, src, coerced_inst, "types must be comptime-known");
    var buffer: Value.ToTypeBuffer = undefined;
    const ty = val.toType(&buffer);
    return ty.copy(sema.arena);
}

pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize) !void {
    if (!sema.mod.backendSupportsFeature(.error_return_trace)) return;

    assert(!block.is_comptime);
    var err_trace_block = block.makeSubBlock();
    defer err_trace_block.instructions.deinit(sema.gpa);

    const src: LazySrcLoc = .unneeded;

    // var addrs: [err_return_trace_addr_count]usize = undefined;
    const err_return_trace_addr_count = 32;
    const addr_arr_ty = try Type.array(sema.arena, err_return_trace_addr_count, null, Type.usize, sema.mod);
    const addrs_ptr = try err_trace_block.addTy(.alloc, try Type.Tag.single_mut_pointer.create(sema.arena, addr_arr_ty));

    // var st: StackTrace = undefined;
    const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
    const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
    const st_ptr = try err_trace_block.addTy(.alloc, try Type.Tag.single_mut_pointer.create(sema.arena, stack_trace_ty));

    // st.instruction_addresses = &addrs;
    const addr_field_ptr = try sema.fieldPtr(&err_trace_block, src, st_ptr, "instruction_addresses", src, true);
    try sema.storePtr2(&err_trace_block, src, addr_field_ptr, src, addrs_ptr, src, .store);

    // st.index = 0;
    const index_field_ptr = try sema.fieldPtr(&err_trace_block, src, st_ptr, "index", src, true);
    try sema.storePtr2(&err_trace_block, src, index_field_ptr, src, .zero_usize, src, .store);

    // @errorReturnTrace() = &st;
    _ = try err_trace_block.addUnOp(.set_err_return_trace, st_ptr);

    try block.instructions.insertSlice(sema.gpa, last_arg_index, err_trace_block.instructions.items);
}

/// May return Value Tags: `variable`, `undef`.
/// See `resolveConstValue` for an alternative.
/// Value Tag `generic_poison` causes `error.GenericPoison` to be returned.
fn resolveValue(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    air_ref: Air.Inst.Ref,
    reason: []const u8,
) CompileError!Value {
    if (try sema.resolveMaybeUndefValAllowVariables(air_ref)) |val| {
        if (val.tag() == .generic_poison) return error.GenericPoison;
        return val;
    }
    return sema.failWithNeededComptime(block, src, reason);
}

/// Value Tag `variable` will cause a compile error.
/// Value Tag `undef` may be returned.
fn resolveConstMaybeUndefVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    inst: Air.Inst.Ref,
    reason: []const u8,
) CompileError!Value {
    if (try sema.resolveMaybeUndefValAllowVariables(inst)) |val| {
        switch (val.tag()) {
            .variable => return sema.failWithNeededComptime(block, src, reason),
            .generic_poison => return error.GenericPoison,
            else => return val,
        }
    }
    return sema.failWithNeededComptime(block, src, reason);
}

/// Will not return Value Tags: `variable`, `undef`. Instead they will emit compile errors.
/// See `resolveValue` for an alternative.
fn resolveConstValue(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    air_ref: Air.Inst.Ref,
    reason: []const u8,
) CompileError!Value {
    if (try sema.resolveMaybeUndefValAllowVariables(air_ref)) |val| {
        switch (val.tag()) {
            .undef => return sema.failWithUseOfUndef(block, src),
            .variable => return sema.failWithNeededComptime(block, src, reason),
            .generic_poison => return error.GenericPoison,
            else => return val,
        }
    }
    return sema.failWithNeededComptime(block, src, reason);
}

/// Value Tag `variable` causes this function to return `null`.
/// Value Tag `undef` causes this function to return a compile error.
fn resolveDefinedValue(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    air_ref: Air.Inst.Ref,
) CompileError!?Value {
    if (try sema.resolveMaybeUndefVal(air_ref)) |val| {
        if (val.isUndef()) {
            if (block.is_typeof) return null;
            return sema.failWithUseOfUndef(block, src);
        }
        return val;
    }
    return null;
}

/// Value Tag `variable` causes this function to return `null`.
/// Value Tag `undef` causes this function to return the Value.
/// Value Tag `generic_poison` causes `error.GenericPoison` to be returned.
fn resolveMaybeUndefVal(
    sema: *Sema,
    inst: Air.Inst.Ref,
) CompileError!?Value {
    const val = (try sema.resolveMaybeUndefValAllowVariables(inst)) orelse return null;
    switch (val.tag()) {
        .variable => return null,
        .generic_poison => return error.GenericPoison,
        else => return val,
    }
}

/// Value Tag `variable` results in `null`.
/// Value Tag `undef` results in the Value.
/// Value Tag `generic_poison` causes `error.GenericPoison` to be returned.
/// Value Tag `decl_ref` and `decl_ref_mut` or any nested such value results in `null`.
fn resolveMaybeUndefValIntable(
    sema: *Sema,
    inst: Air.Inst.Ref,
) CompileError!?Value {
    const val = (try sema.resolveMaybeUndefValAllowVariables(inst)) orelse return null;
    var check = val;
    while (true) switch (check.tag()) {
        .variable, .decl_ref, .decl_ref_mut, .comptime_field_ptr => return null,
        .field_ptr => check = check.castTag(.field_ptr).?.data.container_ptr,
        .elem_ptr => check = check.castTag(.elem_ptr).?.data.array_ptr,
        .eu_payload_ptr, .opt_payload_ptr => check = check.cast(Value.Payload.PayloadPtr).?.data.container_ptr,
        .generic_poison => return error.GenericPoison,
        else => {
            try sema.resolveLazyValue(val);
            return val;
        },
    };
}

/// Returns all Value tags including `variable` and `undef`.
fn resolveMaybeUndefValAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
    var make_runtime = false;
    if (try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(inst, &make_runtime)) |val| {
        if (make_runtime) return null;
        return val;
    }
    return null;
}

/// Returns all Value tags including `variable`, `undef` and `runtime_value`.
fn resolveMaybeUndefValAllowVariablesMaybeRuntime(
    sema: *Sema,
    inst: Air.Inst.Ref,
    make_runtime: *bool,
) CompileError!?Value {
    // First section of indexes correspond to a set number of constant values.
    var i: usize = @enumToInt(inst);
    if (i < Air.Inst.Ref.typed_value_map.len) {
        return Air.Inst.Ref.typed_value_map[i].val;
    }
    i -= Air.Inst.Ref.typed_value_map.len;

    const air_tags = sema.air_instructions.items(.tag);
    if (try sema.typeHasOnePossibleValue(sema.typeOf(inst))) |opv| {
        if (air_tags[i] == .constant) {
            const ty_pl = sema.air_instructions.items(.data)[i].ty_pl;
            const val = sema.air_values.items[ty_pl.payload];
            if (val.tag() == .variable) return val;
        }
        return opv;
    }
    switch (air_tags[i]) {
        .constant => {
            const ty_pl = sema.air_instructions.items(.data)[i].ty_pl;
            const val = sema.air_values.items[ty_pl.payload];
            if (val.tag() == .runtime_value) make_runtime.* = true;
            if (val.isPtrToThreadLocal(sema.mod)) make_runtime.* = true;
            return val;
        },
        .const_ty => {
            return try sema.air_instructions.items(.data)[i].ty.toValue(sema.arena);
        },
        else => return null,
    }
}

fn failWithNeededComptime(sema: *Sema, block: *Block, src: LazySrcLoc, reason: []const u8) CompileError {
    const msg = msg: {
        const msg = try sema.errMsg(block, src, "unable to resolve comptime value", .{});
        errdefer msg.destroy(sema.gpa);

        try sema.errNote(block, src, msg, "{s}", .{reason});
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn failWithUseOfUndef(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError {
    return sema.fail(block, src, "use of undefined value here causes undefined behavior", .{});
}

fn failWithDivideByZero(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError {
    return sema.fail(block, src, "division by zero here causes undefined behavior", .{});
}

fn failWithModRemNegative(sema: *Sema, block: *Block, src: LazySrcLoc, lhs_ty: Type, rhs_ty: Type) CompileError {
    return sema.fail(block, src, "remainder division with '{}' and '{}': signed integers and floats must use @rem or @mod", .{
        lhs_ty.fmt(sema.mod), rhs_ty.fmt(sema.mod),
    });
}

fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, optional_ty: Type) CompileError {
    return sema.fail(block, src, "expected optional type, found '{}'", .{optional_ty.fmt(sema.mod)});
}

fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
    const msg = msg: {
        const msg = try sema.errMsg(block, src, "type '{}' does not support array initialization syntax", .{
            ty.fmt(sema.mod),
        });
        errdefer msg.destroy(sema.gpa);
        if (ty.isSlice()) {
            try sema.errNote(block, src, msg, "inferred array length is specified with an underscore: '[_]{}'", .{ty.elemType2().fmt(sema.mod)});
        }
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn failWithStructInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
    return sema.fail(block, src, "type '{}' does not support struct initialization syntax", .{
        ty.fmt(sema.mod),
    });
}

fn failWithErrorSetCodeMissing(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    dest_err_set_ty: Type,
    src_err_set_ty: Type,
) CompileError {
    return sema.fail(block, src, "expected type '{}', found type '{}'", .{
        dest_err_set_ty.fmt(sema.mod), src_err_set_ty.fmt(sema.mod),
    });
}

fn failWithIntegerOverflow(sema: *Sema, block: *Block, src: LazySrcLoc, int_ty: Type, val: Value, vector_index: usize) CompileError {
    if (int_ty.zigTypeTag() == .Vector) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "overflow of vector type '{}' with value '{}'", .{
                int_ty.fmt(sema.mod), val.fmtValue(int_ty, sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, src, msg, "when computing vector element at index '{d}'", .{vector_index});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    return sema.fail(block, src, "overflow of integer type '{}' with value '{}'", .{
        int_ty.fmt(sema.mod), val.fmtValue(int_ty, sema.mod),
    });
}

fn failWithInvalidComptimeFieldStore(sema: *Sema, block: *Block, init_src: LazySrcLoc, container_ty: Type, field_index: usize) CompileError {
    const msg = msg: {
        const msg = try sema.errMsg(block, init_src, "value stored in comptime field does not match the default value of the field", .{});
        errdefer msg.destroy(sema.gpa);

        const struct_ty = container_ty.castTag(.@"struct") orelse break :msg msg;
        const default_value_src = struct_ty.data.fieldSrcLoc(sema.mod, .{
            .index = field_index,
            .range = .value,
        });
        try sema.mod.errNoteNonLazy(default_value_src, msg, "default value set here", .{});
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn failWithUseOfAsync(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError {
    const msg = msg: {
        const msg = try sema.errMsg(block, src, "async has not been implemented in the self-hosted compiler yet", .{});
        errdefer msg.destroy(sema.gpa);
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

/// We don't return a pointer to the new error note because the pointer
/// becomes invalid when you add another one.
fn errNote(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    parent: *Module.ErrorMsg,
    comptime format: []const u8,
    args: anytype,
) error{OutOfMemory}!void {
    const mod = sema.mod;
    const src_decl = mod.declPtr(block.src_decl);
    return mod.errNoteNonLazy(src.toSrcLoc(src_decl), parent, format, args);
}

fn addFieldErrNote(
    sema: *Sema,
    container_ty: Type,
    field_index: usize,
    parent: *Module.ErrorMsg,
    comptime format: []const u8,
    args: anytype,
) !void {
    @setCold(true);
    const mod = sema.mod;
    const decl_index = container_ty.getOwnerDecl();
    const decl = mod.declPtr(decl_index);

    const field_src = blk: {
        const tree = decl.getFileScope().getTree(sema.gpa) catch |err| {
            log.err("unable to load AST to report compile error: {s}", .{@errorName(err)});
            break :blk decl.srcLoc();
        };

        const container_node = decl.relativeToNodeIndex(0);
        const node_tags = tree.nodes.items(.tag);
        var buf: [2]std.zig.Ast.Node.Index = undefined;
        const container_decl = tree.fullContainerDecl(&buf, container_node) orelse break :blk decl.srcLoc();

        var it_index: usize = 0;
        for (container_decl.ast.members) |member_node| {
            switch (node_tags[member_node]) {
                .container_field_init,
                .container_field_align,
                .container_field,
                => {
                    if (it_index == field_index) {
                        break :blk decl.nodeOffsetSrcLoc(decl.nodeIndexToRelative(member_node));
                    }
                    it_index += 1;
                },
                else => continue,
            }
        }
        unreachable;
    };
    try mod.errNoteNonLazy(field_src, parent, format, args);
}

fn errMsg(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    comptime format: []const u8,
    args: anytype,
) error{OutOfMemory}!*Module.ErrorMsg {
    const mod = sema.mod;
    const src_decl = mod.declPtr(block.src_decl);
    return Module.ErrorMsg.create(sema.gpa, src.toSrcLoc(src_decl), format, args);
}

pub fn fail(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    comptime format: []const u8,
    args: anytype,
) CompileError {
    const err_msg = try sema.errMsg(block, src, format, args);
    return sema.failWithOwnedErrorMsg(err_msg);
}

fn failWithOwnedErrorMsg(sema: *Sema, err_msg: *Module.ErrorMsg) CompileError {
    @setCold(true);
    const gpa = sema.gpa;

    if (crash_report.is_enabled and sema.mod.comp.debug_compile_errors) {
        if (err_msg.src_loc.lazy == .unneeded) return error.NeededSourceLocation;
        var wip_errors: std.zig.ErrorBundle.Wip = undefined;
        wip_errors.init(gpa) catch unreachable;
        Compilation.addModuleErrorMsg(&wip_errors, err_msg.*) catch unreachable;
        std.debug.print("compile error during Sema:\n", .{});
        var error_bundle = wip_errors.toOwnedBundle("") catch unreachable;
        error_bundle.renderToStdErr(.{ .ttyconf = .no_color });
        crash_report.compilerPanic("unexpected compile error occurred", null, null);
    }

    const mod = sema.mod;
    ref: {
        errdefer err_msg.destroy(gpa);
        if (err_msg.src_loc.lazy == .unneeded) {
            return error.NeededSourceLocation;
        }
        try mod.failed_decls.ensureUnusedCapacity(gpa, 1);
        try mod.failed_files.ensureUnusedCapacity(gpa, 1);

        const max_references = blk: {
            if (sema.mod.comp.reference_trace) |num| break :blk num;
            // Do not add multiple traces without explicit request.
            if (sema.mod.failed_decls.count() != 0) break :ref;
            break :blk default_reference_trace_len;
        };

        var referenced_by = if (sema.func) |some| some.owner_decl else sema.owner_decl_index;
        var reference_stack = std.ArrayList(Module.ErrorMsg.Trace).init(gpa);
        defer reference_stack.deinit();

        // Avoid infinite loops.
        var seen = std.AutoHashMap(Module.Decl.Index, void).init(gpa);
        defer seen.deinit();

        var cur_reference_trace: u32 = 0;
        while (sema.mod.reference_table.get(referenced_by)) |ref| : (cur_reference_trace += 1) {
            const gop = try seen.getOrPut(ref.referencer);
            if (gop.found_existing) break;
            if (cur_reference_trace < max_references) {
                const decl = sema.mod.declPtr(ref.referencer);
                try reference_stack.append(.{ .decl = decl.name, .src_loc = ref.src.toSrcLoc(decl) });
            }
            referenced_by = ref.referencer;
        }
        if (sema.mod.comp.reference_trace == null and cur_reference_trace > 0) {
            try reference_stack.append(.{
                .decl = null,
                .src_loc = undefined,
                .hidden = 0,
            });
        } else if (cur_reference_trace > max_references) {
            try reference_stack.append(.{
                .decl = undefined,
                .src_loc = undefined,
                .hidden = cur_reference_trace - max_references,
            });
        }
        err_msg.reference_trace = try reference_stack.toOwnedSlice();
    }
    if (sema.owner_func) |func| {
        func.state = .sema_failure;
    } else {
        sema.owner_decl.analysis = .sema_failure;
        sema.owner_decl.generation = mod.generation;
    }
    if (sema.func) |func| {
        func.state = .sema_failure;
    }
    const gop = mod.failed_decls.getOrPutAssumeCapacity(sema.owner_decl_index);
    if (gop.found_existing) {
        // If there are multiple errors for the same Decl, prefer the first one added.
        sema.err = null;
        err_msg.destroy(gpa);
    } else {
        sema.err = err_msg;
        gop.value_ptr.* = err_msg;
    }
    return error.AnalysisFail;
}

const align_ty = Type.u29;

fn analyzeAsAlign(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    air_ref: Air.Inst.Ref,
) !u32 {
    const alignment_big = try sema.analyzeAsInt(block, src, air_ref, align_ty, "alignment must be comptime-known");
    const alignment = @intCast(u32, alignment_big); // We coerce to u16 in the prev line.
    try sema.validateAlign(block, src, alignment);
    return alignment;
}

fn validateAlign(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    alignment: u32,
) !void {
    if (alignment == 0) return sema.fail(block, src, "alignment must be >= 1", .{});
    if (!std.math.isPowerOfTwo(alignment)) {
        return sema.fail(block, src, "alignment value '{d}' is not a power of two", .{
            alignment,
        });
    }
}

pub fn resolveAlign(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
) !u32 {
    const air_ref = try sema.resolveInst(zir_ref);
    return sema.analyzeAsAlign(block, src, air_ref);
}

fn resolveInt(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    dest_ty: Type,
    reason: []const u8,
) !u64 {
    const air_ref = try sema.resolveInst(zir_ref);
    return sema.analyzeAsInt(block, src, air_ref, dest_ty, reason);
}

fn analyzeAsInt(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    air_ref: Air.Inst.Ref,
    dest_ty: Type,
    reason: []const u8,
) !u64 {
    const coerced = try sema.coerce(block, dest_ty, air_ref, src);
    const val = try sema.resolveConstValue(block, src, coerced, reason);
    const target = sema.mod.getTarget();
    return (try val.getUnsignedIntAdvanced(target, sema)).?;
}

// Returns a compile error if the value has tag `variable`. See `resolveInstValue` for
// a function that does not.
pub fn resolveInstConst(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    reason: []const u8,
) CompileError!TypedValue {
    const air_ref = try sema.resolveInst(zir_ref);
    const val = try sema.resolveConstValue(block, src, air_ref, reason);
    return TypedValue{
        .ty = sema.typeOf(air_ref),
        .val = val,
    };
}

// Value Tag may be `undef` or `variable`.
// See `resolveInstConst` for an alternative.
pub fn resolveInstValue(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    reason: []const u8,
) CompileError!TypedValue {
    const air_ref = try sema.resolveInst(zir_ref);
    const val = try sema.resolveValue(block, src, air_ref, reason);
    return TypedValue{
        .ty = sema.typeOf(air_ref),
        .val = val,
    };
}

fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const pointee_ty = try sema.resolveType(block, src, extra.lhs);
    const ptr = try sema.resolveInst(extra.rhs);
    const target = sema.mod.getTarget();
    const addr_space = target_util.defaultAddressSpace(target, .local);

    if (Air.refToIndex(ptr)) |ptr_inst| {
        if (sema.air_instructions.items(.tag)[ptr_inst] == .constant) {
            const air_datas = sema.air_instructions.items(.data);
            const ptr_val = sema.air_values.items[air_datas[ptr_inst].ty_pl.payload];
            switch (ptr_val.tag()) {
                .inferred_alloc => {
                    const inferred_alloc = &ptr_val.castTag(.inferred_alloc).?.data;
                    // Add the stored instruction to the set we will use to resolve peer types
                    // for the inferred allocation.
                    // This instruction will not make it to codegen; it is only to participate
                    // in the `stored_inst_list` of the `inferred_alloc`.
                    var trash_block = block.makeSubBlock();
                    defer trash_block.instructions.deinit(sema.gpa);
                    const operand = try trash_block.addBitCast(pointee_ty, .void_value);

                    const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                        .pointee_type = pointee_ty,
                        .@"align" = inferred_alloc.alignment,
                        .@"addrspace" = addr_space,
                    });
                    const bitcasted_ptr = try block.addBitCast(ptr_ty, ptr);

                    try inferred_alloc.prongs.append(sema.arena, .{
                        .stored_inst = operand,
                        .placeholder = Air.refToIndex(bitcasted_ptr).?,
                    });

                    return bitcasted_ptr;
                },
                .inferred_alloc_comptime => {
                    const iac = ptr_val.castTag(.inferred_alloc_comptime).?;
                    // There will be only one coerce_result_ptr because we are running at comptime.
                    // The alloc will turn into a Decl.
                    var anon_decl = try block.startAnonDecl();
                    defer anon_decl.deinit();
                    iac.data.decl_index = try anon_decl.finish(
                        try pointee_ty.copy(anon_decl.arena()),
                        Value.undef,
                        iac.data.alignment,
                    );
                    if (iac.data.alignment != 0) {
                        try sema.resolveTypeLayout(pointee_ty);
                    }
                    const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                        .pointee_type = pointee_ty,
                        .@"align" = iac.data.alignment,
                        .@"addrspace" = addr_space,
                    });
                    return sema.addConstant(
                        ptr_ty,
                        try Value.Tag.decl_ref_mut.create(sema.arena, .{
                            .decl_index = iac.data.decl_index,
                            .runtime_index = block.runtime_index,
                        }),
                    );
                },
                else => {},
            }
        }
    }

    // Make a dummy store through the pointer to test the coercion.
    // We will then use the generated instructions to decide what
    // kind of transformations to make on the result pointer.
    var trash_block = block.makeSubBlock();
    trash_block.is_comptime = false;
    trash_block.is_coerce_result_ptr = true;
    defer trash_block.instructions.deinit(sema.gpa);

    const dummy_ptr = try trash_block.addTy(.alloc, sema.typeOf(ptr));
    const dummy_operand = try trash_block.addBitCast(pointee_ty, .void_value);
    return sema.coerceResultPtr(block, src, ptr, dummy_ptr, dummy_operand, &trash_block);
}

fn coerceResultPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    dummy_ptr: Air.Inst.Ref,
    dummy_operand: Air.Inst.Ref,
    trash_block: *Block,
) CompileError!Air.Inst.Ref {
    const target = sema.mod.getTarget();
    const addr_space = target_util.defaultAddressSpace(target, .local);
    const pointee_ty = sema.typeOf(dummy_operand);
    const prev_trash_len = trash_block.instructions.items.len;

    try sema.storePtr2(trash_block, src, dummy_ptr, src, dummy_operand, src, .bitcast);

    {
        const air_tags = sema.air_instructions.items(.tag);

        //std.debug.print("dummy storePtr instructions:\n", .{});
        //for (trash_block.instructions.items) |item| {
        //    std.debug.print("  {s}\n", .{@tagName(air_tags[item])});
        //}

        // The last one is always `store`.
        const trash_inst = trash_block.instructions.items[trash_block.instructions.items.len - 1];
        if (air_tags[trash_inst] != .store) {
            // no store instruction is generated for zero sized types
            assert((try sema.typeHasOnePossibleValue(pointee_ty)) != null);
        } else {
            trash_block.instructions.items.len -= 1;
            assert(trash_inst == sema.air_instructions.len - 1);
            sema.air_instructions.len -= 1;
        }
    }

    const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = pointee_ty,
        .@"addrspace" = addr_space,
    });

    var new_ptr = ptr;

    while (true) {
        const air_tags = sema.air_instructions.items(.tag);
        const air_datas = sema.air_instructions.items(.data);

        if (trash_block.instructions.items.len == prev_trash_len) {
            if (try sema.resolveDefinedValue(block, src, new_ptr)) |ptr_val| {
                return sema.addConstant(ptr_ty, ptr_val);
            }
            if (pointee_ty.eql(Type.null, sema.mod)) {
                const opt_ty = sema.typeOf(new_ptr).childType();
                const null_inst = try sema.addConstant(opt_ty, Value.null);
                _ = try block.addBinOp(.store, new_ptr, null_inst);
                return Air.Inst.Ref.void_value;
            }
            return sema.bitCast(block, ptr_ty, new_ptr, src, null);
        }

        const trash_inst = trash_block.instructions.pop();

        switch (air_tags[trash_inst]) {
            .bitcast => {
                const ty_op = air_datas[trash_inst].ty_op;
                const operand_ty = sema.typeOf(ty_op.operand);
                const ptr_operand_ty = try Type.ptr(sema.arena, sema.mod, .{
                    .pointee_type = operand_ty,
                    .@"addrspace" = addr_space,
                });
                if (try sema.resolveDefinedValue(block, src, new_ptr)) |ptr_val| {
                    new_ptr = try sema.addConstant(ptr_operand_ty, ptr_val);
                } else {
                    new_ptr = try sema.bitCast(block, ptr_operand_ty, new_ptr, src, null);
                }
            },
            .wrap_optional => {
                new_ptr = try sema.analyzeOptionalPayloadPtr(block, src, new_ptr, false, true);
            },
            .wrap_errunion_err => {
                return sema.fail(block, src, "TODO coerce_result_ptr wrap_errunion_err", .{});
            },
            .wrap_errunion_payload => {
                new_ptr = try sema.analyzeErrUnionPayloadPtr(block, src, new_ptr, false, true);
            },
            .array_to_slice => {
                return sema.fail(block, src, "TODO coerce_result_ptr array_to_slice", .{});
            },
            else => {
                if (std.debug.runtime_safety) {
                    std.debug.panic("unexpected AIR tag for coerce_result_ptr: {}", .{
                        air_tags[trash_inst],
                    });
                } else {
                    unreachable;
                }
            },
        }
    }
}

pub fn analyzeStructDecl(
    sema: *Sema,
    new_decl: *Decl,
    inst: Zir.Inst.Index,
    struct_obj: *Module.Struct,
) SemaError!void {
    const extended = sema.code.instructions.items(.data)[inst].extended;
    assert(extended.opcode == .struct_decl);
    const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);

    struct_obj.known_non_opv = small.known_non_opv;
    if (small.known_comptime_only) {
        struct_obj.requires_comptime = .yes;
    }

    var extra_index: usize = extended.operand;
    extra_index += @boolToInt(small.has_src_node);
    extra_index += @boolToInt(small.has_fields_len);
    const decls_len = if (small.has_decls_len) blk: {
        const decls_len = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk decls_len;
    } else 0;

    if (small.has_backing_int) {
        const backing_int_body_len = sema.code.extra[extra_index];
        extra_index += 1; // backing_int_body_len
        if (backing_int_body_len == 0) {
            extra_index += 1; // backing_int_ref
        } else {
            extra_index += backing_int_body_len; // backing_int_body_inst
        }
    }

    _ = try sema.mod.scanNamespace(&struct_obj.namespace, extra_index, decls_len, new_decl);
}

fn zirStructDecl(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);
    const src: LazySrcLoc = if (small.has_src_node) blk: {
        const node_offset = @bitCast(i32, sema.code.extra[extended.operand]);
        break :blk LazySrcLoc.nodeOffset(node_offset);
    } else sema.src;

    var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const mod = sema.mod;
    const struct_obj = try new_decl_arena_allocator.create(Module.Struct);
    const struct_ty = try Type.Tag.@"struct".create(new_decl_arena_allocator, struct_obj);
    const struct_val = try Value.Tag.ty.create(new_decl_arena_allocator, struct_ty);
    const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
        .ty = Type.type,
        .val = struct_val,
    }, small.name_strategy, "struct", inst);
    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer mod.abortAnonDecl(new_decl_index);
    struct_obj.* = .{
        .owner_decl = new_decl_index,
        .fields = .{},
        .zir_index = inst,
        .layout = small.layout,
        .status = .none,
        .known_non_opv = undefined,
        .is_tuple = small.is_tuple,
        .namespace = .{
            .parent = block.namespace,
            .ty = struct_ty,
            .file_scope = block.getFileScope(),
        },
    };
    std.log.scoped(.module).debug("create struct {*} owned by {*} ({s})", .{
        &struct_obj.namespace, new_decl, new_decl.name,
    });
    try sema.analyzeStructDecl(new_decl, inst, struct_obj);
    try new_decl.finalizeNewArena(&new_decl_arena);
    return sema.analyzeDeclVal(block, src, new_decl_index);
}

fn createAnonymousDeclTypeNamed(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    typed_value: TypedValue,
    name_strategy: Zir.Inst.NameStrategy,
    anon_prefix: []const u8,
    inst: ?Zir.Inst.Index,
) !Decl.Index {
    const mod = sema.mod;
    const namespace = block.namespace;
    const src_scope = block.wip_capture_scope;
    const src_decl = mod.declPtr(block.src_decl);
    const src_node = src_decl.relativeToNodeIndex(src.node_offset.x);
    const new_decl_index = try mod.allocateNewDecl(namespace, src_node, src_scope);
    errdefer mod.destroyDecl(new_decl_index);

    switch (name_strategy) {
        .anon => {
            // It would be neat to have "struct:line:column" but this name has
            // to survive incremental updates, where it may have been shifted down
            // or up to a different line, but unchanged, and thus not unnecessarily
            // semantically analyzed.
            // This name is also used as the key in the parent namespace so it cannot be
            // renamed.
            const name = try std.fmt.allocPrintZ(sema.gpa, "{s}__{s}_{d}", .{
                src_decl.name, anon_prefix, @enumToInt(new_decl_index),
            });
            errdefer sema.gpa.free(name);
            try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
            return new_decl_index;
        },
        .parent => {
            const name = try sema.gpa.dupeZ(u8, mem.sliceTo(sema.mod.declPtr(block.src_decl).name, 0));
            errdefer sema.gpa.free(name);
            try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
            return new_decl_index;
        },
        .func => {
            const fn_info = sema.code.getFnInfo(sema.func.?.zir_body_inst);
            const zir_tags = sema.code.instructions.items(.tag);

            var buf = std.ArrayList(u8).init(sema.gpa);
            defer buf.deinit();
            try buf.appendSlice(mem.sliceTo(sema.mod.declPtr(block.src_decl).name, 0));
            try buf.appendSlice("(");

            var arg_i: usize = 0;
            for (fn_info.param_body) |zir_inst| switch (zir_tags[zir_inst]) {
                .param, .param_comptime, .param_anytype, .param_anytype_comptime => {
                    const arg = sema.inst_map.get(zir_inst).?;
                    // The comptime call code in analyzeCall already did this, so we're
                    // just repeating it here and it's guaranteed to work.
                    const arg_val = sema.resolveConstMaybeUndefVal(block, .unneeded, arg, "") catch unreachable;

                    if (arg_i != 0) try buf.appendSlice(",");
                    try buf.writer().print("{}", .{arg_val.fmtValue(sema.typeOf(arg), sema.mod)});

                    arg_i += 1;
                    continue;
                },
                else => continue,
            };

            try buf.appendSlice(")");
            const name = try buf.toOwnedSliceSentinel(0);
            errdefer sema.gpa.free(name);
            try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
            return new_decl_index;
        },
        .dbg_var => {
            const ref = Zir.indexToRef(inst.?);
            const zir_tags = sema.code.instructions.items(.tag);
            const zir_data = sema.code.instructions.items(.data);
            var i = inst.?;
            while (i < zir_tags.len) : (i += 1) switch (zir_tags[i]) {
                .dbg_var_ptr, .dbg_var_val => {
                    if (zir_data[i].str_op.operand != ref) continue;

                    const name = try std.fmt.allocPrintZ(sema.gpa, "{s}.{s}", .{
                        src_decl.name, zir_data[i].str_op.getStr(sema.code),
                    });
                    errdefer sema.gpa.free(name);

                    try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
                    return new_decl_index;
                },
                else => {},
            };
            return sema.createAnonymousDeclTypeNamed(block, src, typed_value, .anon, anon_prefix, null);
        },
    }
}

fn zirEnumDecl(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const mod = sema.mod;
    const gpa = sema.gpa;
    const small = @bitCast(Zir.Inst.EnumDecl.Small, extended.small);
    var extra_index: usize = extended.operand;

    const src: LazySrcLoc = if (small.has_src_node) blk: {
        const node_offset = @bitCast(i32, sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk LazySrcLoc.nodeOffset(node_offset);
    } else sema.src;
    const tag_ty_src: LazySrcLoc = .{ .node_offset_container_tag = src.node_offset.x };

    const tag_type_ref = if (small.has_tag_type) blk: {
        const tag_type_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk tag_type_ref;
    } else .none;

    const body_len = if (small.has_body_len) blk: {
        const body_len = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk body_len;
    } else 0;

    const fields_len = if (small.has_fields_len) blk: {
        const fields_len = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk fields_len;
    } else 0;

    const decls_len = if (small.has_decls_len) blk: {
        const decls_len = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk decls_len;
    } else 0;

    var done = false;

    var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
    errdefer if (!done) new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const enum_obj = try new_decl_arena_allocator.create(Module.EnumFull);
    const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumFull);
    enum_ty_payload.* = .{
        .base = .{ .tag = if (small.nonexhaustive) .enum_nonexhaustive else .enum_full },
        .data = enum_obj,
    };
    const enum_ty = Type.initPayload(&enum_ty_payload.base);
    const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
    const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
        .ty = Type.type,
        .val = enum_val,
    }, small.name_strategy, "enum", inst);
    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer if (!done) mod.abortAnonDecl(new_decl_index);

    enum_obj.* = .{
        .owner_decl = new_decl_index,
        .tag_ty = Type.null,
        .tag_ty_inferred = true,
        .fields = .{},
        .values = .{},
        .namespace = .{
            .parent = block.namespace,
            .ty = enum_ty,
            .file_scope = block.getFileScope(),
        },
    };
    std.log.scoped(.module).debug("create enum {*} owned by {*} ({s})", .{
        &enum_obj.namespace, new_decl, new_decl.name,
    });

    try new_decl.finalizeNewArena(&new_decl_arena);
    const decl_val = try sema.analyzeDeclVal(block, src, new_decl_index);
    done = true;

    var decl_arena = new_decl.value_arena.?.promote(gpa);
    defer new_decl.value_arena.?.* = decl_arena.state;
    const decl_arena_allocator = decl_arena.allocator();

    extra_index = try mod.scanNamespace(&enum_obj.namespace, extra_index, decls_len, new_decl);

    const body = sema.code.extra[extra_index..][0..body_len];
    extra_index += body.len;

    const bit_bags_count = std.math.divCeil(usize, fields_len, 32) catch unreachable;
    const body_end = extra_index;
    extra_index += bit_bags_count;

    {
        // We create a block for the field type instructions because they
        // may need to reference Decls from inside the enum namespace.
        // Within the field type, default value, and alignment expressions, the "owner decl"
        // should be the enum itself.

        const prev_owner_decl = sema.owner_decl;
        const prev_owner_decl_index = sema.owner_decl_index;
        sema.owner_decl = new_decl;
        sema.owner_decl_index = new_decl_index;
        defer {
            sema.owner_decl = prev_owner_decl;
            sema.owner_decl_index = prev_owner_decl_index;
        }

        const prev_owner_func = sema.owner_func;
        sema.owner_func = null;
        defer sema.owner_func = prev_owner_func;

        const prev_func = sema.func;
        sema.func = null;
        defer sema.func = prev_func;

        var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, new_decl.src_scope);
        defer wip_captures.deinit();

        var enum_block: Block = .{
            .parent = null,
            .sema = sema,
            .src_decl = new_decl_index,
            .namespace = &enum_obj.namespace,
            .wip_capture_scope = wip_captures.scope,
            .instructions = .{},
            .inlining = null,
            .is_comptime = true,
        };
        defer enum_block.instructions.deinit(sema.gpa);

        if (body.len != 0) {
            try sema.analyzeBody(&enum_block, body);
        }

        try wip_captures.finalize();

        if (tag_type_ref != .none) {
            const ty = try sema.resolveType(block, tag_ty_src, tag_type_ref);
            if (ty.zigTypeTag() != .Int and ty.zigTypeTag() != .ComptimeInt) {
                return sema.fail(block, tag_ty_src, "expected integer tag type, found '{}'", .{ty.fmt(sema.mod)});
            }
            enum_obj.tag_ty = try ty.copy(decl_arena_allocator);
            enum_obj.tag_ty_inferred = false;
        } else if (fields_len == 0) {
            enum_obj.tag_ty = try Type.Tag.int_unsigned.create(decl_arena_allocator, 0);
            enum_obj.tag_ty_inferred = true;
        } else {
            const bits = std.math.log2_int_ceil(usize, fields_len);
            enum_obj.tag_ty = try Type.Tag.int_unsigned.create(decl_arena_allocator, bits);
            enum_obj.tag_ty_inferred = true;
        }
    }

    if (small.nonexhaustive and enum_obj.tag_ty.zigTypeTag() != .ComptimeInt) {
        if (fields_len > 1 and std.math.log2_int(u64, fields_len) == enum_obj.tag_ty.bitSize(sema.mod.getTarget())) {
            return sema.fail(block, src, "non-exhaustive enum specifies every value", .{});
        }
    }

    try enum_obj.fields.ensureTotalCapacity(decl_arena_allocator, fields_len);
    const any_values = for (sema.code.extra[body_end..][0..bit_bags_count]) |bag| {
        if (bag != 0) break true;
    } else false;
    if (any_values) {
        try enum_obj.values.ensureTotalCapacityContext(decl_arena_allocator, fields_len, .{
            .ty = enum_obj.tag_ty,
            .mod = mod,
        });
    }

    var bit_bag_index: usize = body_end;
    var cur_bit_bag: u32 = undefined;
    var field_i: u32 = 0;
    var last_tag_val: ?Value = null;
    var tag_val_buf: Value.Payload.U64 = undefined;
    while (field_i < fields_len) : (field_i += 1) {
        if (field_i % 32 == 0) {
            cur_bit_bag = sema.code.extra[bit_bag_index];
            bit_bag_index += 1;
        }
        const has_tag_value = @truncate(u1, cur_bit_bag) != 0;
        cur_bit_bag >>= 1;

        const field_name_zir = sema.code.nullTerminatedString(sema.code.extra[extra_index]);
        extra_index += 1;

        // doc comment
        extra_index += 1;

        // This string needs to outlive the ZIR code.
        const field_name = try decl_arena_allocator.dupe(u8, field_name_zir);

        const gop_field = enum_obj.fields.getOrPutAssumeCapacity(field_name);
        if (gop_field.found_existing) {
            const field_src = enum_obj.fieldSrcLoc(sema.mod, .{ .index = field_i }).lazy;
            const other_field_src = enum_obj.fieldSrcLoc(sema.mod, .{ .index = gop_field.index }).lazy;
            const msg = msg: {
                const msg = try sema.errMsg(block, field_src, "duplicate enum field '{s}'", .{field_name});
                errdefer msg.destroy(gpa);
                try sema.errNote(block, other_field_src, msg, "other field here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }

        if (has_tag_value) {
            const tag_val_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
            extra_index += 1;
            const tag_inst = try sema.resolveInst(tag_val_ref);
            const tag_val = sema.resolveConstValue(block, .unneeded, tag_inst, "") catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const value_src = enum_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .value,
                    }).lazy;
                    _ = try sema.resolveConstValue(block, value_src, tag_inst, "enum tag value must be comptime-known");
                    unreachable;
                },
                else => |e| return e,
            };
            last_tag_val = tag_val;
            const copied_tag_val = try tag_val.copy(decl_arena_allocator);
            const gop_val = enum_obj.values.getOrPutAssumeCapacityContext(copied_tag_val, .{
                .ty = enum_obj.tag_ty,
                .mod = mod,
            });
            if (gop_val.found_existing) {
                const value_src = enum_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .value,
                }).lazy;
                const other_field_src = enum_obj.fieldSrcLoc(sema.mod, .{ .index = gop_val.index }).lazy;
                const msg = msg: {
                    const msg = try sema.errMsg(block, value_src, "enum tag value {} already taken", .{tag_val.fmtValue(enum_obj.tag_ty, sema.mod)});
                    errdefer msg.destroy(gpa);
                    try sema.errNote(block, other_field_src, msg, "other occurrence here", .{});
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
        } else if (any_values) {
            const tag_val = if (last_tag_val) |val|
                try sema.intAdd(val, Value.one, enum_obj.tag_ty)
            else
                Value.zero;
            last_tag_val = tag_val;
            const copied_tag_val = try tag_val.copy(decl_arena_allocator);
            const gop_val = enum_obj.values.getOrPutAssumeCapacityContext(copied_tag_val, .{
                .ty = enum_obj.tag_ty,
                .mod = mod,
            });
            if (gop_val.found_existing) {
                const field_src = enum_obj.fieldSrcLoc(sema.mod, .{ .index = field_i }).lazy;
                const other_field_src = enum_obj.fieldSrcLoc(sema.mod, .{ .index = gop_val.index }).lazy;
                const msg = msg: {
                    const msg = try sema.errMsg(block, field_src, "enum tag value {} already taken", .{tag_val.fmtValue(enum_obj.tag_ty, sema.mod)});
                    errdefer msg.destroy(gpa);
                    try sema.errNote(block, other_field_src, msg, "other occurrence here", .{});
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
        } else {
            tag_val_buf = .{
                .base = .{ .tag = .int_u64 },
                .data = field_i,
            };
            last_tag_val = Value.initPayload(&tag_val_buf.base);
        }

        if (!(try sema.intFitsInType(last_tag_val.?, enum_obj.tag_ty, null))) {
            const value_src = enum_obj.fieldSrcLoc(sema.mod, .{
                .index = field_i,
                .range = if (has_tag_value) .value else .name,
            }).lazy;
            const msg = try sema.errMsg(block, value_src, "enumeration value '{}' too large for type '{}'", .{
                last_tag_val.?.fmtValue(enum_obj.tag_ty, mod), enum_obj.tag_ty.fmt(mod),
            });
            return sema.failWithOwnedErrorMsg(msg);
        }
    }
    return decl_val;
}

fn zirUnionDecl(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const small = @bitCast(Zir.Inst.UnionDecl.Small, extended.small);
    var extra_index: usize = extended.operand;

    const src: LazySrcLoc = if (small.has_src_node) blk: {
        const node_offset = @bitCast(i32, sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk LazySrcLoc.nodeOffset(node_offset);
    } else sema.src;

    extra_index += @boolToInt(small.has_tag_type);
    extra_index += @boolToInt(small.has_body_len);
    extra_index += @boolToInt(small.has_fields_len);

    const decls_len = if (small.has_decls_len) blk: {
        const decls_len = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk decls_len;
    } else 0;

    var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const union_obj = try new_decl_arena_allocator.create(Module.Union);
    const type_tag = if (small.has_tag_type or small.auto_enum_tag)
        Type.Tag.union_tagged
    else if (small.layout != .Auto)
        Type.Tag.@"union"
    else switch (block.sema.mod.optimizeMode()) {
        .Debug, .ReleaseSafe => Type.Tag.union_safety_tagged,
        .ReleaseFast, .ReleaseSmall => Type.Tag.@"union",
    };
    const union_payload = try new_decl_arena_allocator.create(Type.Payload.Union);
    union_payload.* = .{
        .base = .{ .tag = type_tag },
        .data = union_obj,
    };
    const union_ty = Type.initPayload(&union_payload.base);
    const union_val = try Value.Tag.ty.create(new_decl_arena_allocator, union_ty);
    const mod = sema.mod;
    const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
        .ty = Type.type,
        .val = union_val,
    }, small.name_strategy, "union", inst);
    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer mod.abortAnonDecl(new_decl_index);
    union_obj.* = .{
        .owner_decl = new_decl_index,
        .tag_ty = Type.initTag(.null),
        .fields = .{},
        .zir_index = inst,
        .layout = small.layout,
        .status = .none,
        .namespace = .{
            .parent = block.namespace,
            .ty = union_ty,
            .file_scope = block.getFileScope(),
        },
    };
    std.log.scoped(.module).debug("create union {*} owned by {*} ({s})", .{
        &union_obj.namespace, new_decl, new_decl.name,
    });

    _ = try mod.scanNamespace(&union_obj.namespace, extra_index, decls_len, new_decl);

    try new_decl.finalizeNewArena(&new_decl_arena);
    return sema.analyzeDeclVal(block, src, new_decl_index);
}

fn zirOpaqueDecl(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const mod = sema.mod;
    const gpa = sema.gpa;
    const small = @bitCast(Zir.Inst.OpaqueDecl.Small, extended.small);
    var extra_index: usize = extended.operand;

    const src: LazySrcLoc = if (small.has_src_node) blk: {
        const node_offset = @bitCast(i32, sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk LazySrcLoc.nodeOffset(node_offset);
    } else sema.src;

    const decls_len = if (small.has_decls_len) blk: {
        const decls_len = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk decls_len;
    } else 0;

    var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const opaque_obj = try new_decl_arena_allocator.create(Module.Opaque);
    const opaque_ty_payload = try new_decl_arena_allocator.create(Type.Payload.Opaque);
    opaque_ty_payload.* = .{
        .base = .{ .tag = .@"opaque" },
        .data = opaque_obj,
    };
    const opaque_ty = Type.initPayload(&opaque_ty_payload.base);
    const opaque_val = try Value.Tag.ty.create(new_decl_arena_allocator, opaque_ty);
    const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
        .ty = Type.type,
        .val = opaque_val,
    }, small.name_strategy, "opaque", inst);
    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer mod.abortAnonDecl(new_decl_index);

    opaque_obj.* = .{
        .owner_decl = new_decl_index,
        .namespace = .{
            .parent = block.namespace,
            .ty = opaque_ty,
            .file_scope = block.getFileScope(),
        },
    };
    std.log.scoped(.module).debug("create opaque {*} owned by {*} ({s})", .{
        &opaque_obj.namespace, new_decl, new_decl.name,
    });

    extra_index = try mod.scanNamespace(&opaque_obj.namespace, extra_index, decls_len, new_decl);

    try new_decl.finalizeNewArena(&new_decl_arena);
    return sema.analyzeDeclVal(block, src, new_decl_index);
}

fn zirErrorSetDecl(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    name_strategy: Zir.Inst.NameStrategy,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const gpa = sema.gpa;
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.ErrorSetDecl, inst_data.payload_index);

    var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const error_set = try new_decl_arena_allocator.create(Module.ErrorSet);
    const error_set_ty = try Type.Tag.error_set.create(new_decl_arena_allocator, error_set);
    const error_set_val = try Value.Tag.ty.create(new_decl_arena_allocator, error_set_ty);
    const mod = sema.mod;
    const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
        .ty = Type.type,
        .val = error_set_val,
    }, name_strategy, "error", inst);
    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer mod.abortAnonDecl(new_decl_index);

    var names = Module.ErrorSet.NameMap{};
    try names.ensureUnusedCapacity(new_decl_arena_allocator, extra.data.fields_len);

    var extra_index = @intCast(u32, extra.end);
    const extra_index_end = extra_index + (extra.data.fields_len * 2);
    while (extra_index < extra_index_end) : (extra_index += 2) { // +2 to skip over doc_string
        const str_index = sema.code.extra[extra_index];
        const kv = try mod.getErrorValue(sema.code.nullTerminatedString(str_index));
        const result = names.getOrPutAssumeCapacity(kv.key);
        assert(!result.found_existing); // verified in AstGen
    }

    // names must be sorted.
    Module.ErrorSet.sortNames(&names);

    error_set.* = .{
        .owner_decl = new_decl_index,
        .names = names,
    };
    try new_decl.finalizeNewArena(&new_decl_arena);
    return sema.analyzeDeclVal(block, src, new_decl_index);
}

fn zirRetPtr(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    if (block.is_comptime or try sema.typeRequiresComptime(sema.fn_ret_ty)) {
        const fn_ret_ty = try sema.resolveTypeFields(sema.fn_ret_ty);
        return sema.analyzeComptimeAlloc(block, fn_ret_ty, 0);
    }

    const target = sema.mod.getTarget();
    const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = sema.fn_ret_ty,
        .@"addrspace" = target_util.defaultAddressSpace(target, .local),
    });

    if (block.inlining != null) {
        // We are inlining a function call; this should be emitted as an alloc, not a ret_ptr.
        // TODO when functions gain result location support, the inlining struct in
        // Block should contain the return pointer, and we would pass that through here.
        return block.addTy(.alloc, ptr_type);
    }

    return block.addTy(.ret_ptr, ptr_type);
}

fn zirRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_tok;
    const operand = try sema.resolveInst(inst_data.operand);
    return sema.analyzeRef(block, inst_data.src(), operand);
}

fn zirEnsureResultUsed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const src = inst_data.src();

    return sema.ensureResultUsed(block, sema.typeOf(operand), src);
}

fn ensureResultUsed(
    sema: *Sema,
    block: *Block,
    ty: Type,
    src: LazySrcLoc,
) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Void, .NoReturn => return,
        .ErrorSet, .ErrorUnion => {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "error is ignored", .{});
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, src, msg, "consider using 'try', 'catch', or 'if'", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        else => {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "value of type '{}' ignored", .{ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, src, msg, "all non-void values must be used", .{});
                try sema.errNote(block, src, msg, "this error can be suppressed by assigning the value to '_'", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
    }
}

fn zirEnsureResultNonError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const src = inst_data.src();
    const operand_ty = sema.typeOf(operand);
    switch (operand_ty.zigTypeTag()) {
        .ErrorSet, .ErrorUnion => {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "error is discarded", .{});
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, src, msg, "consider using 'try', 'catch', or 'if'", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        else => return,
    }
}

fn zirEnsureErrUnionPayloadVoid(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    const err_union_ty = if (operand_ty.zigTypeTag() == .Pointer)
        operand_ty.childType()
    else
        operand_ty;
    if (err_union_ty.zigTypeTag() != .ErrorUnion) return;
    const payload_ty = err_union_ty.errorUnionPayload().zigTypeTag();
    if (payload_ty != .Void and payload_ty != .NoReturn) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "error union payload is ignored", .{});
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, src, msg, "payload value can be explicitly ignored with '|_|'", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
}

fn zirIndexablePtrLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const object = try sema.resolveInst(inst_data.operand);
    const object_ty = sema.typeOf(object);

    const is_pointer_to = object_ty.isSinglePointer();

    const array_ty = if (is_pointer_to)
        object_ty.childType()
    else
        object_ty;

    try checkIndexable(sema, block, src, array_ty);

    return sema.fieldVal(block, src, object, "len", src);
}

fn zirAllocExtended(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.AllocExtended, extended.operand);
    const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = extra.data.src_node };
    const align_src: LazySrcLoc = .{ .node_offset_var_decl_align = extra.data.src_node };
    const small = @bitCast(Zir.Inst.AllocExtended.Small, extended.small);

    var extra_index: usize = extra.end;

    const var_ty: Type = if (small.has_type) blk: {
        const type_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk try sema.resolveType(block, ty_src, type_ref);
    } else undefined;

    const alignment: u32 = if (small.has_align) blk: {
        const align_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const alignment = try sema.resolveAlign(block, align_src, align_ref);
        break :blk alignment;
    } else 0;

    const inferred_alloc_ty = if (small.is_const)
        Type.initTag(.inferred_alloc_const)
    else
        Type.initTag(.inferred_alloc_mut);

    if (block.is_comptime or small.is_comptime) {
        if (small.has_type) {
            return sema.analyzeComptimeAlloc(block, var_ty, alignment);
        } else {
            return sema.addConstant(
                inferred_alloc_ty,
                try Value.Tag.inferred_alloc_comptime.create(sema.arena, .{
                    .decl_index = undefined,
                    .alignment = alignment,
                }),
            );
        }
    }

    if (small.has_type) {
        if (!small.is_const) {
            try sema.validateVarType(block, ty_src, var_ty, false);
        }
        const target = sema.mod.getTarget();
        try sema.resolveTypeLayout(var_ty);
        const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = var_ty,
            .@"align" = alignment,
            .@"addrspace" = target_util.defaultAddressSpace(target, .local),
        });
        return block.addTy(.alloc, ptr_type);
    }

    // `Sema.addConstant` does not add the instruction to the block because it is
    // not needed in the case of constant values. However here, we plan to "downgrade"
    // to a normal instruction when we hit `resolve_inferred_alloc`. So we append
    // to the block even though it is currently a `.constant`.
    const result = try sema.addConstant(
        inferred_alloc_ty,
        try Value.Tag.inferred_alloc.create(sema.arena, .{ .alignment = alignment }),
    );
    try block.instructions.append(sema.gpa, Air.refToIndex(result).?);
    try sema.unresolved_inferred_allocs.putNoClobber(sema.gpa, Air.refToIndex(result).?, {});
    return result;
}

fn zirAllocComptime(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
    const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
    return sema.analyzeComptimeAlloc(block, var_ty, 0);
}

fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const alloc = try sema.resolveInst(inst_data.operand);
    const alloc_ty = sema.typeOf(alloc);

    var ptr_info = alloc_ty.ptrInfo().data;
    const elem_ty = ptr_info.pointee_type;

    // Detect if all stores to an `.alloc` were comptime-known.
    ct: {
        var search_index: usize = block.instructions.items.len;
        const air_tags = sema.air_instructions.items(.tag);
        const air_datas = sema.air_instructions.items(.data);

        const store_inst = while (true) {
            if (search_index == 0) break :ct;
            search_index -= 1;

            const candidate = block.instructions.items[search_index];
            switch (air_tags[candidate]) {
                .dbg_stmt, .dbg_block_begin, .dbg_block_end => continue,
                .store => break candidate,
                else => break :ct,
            }
        };

        while (true) {
            if (search_index == 0) break :ct;
            search_index -= 1;

            const candidate = block.instructions.items[search_index];
            switch (air_tags[candidate]) {
                .dbg_stmt, .dbg_block_begin, .dbg_block_end => continue,
                .alloc => {
                    if (Air.indexToRef(candidate) != alloc) break :ct;
                    break;
                },
                else => break :ct,
            }
        }

        const store_op = air_datas[store_inst].bin_op;
        const store_val = (try sema.resolveMaybeUndefVal(store_op.rhs)) orelse break :ct;
        if (store_op.lhs != alloc) break :ct;

        // Remove all the unnecessary runtime instructions.
        block.instructions.shrinkRetainingCapacity(search_index);

        var anon_decl = try block.startAnonDecl();
        defer anon_decl.deinit();
        return sema.analyzeDeclRef(try anon_decl.finish(
            try elem_ty.copy(anon_decl.arena()),
            try store_val.copy(anon_decl.arena()),
            ptr_info.@"align",
        ));
    }

    ptr_info.mutable = false;
    const const_ptr_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);

    // Detect if a comptime value simply needs to have its type changed.
    if (try sema.resolveMaybeUndefVal(alloc)) |val| {
        return sema.addConstant(const_ptr_ty, val);
    }

    return block.addBitCast(const_ptr_ty, alloc);
}

fn zirAllocInferredComptime(
    sema: *Sema,
    inst: Zir.Inst.Index,
    inferred_alloc_ty: Type,
) CompileError!Air.Inst.Ref {
    const src_node = sema.code.instructions.items(.data)[inst].node;
    const src = LazySrcLoc.nodeOffset(src_node);
    sema.src = src;
    return sema.addConstant(
        inferred_alloc_ty,
        try Value.Tag.inferred_alloc_comptime.create(sema.arena, .{
            .decl_index = undefined,
            .alignment = 0,
        }),
    );
}

fn zirAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
    const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
    if (block.is_comptime) {
        return sema.analyzeComptimeAlloc(block, var_ty, 0);
    }
    const target = sema.mod.getTarget();
    const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = var_ty,
        .@"addrspace" = target_util.defaultAddressSpace(target, .local),
    });
    try sema.queueFullTypeResolution(var_ty);
    return block.addTy(.alloc, ptr_type);
}

fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
    const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
    if (block.is_comptime) {
        return sema.analyzeComptimeAlloc(block, var_ty, 0);
    }
    try sema.validateVarType(block, ty_src, var_ty, false);
    const target = sema.mod.getTarget();
    const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = var_ty,
        .@"addrspace" = target_util.defaultAddressSpace(target, .local),
    });
    try sema.queueFullTypeResolution(var_ty);
    return block.addTy(.alloc, ptr_type);
}

fn zirAllocInferred(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    inferred_alloc_ty: Type,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const src_node = sema.code.instructions.items(.data)[inst].node;
    const src = LazySrcLoc.nodeOffset(src_node);
    sema.src = src;

    if (block.is_comptime) {
        return sema.addConstant(
            inferred_alloc_ty,
            try Value.Tag.inferred_alloc_comptime.create(sema.arena, .{
                .decl_index = undefined,
                .alignment = 0,
            }),
        );
    }

    // `Sema.addConstant` does not add the instruction to the block because it is
    // not needed in the case of constant values. However here, we plan to "downgrade"
    // to a normal instruction when we hit `resolve_inferred_alloc`. So we append
    // to the block even though it is currently a `.constant`.
    const result = try sema.addConstant(
        inferred_alloc_ty,
        try Value.Tag.inferred_alloc.create(sema.arena, .{ .alignment = 0 }),
    );
    try block.instructions.append(sema.gpa, Air.refToIndex(result).?);
    try sema.unresolved_inferred_allocs.putNoClobber(sema.gpa, Air.refToIndex(result).?, {});
    return result;
}

fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = inst_data.src_node };
    const ptr = try sema.resolveInst(inst_data.operand);
    const ptr_inst = Air.refToIndex(ptr).?;
    assert(sema.air_instructions.items(.tag)[ptr_inst] == .constant);
    const value_index = sema.air_instructions.items(.data)[ptr_inst].ty_pl.payload;
    const ptr_val = sema.air_values.items[value_index];
    const var_is_mut = switch (sema.typeOf(ptr).tag()) {
        .inferred_alloc_const => false,
        .inferred_alloc_mut => true,
        else => unreachable,
    };
    const target = sema.mod.getTarget();

    switch (ptr_val.tag()) {
        .inferred_alloc_comptime => {
            const iac = ptr_val.castTag(.inferred_alloc_comptime).?;
            const decl_index = iac.data.decl_index;
            try sema.mod.declareDeclDependency(sema.owner_decl_index, decl_index);

            const decl = sema.mod.declPtr(decl_index);
            const final_elem_ty = try decl.ty.copy(sema.arena);
            const final_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                .pointee_type = final_elem_ty,
                .mutable = true,
                .@"align" = iac.data.alignment,
                .@"addrspace" = target_util.defaultAddressSpace(target, .local),
            });
            const final_ptr_ty_inst = try sema.addType(final_ptr_ty);
            sema.air_instructions.items(.data)[ptr_inst].ty_pl.ty = final_ptr_ty_inst;

            if (var_is_mut) {
                sema.air_values.items[value_index] = try Value.Tag.decl_ref_mut.create(sema.arena, .{
                    .decl_index = decl_index,
                    .runtime_index = block.runtime_index,
                });
            } else {
                sema.air_values.items[value_index] = try Value.Tag.decl_ref.create(sema.arena, decl_index);
            }
        },
        .inferred_alloc => {
            assert(sema.unresolved_inferred_allocs.remove(ptr_inst));
            const inferred_alloc = ptr_val.castTag(.inferred_alloc).?;
            const peer_inst_list = inferred_alloc.data.prongs.items(.stored_inst);
            const final_elem_ty = try sema.resolvePeerTypes(block, ty_src, peer_inst_list, .none);

            const final_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                .pointee_type = final_elem_ty,
                .mutable = true,
                .@"align" = inferred_alloc.data.alignment,
                .@"addrspace" = target_util.defaultAddressSpace(target, .local),
            });

            if (var_is_mut) {
                try sema.validateVarType(block, ty_src, final_elem_ty, false);
            } else ct: {
                // Detect if the value is comptime-known. In such case, the
                // last 3 AIR instructions of the block will look like this:
                //
                //   %a = constant
                //   %b = bitcast(%a)
                //   %c = store(%b, %d)
                //
                // If `%d` is comptime-known, then we want to store the value
                // inside an anonymous Decl and then erase these three AIR
                // instructions from the block, replacing the inst_map entry
                // corresponding to the ZIR alloc instruction with a constant
                // decl_ref pointing at our new Decl.
                // dbg_stmt instructions may be interspersed into this pattern
                // which must be ignored.
                if (block.instructions.items.len < 3) break :ct;
                var search_index: usize = block.instructions.items.len;
                const air_tags = sema.air_instructions.items(.tag);
                const air_datas = sema.air_instructions.items(.data);

                const store_inst = while (true) {
                    if (search_index == 0) break :ct;
                    search_index -= 1;

                    const candidate = block.instructions.items[search_index];
                    switch (air_tags[candidate]) {
                        .dbg_stmt, .dbg_block_begin, .dbg_block_end => continue,
                        .store => break candidate,
                        else => break :ct,
                    }
                };

                const bitcast_inst = while (true) {
                    if (search_index == 0) break :ct;
                    search_index -= 1;

                    const candidate = block.instructions.items[search_index];
                    switch (air_tags[candidate]) {
                        .dbg_stmt, .dbg_block_begin, .dbg_block_end => continue,
                        .bitcast => break candidate,
                        else => break :ct,
                    }
                };

                const const_inst = while (true) {
                    if (search_index == 0) break :ct;
                    search_index -= 1;

                    const candidate = block.instructions.items[search_index];
                    switch (air_tags[candidate]) {
                        .dbg_stmt, .dbg_block_begin, .dbg_block_end => continue,
                        .constant => break candidate,
                        else => break :ct,
                    }
                };

                const store_op = air_datas[store_inst].bin_op;
                const store_val = (try sema.resolveMaybeUndefVal(store_op.rhs)) orelse break :ct;
                if (store_op.lhs != Air.indexToRef(bitcast_inst)) break :ct;
                if (air_datas[bitcast_inst].ty_op.operand != Air.indexToRef(const_inst)) break :ct;

                const new_decl_index = d: {
                    var anon_decl = try block.startAnonDecl();
                    defer anon_decl.deinit();
                    const new_decl_index = try anon_decl.finish(
                        try final_elem_ty.copy(anon_decl.arena()),
                        try store_val.copy(anon_decl.arena()),
                        inferred_alloc.data.alignment,
                    );
                    break :d new_decl_index;
                };
                try sema.mod.declareDeclDependency(sema.owner_decl_index, new_decl_index);

                // Even though we reuse the constant instruction, we still remove it from the
                // block so that codegen does not see it.
                block.instructions.shrinkRetainingCapacity(search_index);
                sema.air_values.items[value_index] = try Value.Tag.decl_ref.create(sema.arena, new_decl_index);
                // if bitcast ty ref needs to be made const, make_ptr_const
                // ZIR handles it later, so we can just use the ty ref here.
                air_datas[ptr_inst].ty_pl.ty = air_datas[bitcast_inst].ty_op.ty;

                // Unless the block is comptime, `alloc_inferred` always produces
                // a runtime constant. The final inferred type needs to be
                // fully resolved so it can be lowered in codegen.
                try sema.resolveTypeFully(final_elem_ty);

                return;
            }

            try sema.queueFullTypeResolution(final_elem_ty);

            // Change it to a normal alloc.
            sema.air_instructions.set(ptr_inst, .{
                .tag = .alloc,
                .data = .{ .ty = final_ptr_ty },
            });

            // Now we need to go back over all the coerce_result_ptr instructions, which
            // previously inserted a bitcast as a placeholder, and do the logic as if
            // the new result ptr type was available.
            const placeholders = inferred_alloc.data.prongs.items(.placeholder);
            const gpa = sema.gpa;

            var trash_block = block.makeSubBlock();
            trash_block.is_comptime = false;
            trash_block.is_coerce_result_ptr = true;
            defer trash_block.instructions.deinit(gpa);

            const mut_final_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                .pointee_type = final_elem_ty,
                .mutable = true,
                .@"align" = inferred_alloc.data.alignment,
                .@"addrspace" = target_util.defaultAddressSpace(target, .local),
            });
            const dummy_ptr = try trash_block.addTy(.alloc, mut_final_ptr_ty);
            const empty_trash_count = trash_block.instructions.items.len;

            for (placeholders, 0..) |bitcast_inst, i| {
                const sub_ptr_ty = sema.typeOf(Air.indexToRef(bitcast_inst));

                if (mut_final_ptr_ty.eql(sub_ptr_ty, sema.mod)) {
                    // New result location type is the same as the old one; nothing
                    // to do here.
                    continue;
                }

                var bitcast_block = block.makeSubBlock();
                defer bitcast_block.instructions.deinit(gpa);

                trash_block.instructions.shrinkRetainingCapacity(empty_trash_count);
                const sub_ptr = try sema.coerceResultPtr(&bitcast_block, src, ptr, dummy_ptr, peer_inst_list[i], &trash_block);

                assert(bitcast_block.instructions.items.len > 0);
                // If only one instruction is produced then we can replace the bitcast
                // placeholder instruction with this instruction; no need for an entire block.
                if (bitcast_block.instructions.items.len == 1) {
                    const only_inst = bitcast_block.instructions.items[0];
                    sema.air_instructions.set(bitcast_inst, sema.air_instructions.get(only_inst));
                    continue;
                }

                // Here we replace the placeholder bitcast instruction with a block
                // that does the coerce_result_ptr logic.
                _ = try bitcast_block.addBr(bitcast_inst, sub_ptr);
                const ty_inst = sema.air_instructions.items(.data)[bitcast_inst].ty_op.ty;
                try sema.air_extra.ensureUnusedCapacity(
                    gpa,
                    @typeInfo(Air.Block).Struct.fields.len + bitcast_block.instructions.items.len,
                );
                sema.air_instructions.set(bitcast_inst, .{
                    .tag = .block,
                    .data = .{ .ty_pl = .{
                        .ty = ty_inst,
                        .payload = sema.addExtraAssumeCapacity(Air.Block{
                            .body_len = @intCast(u32, bitcast_block.instructions.items.len),
                        }),
                    } },
                });
                sema.air_extra.appendSliceAssumeCapacity(bitcast_block.instructions.items);
            }
        },
        else => unreachable,
    }
}

fn zirArrayBasePtr(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();

    const start_ptr = try sema.resolveInst(inst_data.operand);
    var base_ptr = start_ptr;
    while (true) switch (sema.typeOf(base_ptr).childType().zigTypeTag()) {
        .ErrorUnion => base_ptr = try sema.analyzeErrUnionPayloadPtr(block, src, base_ptr, false, true),
        .Optional => base_ptr = try sema.analyzeOptionalPayloadPtr(block, src, base_ptr, false, true),
        else => break,
    };

    const elem_ty = sema.typeOf(base_ptr).childType();
    switch (elem_ty.zigTypeTag()) {
        .Array, .Vector => return base_ptr,
        .Struct => if (elem_ty.isTuple()) {
            // TODO validate element count
            return base_ptr;
        },
        else => {},
    }
    return sema.failWithArrayInitNotSupported(block, src, sema.typeOf(start_ptr).childType());
}

fn zirFieldBasePtr(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();

    const start_ptr = try sema.resolveInst(inst_data.operand);
    var base_ptr = start_ptr;
    while (true) switch (sema.typeOf(base_ptr).childType().zigTypeTag()) {
        .ErrorUnion => base_ptr = try sema.analyzeErrUnionPayloadPtr(block, src, base_ptr, false, true),
        .Optional => base_ptr = try sema.analyzeOptionalPayloadPtr(block, src, base_ptr, false, true),
        else => break,
    };

    const elem_ty = sema.typeOf(base_ptr).childType();
    switch (elem_ty.zigTypeTag()) {
        .Struct, .Union => return base_ptr,
        else => {},
    }
    return sema.failWithStructInitNotSupported(block, src, sema.typeOf(start_ptr).childType());
}

fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const gpa = sema.gpa;
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
    const args = sema.code.refSlice(extra.end, extra.data.operands_len);
    const src = inst_data.src();

    var len: Air.Inst.Ref = .none;
    var len_val: ?Value = null;
    var len_idx: u32 = undefined;
    var any_runtime = false;

    const runtime_arg_lens = try gpa.alloc(Air.Inst.Ref, args.len);
    defer gpa.free(runtime_arg_lens);

    // First pass to look for comptime values.
    for (args, 0..) |zir_arg, i_usize| {
        const i = @intCast(u32, i_usize);
        runtime_arg_lens[i] = .none;
        if (zir_arg == .none) continue;
        const object = try sema.resolveInst(zir_arg);
        const object_ty = sema.typeOf(object);
        // Each arg could be an indexable, or a range, in which case the length
        // is passed directly as an integer.
        const is_int = switch (object_ty.zigTypeTag()) {
            .Int, .ComptimeInt => true,
            else => false,
        };
        const arg_src: LazySrcLoc = .{ .for_input = .{
            .for_node_offset = inst_data.src_node,
            .input_index = i,
        } };
        const arg_len_uncoerced = if (is_int) object else l: {
            try checkIndexable(sema, block, arg_src, object_ty);
            if (!object_ty.indexableHasLen()) continue;

            break :l try sema.fieldVal(block, arg_src, object, "len", arg_src);
        };
        const arg_len = try sema.coerce(block, Type.usize, arg_len_uncoerced, arg_src);
        if (len == .none) {
            len = arg_len;
            len_idx = i;
        }
        if (try sema.resolveDefinedValue(block, src, arg_len)) |arg_val| {
            if (len_val) |v| {
                if (!(try sema.valuesEqual(arg_val, v, Type.usize))) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "non-matching for loop lengths", .{});
                        errdefer msg.destroy(gpa);
                        const a_src: LazySrcLoc = .{ .for_input = .{
                            .for_node_offset = inst_data.src_node,
                            .input_index = len_idx,
                        } };
                        try sema.errNote(block, a_src, msg, "length {} here", .{
                            v.fmtValue(Type.usize, sema.mod),
                        });
                        try sema.errNote(block, arg_src, msg, "length {} here", .{
                            arg_val.fmtValue(Type.usize, sema.mod),
                        });
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            } else {
                len = arg_len;
                len_val = arg_val;
                len_idx = i;
            }
            continue;
        }
        runtime_arg_lens[i] = arg_len;
        any_runtime = true;
    }

    if (len == .none) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "unbounded for loop", .{});
            errdefer msg.destroy(gpa);
            for (args, 0..) |zir_arg, i_usize| {
                const i = @intCast(u32, i_usize);
                if (zir_arg == .none) continue;
                const object = try sema.resolveInst(zir_arg);
                const object_ty = sema.typeOf(object);
                // Each arg could be an indexable, or a range, in which case the length
                // is passed directly as an integer.
                switch (object_ty.zigTypeTag()) {
                    .Int, .ComptimeInt => continue,
                    else => {},
                }
                const arg_src: LazySrcLoc = .{ .for_input = .{
                    .for_node_offset = inst_data.src_node,
                    .input_index = i,
                } };
                try sema.errNote(block, arg_src, msg, "type '{}' has no upper bound", .{
                    object_ty.fmt(sema.mod),
                });
            }
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    // Now for the runtime checks.
    if (any_runtime and block.wantSafety()) {
        for (runtime_arg_lens, 0..) |arg_len, i| {
            if (arg_len == .none) continue;
            if (i == len_idx) continue;
            const ok = try block.addBinOp(.cmp_eq, len, arg_len);
            try sema.addSafetyCheck(block, ok, .for_len_mismatch);
        }
    }

    return len;
}

fn validateArrayInitTy(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const ty_src: LazySrcLoc = .{ .node_offset_init_ty = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.ArrayInit, inst_data.payload_index).data;
    const ty = try sema.resolveType(block, ty_src, extra.ty);

    switch (ty.zigTypeTag()) {
        .Array => {
            const array_len = ty.arrayLen();
            if (extra.init_count != array_len) {
                return sema.fail(block, src, "expected {d} array elements; found {d}", .{
                    array_len, extra.init_count,
                });
            }
            return;
        },
        .Vector => {
            const array_len = ty.arrayLen();
            if (extra.init_count != array_len) {
                return sema.fail(block, src, "expected {d} vector elements; found {d}", .{
                    array_len, extra.init_count,
                });
            }
            return;
        },
        .Struct => if (ty.isTuple()) {
            _ = try sema.resolveTypeFields(ty);
            const array_len = ty.arrayLen();
            if (extra.init_count > array_len) {
                return sema.fail(block, src, "expected at most {d} tuple fields; found {d}", .{
                    array_len, extra.init_count,
                });
            }
            return;
        },
        else => {},
    }
    return sema.failWithArrayInitNotSupported(block, ty_src, ty);
}

fn validateStructInitTy(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ty = try sema.resolveType(block, src, inst_data.operand);

    switch (ty.zigTypeTag()) {
        .Struct, .Union => return,
        else => {},
    }
    return sema.failWithStructInitNotSupported(block, src, ty);
}

fn zirValidateStructInit(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_comptime: bool,
) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const validate_inst = sema.code.instructions.items(.data)[inst].pl_node;
    const init_src = validate_inst.src();
    const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
    const instrs = sema.code.extra[validate_extra.end..][0..validate_extra.data.body_len];
    const field_ptr_data = sema.code.instructions.items(.data)[instrs[0]].pl_node;
    const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
    const object_ptr = try sema.resolveInst(field_ptr_extra.lhs);
    const agg_ty = sema.typeOf(object_ptr).childType();
    switch (agg_ty.zigTypeTag()) {
        .Struct => return sema.validateStructInit(
            block,
            agg_ty,
            init_src,
            instrs,
            is_comptime,
        ),
        .Union => return sema.validateUnionInit(
            block,
            agg_ty,
            init_src,
            instrs,
            object_ptr,
            is_comptime,
        ),
        else => unreachable,
    }
}

fn validateUnionInit(
    sema: *Sema,
    block: *Block,
    union_ty: Type,
    init_src: LazySrcLoc,
    instrs: []const Zir.Inst.Index,
    union_ptr: Air.Inst.Ref,
    is_comptime: bool,
) CompileError!void {
    if (instrs.len != 1) {
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                init_src,
                "cannot initialize multiple union fields at once, unions can only have one active field",
                .{},
            );
            errdefer msg.destroy(sema.gpa);

            for (instrs[1..]) |inst| {
                const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
                const inst_src: LazySrcLoc = .{ .node_offset_initializer = inst_data.src_node };
                try sema.errNote(block, inst_src, msg, "additional initializer here", .{});
            }
            try sema.addDeclaredHereNote(msg, union_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    if ((is_comptime or block.is_comptime) and
        (try sema.resolveDefinedValue(block, init_src, union_ptr)) != null)
    {
        // In this case, comptime machinery already did everything. No work to do here.
        return;
    }

    const field_ptr = instrs[0];
    const field_ptr_data = sema.code.instructions.items(.data)[field_ptr].pl_node;
    const field_src: LazySrcLoc = .{ .node_offset_initializer = field_ptr_data.src_node };
    const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
    const field_name = sema.code.nullTerminatedString(field_ptr_extra.field_name_start);
    // Validate the field access but ignore the index since we want the tag enum field index.
    _ = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
    const air_tags = sema.air_instructions.items(.tag);
    const air_datas = sema.air_instructions.items(.data);
    const field_ptr_air_ref = sema.inst_map.get(field_ptr).?;
    const field_ptr_air_inst = Air.refToIndex(field_ptr_air_ref).?;

    // Our task here is to determine if the union is comptime-known. In such case,
    // we erase the runtime AIR instructions for initializing the union, and replace
    // the mapping with the comptime value. Either way, we will need to populate the tag.

    // We expect to see something like this in the current block AIR:
    //   %a = alloc(*const U)
    //   %b = bitcast(*U, %a)
    //   %c = field_ptr(..., %b)
    //   %e!= store(%c!, %d!)
    // If %d is a comptime operand, the union is comptime.
    // If the union is comptime, we want `first_block_index`
    // to point at %c so that the bitcast becomes the last instruction in the block.
    //
    // In the case of a comptime-known pointer to a union, the
    // the field_ptr instruction is missing, so we have to pattern-match
    // based only on the store instructions.
    // `first_block_index` needs to point to the `field_ptr` if it exists;
    // the `store` otherwise.
    //
    // It's also possible for there to be no store instruction, in the case
    // of nested `coerce_result_ptr` instructions. If we see the `field_ptr`
    // but we have not found a `store`, treat as a runtime-known field.
    var first_block_index = block.instructions.items.len;
    var block_index = block.instructions.items.len - 1;
    var init_val: ?Value = null;
    var make_runtime = false;
    while (block_index > 0) : (block_index -= 1) {
        const store_inst = block.instructions.items[block_index];
        if (store_inst == field_ptr_air_inst) break;
        if (air_tags[store_inst] != .store) continue;
        const bin_op = air_datas[store_inst].bin_op;
        var lhs = bin_op.lhs;
        if (Air.refToIndex(lhs)) |lhs_index| {
            if (air_tags[lhs_index] == .bitcast) {
                lhs = air_datas[lhs_index].ty_op.operand;
                block_index -= 1;
            }
        }
        if (lhs != field_ptr_air_ref) continue;
        while (block_index > 0) : (block_index -= 1) {
            const block_inst = block.instructions.items[block_index - 1];
            if (air_tags[block_inst] != .dbg_stmt) break;
        }
        if (block_index > 0 and
            field_ptr_air_inst == block.instructions.items[block_index - 1])
        {
            first_block_index = @min(first_block_index, block_index - 1);
        } else {
            first_block_index = @min(first_block_index, block_index);
        }
        init_val = try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(bin_op.rhs, &make_runtime);
        break;
    }

    const tag_ty = union_ty.unionTagTypeHypothetical();
    const enum_field_index = @intCast(u32, tag_ty.enumFieldIndex(field_name).?);
    const tag_val = try Value.Tag.enum_field_index.create(sema.arena, enum_field_index);

    if (init_val) |val| {
        // Our task is to delete all the `field_ptr` and `store` instructions, and insert
        // instead a single `store` to the result ptr with a comptime union value.
        block.instructions.shrinkRetainingCapacity(first_block_index);

        var union_val = try Value.Tag.@"union".create(sema.arena, .{
            .tag = tag_val,
            .val = val,
        });
        if (make_runtime) union_val = try Value.Tag.runtime_value.create(sema.arena, union_val);
        const union_init = try sema.addConstant(union_ty, union_val);
        try sema.storePtr2(block, init_src, union_ptr, init_src, union_init, init_src, .store);
        return;
    } else if (try sema.typeRequiresComptime(union_ty)) {
        return sema.failWithNeededComptime(block, field_ptr_data.src(), "initializer of comptime only union must be comptime-known");
    }

    const new_tag = try sema.addConstant(tag_ty, tag_val);
    _ = try block.addBinOp(.set_union_tag, union_ptr, new_tag);
}

fn validateStructInit(
    sema: *Sema,
    block: *Block,
    struct_ty: Type,
    init_src: LazySrcLoc,
    instrs: []const Zir.Inst.Index,
    is_comptime: bool,
) CompileError!void {
    const gpa = sema.gpa;

    // Maps field index to field_ptr index of where it was already initialized.
    const found_fields = try gpa.alloc(Zir.Inst.Index, struct_ty.structFieldCount());
    defer gpa.free(found_fields);
    mem.set(Zir.Inst.Index, found_fields, 0);

    var struct_ptr_zir_ref: Zir.Inst.Ref = undefined;

    for (instrs) |field_ptr| {
        const field_ptr_data = sema.code.instructions.items(.data)[field_ptr].pl_node;
        const field_src: LazySrcLoc = .{ .node_offset_initializer = field_ptr_data.src_node };
        const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
        struct_ptr_zir_ref = field_ptr_extra.lhs;
        const field_name = sema.code.nullTerminatedString(field_ptr_extra.field_name_start);
        const field_index = if (struct_ty.isTuple())
            try sema.tupleFieldIndex(block, struct_ty, field_name, field_src)
        else
            try sema.structFieldIndex(block, struct_ty, field_name, field_src);
        if (found_fields[field_index] != 0) {
            const other_field_ptr = found_fields[field_index];
            const other_field_ptr_data = sema.code.instructions.items(.data)[other_field_ptr].pl_node;
            const other_field_src: LazySrcLoc = .{ .node_offset_initializer = other_field_ptr_data.src_node };
            const msg = msg: {
                const msg = try sema.errMsg(block, field_src, "duplicate field", .{});
                errdefer msg.destroy(gpa);
                try sema.errNote(block, other_field_src, msg, "other field here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        found_fields[field_index] = field_ptr;
    }

    var root_msg: ?*Module.ErrorMsg = null;
    errdefer if (root_msg) |msg| msg.destroy(sema.gpa);

    const struct_ptr = try sema.resolveInst(struct_ptr_zir_ref);
    if ((is_comptime or block.is_comptime) and
        (try sema.resolveDefinedValue(block, init_src, struct_ptr)) != null)
    {
        try sema.resolveStructLayout(struct_ty);
        // In this case the only thing we need to do is evaluate the implicit
        // store instructions for default field values, and report any missing fields.
        // Avoid the cost of the extra machinery for detecting a comptime struct init value.
        for (found_fields, 0..) |field_ptr, i| {
            if (field_ptr != 0) continue;

            const default_val = struct_ty.structFieldDefaultValue(i);
            if (default_val.tag() == .unreachable_value) {
                if (struct_ty.isTuple()) {
                    const template = "missing tuple field with index {d}";
                    if (root_msg) |msg| {
                        try sema.errNote(block, init_src, msg, template, .{i});
                    } else {
                        root_msg = try sema.errMsg(block, init_src, template, .{i});
                    }
                    continue;
                }
                const field_name = struct_ty.structFieldName(i);
                const template = "missing struct field: {s}";
                const args = .{field_name};
                if (root_msg) |msg| {
                    try sema.errNote(block, init_src, msg, template, args);
                } else {
                    root_msg = try sema.errMsg(block, init_src, template, args);
                }
                continue;
            }

            const field_src = init_src; // TODO better source location
            const default_field_ptr = if (struct_ty.isTuple())
                try sema.tupleFieldPtr(block, init_src, struct_ptr, field_src, @intCast(u32, i), true)
            else
                try sema.structFieldPtrByIndex(block, init_src, struct_ptr, @intCast(u32, i), field_src, struct_ty, true);
            const field_ty = sema.typeOf(default_field_ptr).childType();
            const init = try sema.addConstant(field_ty, default_val);
            try sema.storePtr2(block, init_src, default_field_ptr, init_src, init, field_src, .store);
        }

        if (root_msg) |msg| {
            if (struct_ty.castTag(.@"struct")) |struct_obj| {
                const mod = sema.mod;
                const fqn = try struct_obj.data.getFullyQualifiedName(mod);
                defer gpa.free(fqn);
                try mod.errNoteNonLazy(
                    struct_obj.data.srcLoc(mod),
                    msg,
                    "struct '{s}' declared here",
                    .{fqn},
                );
            }
            root_msg = null;
            return sema.failWithOwnedErrorMsg(msg);
        }

        return;
    }

    var struct_is_comptime = true;
    var first_block_index = block.instructions.items.len;
    var make_runtime = false;

    const require_comptime = try sema.typeRequiresComptime(struct_ty);
    const air_tags = sema.air_instructions.items(.tag);
    const air_datas = sema.air_instructions.items(.data);

    // We collect the comptime field values in case the struct initialization
    // ends up being comptime-known.
    const field_values = try sema.arena.alloc(Value, struct_ty.structFieldCount());

    field: for (found_fields, 0..) |field_ptr, i| {
        if (field_ptr != 0) {
            // Determine whether the value stored to this pointer is comptime-known.
            const field_ty = struct_ty.structFieldType(i);
            if (try sema.typeHasOnePossibleValue(field_ty)) |opv| {
                field_values[i] = opv;
                continue;
            }

            const field_ptr_air_ref = sema.inst_map.get(field_ptr).?;
            const field_ptr_air_inst = Air.refToIndex(field_ptr_air_ref).?;

            //std.debug.print("validateStructInit (field_ptr_air_inst=%{d}):\n", .{
            //    field_ptr_air_inst,
            //});
            //for (block.instructions.items) |item| {
            //    std.debug.print("  %{d} = {s}\n", .{item, @tagName(air_tags[item])});
            //}

            // We expect to see something like this in the current block AIR:
            //   %a = field_ptr(...)
            //   store(%a, %b)
            // With an optional bitcast between the store and the field_ptr.
            // If %b is a comptime operand, this field is comptime.
            //
            // However, in the case of a comptime-known pointer to a struct, the
            // the field_ptr instruction is missing, so we have to pattern-match
            // based only on the store instructions.
            // `first_block_index` needs to point to the `field_ptr` if it exists;
            // the `store` otherwise.
            //
            // It's also possible for there to be no store instruction, in the case
            // of nested `coerce_result_ptr` instructions. If we see the `field_ptr`
            // but we have not found a `store`, treat as a runtime-known field.

            // Possible performance enhancement: save the `block_index` between iterations
            // of the for loop.
            var block_index = block.instructions.items.len - 1;
            while (block_index > 0) : (block_index -= 1) {
                const store_inst = block.instructions.items[block_index];
                if (store_inst == field_ptr_air_inst) {
                    struct_is_comptime = false;
                    continue :field;
                }
                if (air_tags[store_inst] != .store) continue;
                const bin_op = air_datas[store_inst].bin_op;
                var lhs = bin_op.lhs;
                {
                    const lhs_index = Air.refToIndex(lhs) orelse continue;
                    if (air_tags[lhs_index] == .bitcast) {
                        lhs = air_datas[lhs_index].ty_op.operand;
                        block_index -= 1;
                    }
                }
                if (lhs != field_ptr_air_ref) continue;
                while (block_index > 0) : (block_index -= 1) {
                    const block_inst = block.instructions.items[block_index - 1];
                    if (air_tags[block_inst] != .dbg_stmt) break;
                }
                if (block_index > 0 and
                    field_ptr_air_inst == block.instructions.items[block_index - 1])
                {
                    first_block_index = @min(first_block_index, block_index - 1);
                } else {
                    first_block_index = @min(first_block_index, block_index);
                }
                if (try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(bin_op.rhs, &make_runtime)) |val| {
                    field_values[i] = val;
                } else if (require_comptime) {
                    const field_ptr_data = sema.code.instructions.items(.data)[field_ptr].pl_node;
                    return sema.failWithNeededComptime(block, field_ptr_data.src(), "initializer of comptime only struct must be comptime-known");
                } else {
                    struct_is_comptime = false;
                }
                continue :field;
            }
            struct_is_comptime = false;
            continue :field;
        }

        const default_val = struct_ty.structFieldDefaultValue(i);
        if (default_val.tag() == .unreachable_value) {
            if (struct_ty.isTuple()) {
                const template = "missing tuple field with index {d}";
                if (root_msg) |msg| {
                    try sema.errNote(block, init_src, msg, template, .{i});
                } else {
                    root_msg = try sema.errMsg(block, init_src, template, .{i});
                }
                continue;
            }
            const field_name = struct_ty.structFieldName(i);
            const template = "missing struct field: {s}";
            const args = .{field_name};
            if (root_msg) |msg| {
                try sema.errNote(block, init_src, msg, template, args);
            } else {
                root_msg = try sema.errMsg(block, init_src, template, args);
            }
            continue;
        }
        field_values[i] = default_val;
    }

    if (root_msg) |msg| {
        if (struct_ty.castTag(.@"struct")) |struct_obj| {
            const fqn = try struct_obj.data.getFullyQualifiedName(sema.mod);
            defer gpa.free(fqn);
            try sema.mod.errNoteNonLazy(
                struct_obj.data.srcLoc(sema.mod),
                msg,
                "struct '{s}' declared here",
                .{fqn},
            );
        }
        root_msg = null;
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (struct_is_comptime) {
        // Our task is to delete all the `field_ptr` and `store` instructions, and insert
        // instead a single `store` to the struct_ptr with a comptime struct value.

        block.instructions.shrinkRetainingCapacity(first_block_index);
        var struct_val = try Value.Tag.aggregate.create(sema.arena, field_values);
        if (make_runtime) struct_val = try Value.Tag.runtime_value.create(sema.arena, struct_val);
        const struct_init = try sema.addConstant(struct_ty, struct_val);
        try sema.storePtr2(block, init_src, struct_ptr, init_src, struct_init, init_src, .store);
        return;
    }
    try sema.resolveStructLayout(struct_ty);

    // Our task is to insert `store` instructions for all the default field values.
    for (found_fields, 0..) |field_ptr, i| {
        if (field_ptr != 0) continue;

        const field_src = init_src; // TODO better source location
        const default_field_ptr = if (struct_ty.isTuple())
            try sema.tupleFieldPtr(block, init_src, struct_ptr, field_src, @intCast(u32, i), true)
        else
            try sema.structFieldPtrByIndex(block, init_src, struct_ptr, @intCast(u32, i), field_src, struct_ty, true);
        const field_ty = sema.typeOf(default_field_ptr).childType();
        const init = try sema.addConstant(field_ty, field_values[i]);
        try sema.storePtr2(block, init_src, default_field_ptr, init_src, init, field_src, .store);
    }
}

fn zirValidateArrayInit(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_comptime: bool,
) CompileError!void {
    const validate_inst = sema.code.instructions.items(.data)[inst].pl_node;
    const init_src = validate_inst.src();
    const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
    const instrs = sema.code.extra[validate_extra.end..][0..validate_extra.data.body_len];
    const first_elem_ptr_data = sema.code.instructions.items(.data)[instrs[0]].pl_node;
    const elem_ptr_extra = sema.code.extraData(Zir.Inst.ElemPtrImm, first_elem_ptr_data.payload_index).data;
    const array_ptr = try sema.resolveInst(elem_ptr_extra.ptr);
    const array_ty = sema.typeOf(array_ptr).childType();
    const array_len = array_ty.arrayLen();

    if (instrs.len != array_len) switch (array_ty.zigTypeTag()) {
        .Struct => {
            var root_msg: ?*Module.ErrorMsg = null;
            errdefer if (root_msg) |msg| msg.destroy(sema.gpa);

            var i = instrs.len;
            while (i < array_len) : (i += 1) {
                const default_val = array_ty.structFieldDefaultValue(i);
                if (default_val.tag() == .unreachable_value) {
                    const template = "missing tuple field with index {d}";
                    if (root_msg) |msg| {
                        try sema.errNote(block, init_src, msg, template, .{i});
                    } else {
                        root_msg = try sema.errMsg(block, init_src, template, .{i});
                    }
                }
            }

            if (root_msg) |msg| {
                root_msg = null;
                return sema.failWithOwnedErrorMsg(msg);
            }
        },
        .Array => {
            return sema.fail(block, init_src, "expected {d} array elements; found {d}", .{
                array_len, instrs.len,
            });
        },
        .Vector => {
            return sema.fail(block, init_src, "expected {d} vector elements; found {d}", .{
                array_len, instrs.len,
            });
        },
        else => unreachable,
    };

    if ((is_comptime or block.is_comptime) and
        (try sema.resolveDefinedValue(block, init_src, array_ptr)) != null)
    {
        // In this case the comptime machinery will have evaluated the store instructions
        // at comptime so we have almost nothing to do here. However, in case of a
        // sentinel-terminated array, the sentinel will not have been populated by
        // any ZIR instructions at comptime; we need to do that here.
        if (array_ty.sentinel()) |sentinel_val| {
            const array_len_ref = try sema.addIntUnsigned(Type.usize, array_len);
            const sentinel_ptr = try sema.elemPtrArray(block, init_src, init_src, array_ptr, init_src, array_len_ref, true, true);
            const sentinel = try sema.addConstant(array_ty.childType(), sentinel_val);
            try sema.storePtr2(block, init_src, sentinel_ptr, init_src, sentinel, init_src, .store);
        }
        return;
    }

    var array_is_comptime = true;
    var first_block_index = block.instructions.items.len;
    var make_runtime = false;

    // Collect the comptime element values in case the array literal ends up
    // being comptime-known.
    const array_len_s = try sema.usizeCast(block, init_src, array_ty.arrayLenIncludingSentinel());
    const element_vals = try sema.arena.alloc(Value, array_len_s);
    const opt_opv = try sema.typeHasOnePossibleValue(array_ty);
    const air_tags = sema.air_instructions.items(.tag);
    const air_datas = sema.air_instructions.items(.data);

    outer: for (instrs, 0..) |elem_ptr, i| {
        // Determine whether the value stored to this pointer is comptime-known.

        if (array_ty.isTuple()) {
            if (array_ty.structFieldValueComptime(i)) |opv| {
                element_vals[i] = opv;
                continue;
            }
        } else {
            // Array has one possible value, so value is always comptime-known
            if (opt_opv) |opv| {
                element_vals[i] = opv;
                continue;
            }
        }

        const elem_ptr_air_ref = sema.inst_map.get(elem_ptr).?;
        const elem_ptr_air_inst = Air.refToIndex(elem_ptr_air_ref).?;

        // We expect to see something like this in the current block AIR:
        //   %a = elem_ptr(...)
        //   store(%a, %b)
        // With an optional bitcast between the store and the elem_ptr.
        // If %b is a comptime operand, this element is comptime.
        //
        // However, in the case of a comptime-known pointer to an array, the
        // the elem_ptr instruction is missing, so we have to pattern-match
        // based only on the store instructions.
        // `first_block_index` needs to point to the `elem_ptr` if it exists;
        // the `store` otherwise.
        //
        // It's also possible for there to be no store instruction, in the case
        // of nested `coerce_result_ptr` instructions. If we see the `elem_ptr`
        // but we have not found a `store`, treat as a runtime-known element.
        //
        // This is nearly identical to similar logic in `validateStructInit`.

        // Possible performance enhancement: save the `block_index` between iterations
        // of the for loop.
        var block_index = block.instructions.items.len - 1;
        while (block_index > 0) : (block_index -= 1) {
            const store_inst = block.instructions.items[block_index];
            if (store_inst == elem_ptr_air_inst) {
                array_is_comptime = false;
                continue :outer;
            }
            if (air_tags[store_inst] != .store) continue;
            const bin_op = air_datas[store_inst].bin_op;
            var lhs = bin_op.lhs;
            {
                const lhs_index = Air.refToIndex(lhs) orelse continue;
                if (air_tags[lhs_index] == .bitcast) {
                    lhs = air_datas[lhs_index].ty_op.operand;
                    block_index -= 1;
                }
            }
            if (lhs != elem_ptr_air_ref) continue;
            while (block_index > 0) : (block_index -= 1) {
                const block_inst = block.instructions.items[block_index - 1];
                if (air_tags[block_inst] != .dbg_stmt) break;
            }
            if (block_index > 0 and
                elem_ptr_air_inst == block.instructions.items[block_index - 1])
            {
                first_block_index = @min(first_block_index, block_index - 1);
            } else {
                first_block_index = @min(first_block_index, block_index);
            }
            if (try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(bin_op.rhs, &make_runtime)) |val| {
                element_vals[i] = val;
            } else {
                array_is_comptime = false;
            }
            continue :outer;
        }
        array_is_comptime = false;
        continue :outer;
    }

    if (array_is_comptime) {
        if (try sema.resolveDefinedValue(block, init_src, array_ptr)) |ptr_val| {
            if (ptr_val.tag() == .comptime_field_ptr) {
                // This store was validated by the individual elem ptrs.
                return;
            }
        }

        // Our task is to delete all the `elem_ptr` and `store` instructions, and insert
        // instead a single `store` to the array_ptr with a comptime struct value.
        // Also to populate the sentinel value, if any.
        if (array_ty.sentinel()) |sentinel_val| {
            element_vals[instrs.len] = sentinel_val;
        }

        block.instructions.shrinkRetainingCapacity(first_block_index);

        var array_val = try Value.Tag.aggregate.create(sema.arena, element_vals);
        if (make_runtime) array_val = try Value.Tag.runtime_value.create(sema.arena, array_val);
        const array_init = try sema.addConstant(array_ty, array_val);
        try sema.storePtr2(block, init_src, array_ptr, init_src, array_init, init_src, .store);
    }
}

fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);

    if (operand_ty.zigTypeTag() != .Pointer) {
        return sema.fail(block, src, "cannot dereference non-pointer type '{}'", .{operand_ty.fmt(sema.mod)});
    } else switch (operand_ty.ptrSize()) {
        .One, .C => {},
        .Many => return sema.fail(block, src, "index syntax required for unknown-length pointer type '{}'", .{operand_ty.fmt(sema.mod)}),
        .Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(sema.mod)}),
    }

    const elem_ty = operand_ty.elemType2();
    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        if (val.isUndef()) {
            return sema.fail(block, src, "cannot dereference undefined value", .{});
        }
    } else if (!(try sema.validateRunTimeType(elem_ty, false))) {
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                src,
                "values of type '{}' must be comptime-known, but operand value is runtime-known",
                .{elem_ty.fmt(sema.mod)},
            );
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsComptime(block, src, msg, src.toSrcLoc(src_decl), elem_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
}

fn failWithBadMemberAccess(
    sema: *Sema,
    block: *Block,
    agg_ty: Type,
    field_src: LazySrcLoc,
    field_name: []const u8,
) CompileError {
    const kw_name = switch (agg_ty.zigTypeTag()) {
        .Union => "union",
        .Struct => "struct",
        .Opaque => "opaque",
        .Enum => "enum",
        else => unreachable,
    };
    if (agg_ty.getOwnerDeclOrNull()) |some| if (sema.mod.declIsRoot(some)) {
        return sema.fail(block, field_src, "root struct of file '{}' has no member named '{s}'", .{
            agg_ty.fmt(sema.mod), field_name,
        });
    };
    const msg = msg: {
        const msg = try sema.errMsg(block, field_src, "{s} '{}' has no member named '{s}'", .{
            kw_name, agg_ty.fmt(sema.mod), field_name,
        });
        errdefer msg.destroy(sema.gpa);
        try sema.addDeclaredHereNote(msg, agg_ty);
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn failWithBadStructFieldAccess(
    sema: *Sema,
    block: *Block,
    struct_obj: *Module.Struct,
    field_src: LazySrcLoc,
    field_name: []const u8,
) CompileError {
    const gpa = sema.gpa;

    const fqn = try struct_obj.getFullyQualifiedName(sema.mod);
    defer gpa.free(fqn);

    const msg = msg: {
        const msg = try sema.errMsg(
            block,
            field_src,
            "no field named '{s}' in struct '{s}'",
            .{ field_name, fqn },
        );
        errdefer msg.destroy(gpa);
        try sema.mod.errNoteNonLazy(struct_obj.srcLoc(sema.mod), msg, "struct declared here", .{});
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn failWithBadUnionFieldAccess(
    sema: *Sema,
    block: *Block,
    union_obj: *Module.Union,
    field_src: LazySrcLoc,
    field_name: []const u8,
) CompileError {
    const gpa = sema.gpa;

    const fqn = try union_obj.getFullyQualifiedName(sema.mod);
    defer gpa.free(fqn);

    const msg = msg: {
        const msg = try sema.errMsg(
            block,
            field_src,
            "no field named '{s}' in union '{s}'",
            .{ field_name, fqn },
        );
        errdefer msg.destroy(gpa);
        try sema.mod.errNoteNonLazy(union_obj.srcLoc(sema.mod), msg, "union declared here", .{});
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn addDeclaredHereNote(sema: *Sema, parent: *Module.ErrorMsg, decl_ty: Type) !void {
    const src_loc = decl_ty.declSrcLocOrNull(sema.mod) orelse return;
    const category = switch (decl_ty.zigTypeTag()) {
        .Union => "union",
        .Struct => "struct",
        .Enum => "enum",
        .Opaque => "opaque",
        .ErrorSet => "error set",
        else => unreachable,
    };
    try sema.mod.errNoteNonLazy(src_loc, parent, "{s} declared here", .{category});
}

fn zirStoreToBlockPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const bin_inst = sema.code.instructions.items(.data)[inst].bin;
    const ptr = sema.inst_map.get(Zir.refToIndex(bin_inst.lhs).?) orelse {
        // This is an elided instruction, but AstGen was unable to omit it.
        return;
    };
    const operand = try sema.resolveInst(bin_inst.rhs);
    const src: LazySrcLoc = sema.src;
    blk: {
        const ptr_inst = Air.refToIndex(ptr) orelse break :blk;
        if (sema.air_instructions.items(.tag)[ptr_inst] != .constant) break :blk;
        const air_datas = sema.air_instructions.items(.data);
        const ptr_val = sema.air_values.items[air_datas[ptr_inst].ty_pl.payload];
        switch (ptr_val.tag()) {
            .inferred_alloc_comptime => {
                const iac = ptr_val.castTag(.inferred_alloc_comptime).?;
                return sema.storeToInferredAllocComptime(block, src, operand, iac);
            },
            .inferred_alloc => {
                const inferred_alloc = ptr_val.castTag(.inferred_alloc).?;
                return sema.storeToInferredAlloc(block, src, ptr, operand, inferred_alloc);
            },
            else => break :blk,
        }
    }

    return sema.storePtr(block, src, ptr, operand);
}

fn zirStoreToInferredPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const src: LazySrcLoc = sema.src;
    const bin_inst = sema.code.instructions.items(.data)[inst].bin;
    const ptr = try sema.resolveInst(bin_inst.lhs);
    const operand = try sema.resolveInst(bin_inst.rhs);
    const ptr_inst = Air.refToIndex(ptr).?;
    assert(sema.air_instructions.items(.tag)[ptr_inst] == .constant);
    const air_datas = sema.air_instructions.items(.data);
    const ptr_val = sema.air_values.items[air_datas[ptr_inst].ty_pl.payload];

    switch (ptr_val.tag()) {
        .inferred_alloc_comptime => {
            const iac = ptr_val.castTag(.inferred_alloc_comptime).?;
            return sema.storeToInferredAllocComptime(block, src, operand, iac);
        },
        .inferred_alloc => {
            const inferred_alloc = ptr_val.castTag(.inferred_alloc).?;
            return sema.storeToInferredAlloc(block, src, ptr, operand, inferred_alloc);
        },
        else => unreachable,
    }
}

fn storeToInferredAlloc(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    operand: Air.Inst.Ref,
    inferred_alloc: *Value.Payload.InferredAlloc,
) CompileError!void {
    const operand_ty = sema.typeOf(operand);
    // Create a runtime bitcast instruction with exactly the type the pointer wants.
    const target = sema.mod.getTarget();
    const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = operand_ty,
        .@"align" = inferred_alloc.data.alignment,
        .@"addrspace" = target_util.defaultAddressSpace(target, .local),
    });
    const bitcasted_ptr = try block.addBitCast(ptr_ty, ptr);
    // Add the stored instruction to the set we will use to resolve peer types
    // for the inferred allocation.
    try inferred_alloc.data.prongs.append(sema.arena, .{
        .stored_inst = operand,
        .placeholder = Air.refToIndex(bitcasted_ptr).?,
    });
    return sema.storePtr2(block, src, bitcasted_ptr, src, operand, src, .bitcast);
}

fn storeToInferredAllocComptime(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
    iac: *Value.Payload.InferredAllocComptime,
) CompileError!void {
    const operand_ty = sema.typeOf(operand);
    // There will be only one store_to_inferred_ptr because we are running at comptime.
    // The alloc will turn into a Decl.
    if (try sema.resolveMaybeUndefValAllowVariables(operand)) |operand_val| store: {
        if (operand_val.tag() == .variable) break :store;
        var anon_decl = try block.startAnonDecl();
        defer anon_decl.deinit();
        iac.data.decl_index = try anon_decl.finish(
            try operand_ty.copy(anon_decl.arena()),
            try operand_val.copy(anon_decl.arena()),
            iac.data.alignment,
        );
        return;
    }

    return sema.failWithNeededComptime(block, src, "value being stored to a comptime variable must be comptime-known");
}

fn zirSetEvalBranchQuota(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const quota = @intCast(u32, try sema.resolveInt(block, src, inst_data.operand, Type.u32, "eval branch quota must be comptime-known"));
    sema.branch_quota = @max(sema.branch_quota, quota);
}

fn zirStore(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const bin_inst = sema.code.instructions.items(.data)[inst].bin;
    const ptr = try sema.resolveInst(bin_inst.lhs);
    const value = try sema.resolveInst(bin_inst.rhs);
    return sema.storePtr(block, sema.src, ptr, value);
}

fn zirStoreNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const zir_tags = sema.code.instructions.items(.tag);
    const zir_datas = sema.code.instructions.items(.data);
    const inst_data = zir_datas[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const ptr = try sema.resolveInst(extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);

    const is_ret = if (Zir.refToIndex(extra.lhs)) |ptr_index|
        zir_tags[ptr_index] == .ret_ptr
    else
        false;

    // Check for the possibility of this pattern:
    //   %a = ret_ptr
    //   %b = store(%a, %c)
    // Where %c is an error union or error set. In such case we need to add
    // to the current function's inferred error set, if any.
    if (is_ret and (sema.typeOf(operand).zigTypeTag() == .ErrorUnion or
        sema.typeOf(operand).zigTypeTag() == .ErrorSet) and
        sema.fn_ret_ty.zigTypeTag() == .ErrorUnion)
    {
        try sema.addToInferredErrorSet(operand);
    }

    const ptr_src: LazySrcLoc = .{ .node_offset_store_ptr = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_store_operand = inst_data.src_node };
    const air_tag: Air.Inst.Tag = if (is_ret) .ret_ptr else .store;
    return sema.storePtr2(block, src, ptr, ptr_src, operand, operand_src, air_tag);
}

fn zirStr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const bytes = sema.code.instructions.items(.data)[inst].str.get(sema.code);
    return sema.addStrLit(block, bytes);
}

fn addStrLit(sema: *Sema, block: *Block, zir_bytes: []const u8) CompileError!Air.Inst.Ref {
    // `zir_bytes` references memory inside the ZIR module, which can get deallocated
    // after semantic analysis is complete, for example in the case of the initialization
    // expression of a variable declaration.
    const mod = sema.mod;
    const gpa = sema.gpa;
    const string_bytes = &mod.string_literal_bytes;
    const StringLiteralAdapter = Module.StringLiteralAdapter;
    const StringLiteralContext = Module.StringLiteralContext;
    try string_bytes.ensureUnusedCapacity(gpa, zir_bytes.len);
    const gop = try mod.string_literal_table.getOrPutContextAdapted(gpa, zir_bytes, StringLiteralAdapter{
        .bytes = string_bytes,
    }, StringLiteralContext{
        .bytes = string_bytes,
    });
    if (!gop.found_existing) {
        gop.key_ptr.* = .{
            .index = @intCast(u32, string_bytes.items.len),
            .len = @intCast(u32, zir_bytes.len),
        };
        string_bytes.appendSliceAssumeCapacity(zir_bytes);
        gop.value_ptr.* = .none;
    }
    const decl_index = gop.value_ptr.unwrap() orelse di: {
        var anon_decl = try block.startAnonDecl();
        defer anon_decl.deinit();

        const decl_index = try anon_decl.finish(
            try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), gop.key_ptr.len),
            try Value.Tag.str_lit.create(anon_decl.arena(), gop.key_ptr.*),
            0, // default alignment
        );

        // Needed so that `Decl.clearValues` will additionally set the corresponding
        // string literal table value back to `Decl.OptionalIndex.none`.
        mod.declPtr(decl_index).owns_tv = true;

        gop.value_ptr.* = decl_index.toOptional();
        break :di decl_index;
    };
    return sema.analyzeDeclRef(decl_index);
}

fn zirInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const tracy = trace(@src());
    defer tracy.end();

    const int = sema.code.instructions.items(.data)[inst].int;
    return sema.addIntUnsigned(Type.initTag(.comptime_int), int);
}

fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const tracy = trace(@src());
    defer tracy.end();

    const arena = sema.arena;
    const int = sema.code.instructions.items(.data)[inst].str;
    const byte_count = int.len * @sizeOf(std.math.big.Limb);
    const limb_bytes = sema.code.string_bytes[int.start..][0..byte_count];
    const limbs = try arena.alloc(std.math.big.Limb, int.len);
    mem.copy(u8, mem.sliceAsBytes(limbs), limb_bytes);

    return sema.addConstant(
        Type.initTag(.comptime_int),
        try Value.Tag.int_big_positive.create(arena, limbs),
    );
}

fn zirFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const arena = sema.arena;
    const number = sema.code.instructions.items(.data)[inst].float;
    return sema.addConstant(
        Type.initTag(.comptime_float),
        try Value.Tag.float_64.create(arena, number),
    );
}

fn zirFloat128(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const arena = sema.arena;
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data;
    const number = extra.get();
    return sema.addConstant(
        Type.initTag(.comptime_float),
        try Value.Tag.float_128.create(arena, number),
    );
}

fn zirCompileError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Index {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const msg = try sema.resolveConstString(block, operand_src, inst_data.operand, "compile error string must be comptime-known");
    return sema.fail(block, src, "{s}", .{msg});
}

fn zirCompileLog(
    sema: *Sema,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    var managed = sema.mod.compile_log_text.toManaged(sema.gpa);
    defer sema.mod.compile_log_text = managed.moveToUnmanaged();
    const writer = managed.writer();

    const extra = sema.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);
    const src_node = extra.data.src_node;
    const args = sema.code.refSlice(extra.end, extended.small);

    for (args, 0..) |arg_ref, i| {
        if (i != 0) try writer.print(", ", .{});

        const arg = try sema.resolveInst(arg_ref);
        const arg_ty = sema.typeOf(arg);
        if (try sema.resolveMaybeUndefVal(arg)) |val| {
            try sema.resolveLazyValue(val);
            try writer.print("@as({}, {})", .{
                arg_ty.fmt(sema.mod), val.fmtValue(arg_ty, sema.mod),
            });
        } else {
            try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(sema.mod)});
        }
    }
    try writer.print("\n", .{});

    const decl_index = if (sema.func) |some| some.owner_decl else sema.owner_decl_index;
    const gop = try sema.mod.compile_log_decls.getOrPut(sema.gpa, decl_index);
    if (!gop.found_existing) {
        gop.value_ptr.* = src_node;
    }
    return Air.Inst.Ref.void_value;
}

fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index, force_comptime: bool) CompileError!Zir.Inst.Index {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const msg_inst = try sema.resolveInst(inst_data.operand);

    if (block.is_comptime or force_comptime) {
        return sema.fail(block, src, "encountered @panic at comptime", .{});
    }
    try sema.panicWithMsg(block, src, msg_inst);
    return always_noreturn;
}

fn zirTrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Index {
    const src_node = sema.code.instructions.items(.data)[inst].node;
    const src = LazySrcLoc.nodeOffset(src_node);
    sema.src = src;
    _ = try block.addNoOp(.trap);
    return always_noreturn;
}

fn zirLoop(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];
    const gpa = sema.gpa;

    // AIR expects a block outside the loop block too.
    // Reserve space for a Loop instruction so that generated Break instructions can
    // point to it, even if it doesn't end up getting used because the code ends up being
    // comptime evaluated.
    const block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
    const loop_inst = block_inst + 1;
    try sema.air_instructions.ensureUnusedCapacity(gpa, 2);
    sema.air_instructions.appendAssumeCapacity(.{
        .tag = .block,
        .data = undefined,
    });
    sema.air_instructions.appendAssumeCapacity(.{
        .tag = .loop,
        .data = .{ .ty_pl = .{
            .ty = .noreturn_type,
            .payload = undefined,
        } },
    });
    var label: Block.Label = .{
        .zir_block = inst,
        .merges = .{
            .results = .{},
            .br_list = .{},
            .block_inst = block_inst,
        },
    };
    var child_block = parent_block.makeSubBlock();
    child_block.label = &label;
    child_block.runtime_cond = null;
    child_block.runtime_loop = src;
    child_block.runtime_index.increment();
    const merges = &child_block.label.?.merges;

    defer child_block.instructions.deinit(gpa);
    defer merges.results.deinit(gpa);
    defer merges.br_list.deinit(gpa);

    var loop_block = child_block.makeSubBlock();
    defer loop_block.instructions.deinit(gpa);

    try sema.analyzeBody(&loop_block, body);

    try child_block.instructions.append(gpa, loop_inst);

    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
        loop_block.instructions.items.len);
    sema.air_instructions.items(.data)[loop_inst].ty_pl.payload = sema.addExtraAssumeCapacity(
        Air.Block{ .body_len = @intCast(u32, loop_block.instructions.items.len) },
    );
    sema.air_extra.appendSliceAssumeCapacity(loop_block.instructions.items);
    return sema.analyzeBlockBody(parent_block, src, &child_block, merges);
}

fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const pl_node = sema.code.instructions.items(.data)[inst].pl_node;
    const src = pl_node.src();
    const extra = sema.code.extraData(Zir.Inst.Block, pl_node.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];

    // we check this here to avoid undefined symbols
    if (!@import("build_options").have_llvm)
        return sema.fail(parent_block, src, "cannot do C import on Zig compiler not built with LLVM-extension", .{});

    var c_import_buf = std.ArrayList(u8).init(sema.gpa);
    defer c_import_buf.deinit();

    var comptime_reason: Block.ComptimeReason = .{ .c_import = .{
        .block = parent_block,
        .src = src,
    } };
    var child_block: Block = .{
        .parent = parent_block,
        .sema = sema,
        .src_decl = parent_block.src_decl,
        .namespace = parent_block.namespace,
        .wip_capture_scope = parent_block.wip_capture_scope,
        .instructions = .{},
        .inlining = parent_block.inlining,
        .is_comptime = true,
        .comptime_reason = &comptime_reason,
        .c_import_buf = &c_import_buf,
        .runtime_cond = parent_block.runtime_cond,
        .runtime_loop = parent_block.runtime_loop,
        .runtime_index = parent_block.runtime_index,
    };
    defer child_block.instructions.deinit(sema.gpa);

    // Ignore the result, all the relevant operations have written to c_import_buf already.
    _ = try sema.analyzeBodyBreak(&child_block, body);

    const mod = sema.mod;
    const c_import_res = mod.comp.cImport(c_import_buf.items) catch |err|
        return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});

    if (c_import_res.errors.len != 0) {
        const msg = msg: {
            defer @import("clang.zig").ErrorMsg.delete(c_import_res.errors.ptr, c_import_res.errors.len);

            const msg = try sema.errMsg(&child_block, src, "C import failed", .{});
            errdefer msg.destroy(sema.gpa);

            if (!mod.comp.bin_file.options.link_libc)
                try sema.errNote(&child_block, src, msg, "libc headers not available; compilation does not link against libc", .{});

            const gop = try sema.mod.cimport_errors.getOrPut(sema.gpa, sema.owner_decl_index);
            if (!gop.found_existing) {
                var errs = try std.ArrayListUnmanaged(Module.CImportError).initCapacity(sema.gpa, c_import_res.errors.len);
                errdefer {
                    for (errs.items) |err| err.deinit(sema.gpa);
                    errs.deinit(sema.gpa);
                }

                for (c_import_res.errors) |c_error| {
                    const path = if (c_error.filename_ptr) |some|
                        try sema.gpa.dupeZ(u8, some[0..c_error.filename_len])
                    else
                        null;
                    errdefer if (path) |some| sema.gpa.free(some);

                    const c_msg = try sema.gpa.dupeZ(u8, c_error.msg_ptr[0..c_error.msg_len]);
                    errdefer sema.gpa.free(c_msg);

                    const line = line: {
                        const source = c_error.source orelse break :line null;
                        var start = c_error.offset;
                        while (start > 0) : (start -= 1) {
                            if (source[start - 1] == '\n') break;
                        }
                        var end = c_error.offset;
                        while (true) : (end += 1) {
                            if (source[end] == 0) break;
                            if (source[end] == '\n') break;
                        }
                        break :line try sema.gpa.dupeZ(u8, source[start..end]);
                    };
                    errdefer if (line) |some| sema.gpa.free(some);

                    errs.appendAssumeCapacity(.{
                        .path = path orelse null,
                        .source_line = line orelse null,
                        .line = c_error.line,
                        .column = c_error.column,
                        .offset = c_error.offset,
                        .msg = c_msg,
                    });
                }
                gop.value_ptr.* = errs.items;
            }
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    const c_import_pkg = Package.create(
        sema.gpa,
        null,
        c_import_res.out_zig_path,
    ) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        else => unreachable, // we pass null for root_src_dir_path
    };

    const result = mod.importPkg(c_import_pkg) catch |err|
        return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});

    mod.astGenFile(result.file) catch |err|
        return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});

    try mod.semaFile(result.file);
    const file_root_decl_index = result.file.root_decl.unwrap().?;
    const file_root_decl = mod.declPtr(file_root_decl_index);
    try mod.declareDeclDependency(sema.owner_decl_index, file_root_decl_index);
    return sema.addConstant(file_root_decl.ty, file_root_decl.val);
}

fn zirSuspendBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    return sema.failWithUseOfAsync(parent_block, src);
}

fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const pl_node = sema.code.instructions.items(.data)[inst].pl_node;
    const src = pl_node.src();
    const extra = sema.code.extraData(Zir.Inst.Block, pl_node.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];
    const gpa = sema.gpa;

    // Reserve space for a Block instruction so that generated Break instructions can
    // point to it, even if it doesn't end up getting used because the code ends up being
    // comptime evaluated or is an unlabeled block.
    const block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
    try sema.air_instructions.append(gpa, .{
        .tag = .block,
        .data = undefined,
    });

    var label: Block.Label = .{
        .zir_block = inst,
        .merges = .{
            .results = .{},
            .br_list = .{},
            .block_inst = block_inst,
        },
    };

    var child_block: Block = .{
        .parent = parent_block,
        .sema = sema,
        .src_decl = parent_block.src_decl,
        .namespace = parent_block.namespace,
        .wip_capture_scope = parent_block.wip_capture_scope,
        .instructions = .{},
        .label = &label,
        .inlining = parent_block.inlining,
        .is_comptime = parent_block.is_comptime,
        .comptime_reason = parent_block.comptime_reason,
        .is_typeof = parent_block.is_typeof,
        .want_safety = parent_block.want_safety,
        .float_mode = parent_block.float_mode,
        .c_import_buf = parent_block.c_import_buf,
        .runtime_cond = parent_block.runtime_cond,
        .runtime_loop = parent_block.runtime_loop,
        .runtime_index = parent_block.runtime_index,
        .error_return_trace_index = parent_block.error_return_trace_index,
    };

    defer child_block.instructions.deinit(gpa);
    defer label.merges.results.deinit(gpa);
    defer label.merges.br_list.deinit(gpa);

    return sema.resolveBlockBody(parent_block, src, &child_block, body, inst, &label.merges);
}

fn resolveBlockBody(
    sema: *Sema,
    parent_block: *Block,
    src: LazySrcLoc,
    child_block: *Block,
    body: []const Zir.Inst.Index,
    /// This is the instruction that a break instruction within `body` can
    /// use to return from the body.
    body_inst: Zir.Inst.Index,
    merges: *Block.Merges,
) CompileError!Air.Inst.Ref {
    if (child_block.is_comptime) {
        return sema.resolveBody(child_block, body, body_inst);
    } else {
        if (sema.analyzeBodyInner(child_block, body)) |_| {
            return sema.analyzeBlockBody(parent_block, src, child_block, merges);
        } else |err| switch (err) {
            error.ComptimeBreak => {
                // Comptime control flow is happening, however child_block may still contain
                // runtime instructions which need to be copied to the parent block.
                try parent_block.instructions.appendSlice(sema.gpa, child_block.instructions.items);

                const break_inst = sema.comptime_break_inst;
                const break_data = sema.code.instructions.items(.data)[break_inst].@"break";
                if (break_data.block_inst == body_inst) {
                    return try sema.resolveInst(break_data.operand);
                } else {
                    return error.ComptimeBreak;
                }
            },
            else => |e| return e,
        }
    }
}

fn analyzeBlockBody(
    sema: *Sema,
    parent_block: *Block,
    src: LazySrcLoc,
    child_block: *Block,
    merges: *Block.Merges,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const gpa = sema.gpa;
    const mod = sema.mod;

    // Blocks must terminate with noreturn instruction.
    assert(child_block.instructions.items.len != 0);
    assert(sema.typeOf(Air.indexToRef(child_block.instructions.items[child_block.instructions.items.len - 1])).isNoReturn());

    if (merges.results.items.len == 0) {
        // No need for a block instruction. We can put the new instructions
        // directly into the parent block.
        try parent_block.instructions.appendSlice(gpa, child_block.instructions.items);
        return Air.indexToRef(child_block.instructions.items[child_block.instructions.items.len - 1]);
    }
    if (merges.results.items.len == 1) {
        const last_inst_index = child_block.instructions.items.len - 1;
        const last_inst = child_block.instructions.items[last_inst_index];
        if (sema.getBreakBlock(last_inst)) |br_block| {
            if (br_block == merges.block_inst) {
                // No need for a block instruction. We can put the new instructions directly
                // into the parent block. Here we omit the break instruction.
                const without_break = child_block.instructions.items[0..last_inst_index];
                try parent_block.instructions.appendSlice(gpa, without_break);
                return merges.results.items[0];
            }
        }
    }
    // It is impossible to have the number of results be > 1 in a comptime scope.
    assert(!child_block.is_comptime); // Should already got a compile error in the condbr condition.

    // Need to set the type and emit the Block instruction. This allows machine code generation
    // to emit a jump instruction to after the block when it encounters the break.
    try parent_block.instructions.append(gpa, merges.block_inst);
    const resolved_ty = try sema.resolvePeerTypes(parent_block, src, merges.results.items, .none);
    // TODO add note "missing else causes void value"

    const type_src = src; // TODO: better source location
    const valid_rt = try sema.validateRunTimeType(resolved_ty, false);
    if (!valid_rt) {
        const msg = msg: {
            const msg = try sema.errMsg(child_block, type_src, "value with comptime-only type '{}' depends on runtime control flow", .{resolved_ty.fmt(mod)});
            errdefer msg.destroy(sema.gpa);

            const runtime_src = child_block.runtime_cond orelse child_block.runtime_loop.?;
            try sema.errNote(child_block, runtime_src, msg, "runtime control flow here", .{});

            const child_src_decl = mod.declPtr(child_block.src_decl);
            try sema.explainWhyTypeIsComptime(child_block, type_src, msg, type_src.toSrcLoc(child_src_decl), resolved_ty);

            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    const ty_inst = try sema.addType(resolved_ty);
    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
        child_block.instructions.items.len);
    sema.air_instructions.items(.data)[merges.block_inst] = .{ .ty_pl = .{
        .ty = ty_inst,
        .payload = sema.addExtraAssumeCapacity(Air.Block{
            .body_len = @intCast(u32, child_block.instructions.items.len),
        }),
    } };
    sema.air_extra.appendSliceAssumeCapacity(child_block.instructions.items);
    // Now that the block has its type resolved, we need to go back into all the break
    // instructions, and insert type coercion on the operands.
    for (merges.br_list.items) |br| {
        const br_operand = sema.air_instructions.items(.data)[br].br.operand;
        const br_operand_src = src;
        const br_operand_ty = sema.typeOf(br_operand);
        if (br_operand_ty.eql(resolved_ty, mod)) {
            // No type coercion needed.
            continue;
        }
        var coerce_block = parent_block.makeSubBlock();
        defer coerce_block.instructions.deinit(gpa);
        const coerced_operand = try sema.coerce(&coerce_block, resolved_ty, br_operand, br_operand_src);
        // If no instructions were produced, such as in the case of a coercion of a
        // constant value to a new type, we can simply point the br operand to it.
        if (coerce_block.instructions.items.len == 0) {
            sema.air_instructions.items(.data)[br].br.operand = coerced_operand;
            continue;
        }
        assert(coerce_block.instructions.items[coerce_block.instructions.items.len - 1] ==
            Air.refToIndex(coerced_operand).?);

        // Convert the br instruction to a block instruction that has the coercion
        // and then a new br inside that returns the coerced instruction.
        const sub_block_len = @intCast(u32, coerce_block.instructions.items.len + 1);
        try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
            sub_block_len);
        try sema.air_instructions.ensureUnusedCapacity(gpa, 1);
        const sub_br_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);

        sema.air_instructions.items(.tag)[br] = .block;
        sema.air_instructions.items(.data)[br] = .{ .ty_pl = .{
            .ty = Air.Inst.Ref.noreturn_type,
            .payload = sema.addExtraAssumeCapacity(Air.Block{
                .body_len = sub_block_len,
            }),
        } };
        sema.air_extra.appendSliceAssumeCapacity(coerce_block.instructions.items);
        sema.air_extra.appendAssumeCapacity(sub_br_inst);

        sema.air_instructions.appendAssumeCapacity(.{
            .tag = .br,
            .data = .{ .br = .{
                .block_inst = merges.block_inst,
                .operand = coerced_operand,
            } },
        });
    }
    return Air.indexToRef(merges.block_inst);
}

fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Export, inst_data.payload_index).data;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const options_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const decl_name = sema.code.nullTerminatedString(extra.decl_name);
    const decl_index = if (extra.namespace != .none) index_blk: {
        const container_ty = try sema.resolveType(block, operand_src, extra.namespace);
        const container_namespace = container_ty.getNamespace().?;

        const maybe_index = try sema.lookupInNamespace(block, operand_src, container_namespace, decl_name, false);
        break :index_blk maybe_index orelse
            return sema.failWithBadMemberAccess(block, container_ty, operand_src, decl_name);
    } else try sema.lookupIdentifier(block, operand_src, decl_name);
    const options = sema.resolveExportOptions(block, .unneeded, extra.options) catch |err| switch (err) {
        error.NeededSourceLocation => {
            _ = try sema.resolveExportOptions(block, options_src, extra.options);
            unreachable;
        },
        else => |e| return e,
    };
    {
        try sema.mod.ensureDeclAnalyzed(decl_index);
        const exported_decl = sema.mod.declPtr(decl_index);
        if (exported_decl.val.castTag(.function)) |some| {
            return sema.analyzeExport(block, src, options, some.data.owner_decl);
        }
    }
    try sema.analyzeExport(block, src, options, decl_index);
}

fn zirExportValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.ExportValue, inst_data.payload_index).data;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const options_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const operand = try sema.resolveInstConst(block, operand_src, extra.operand, "export target must be comptime-known");
    const options = sema.resolveExportOptions(block, .unneeded, extra.options) catch |err| switch (err) {
        error.NeededSourceLocation => {
            _ = try sema.resolveExportOptions(block, options_src, extra.options);
            unreachable;
        },
        else => |e| return e,
    };
    const decl_index = switch (operand.val.tag()) {
        .function => operand.val.castTag(.function).?.data.owner_decl,
        else => return sema.fail(block, operand_src, "TODO implement exporting arbitrary Value objects", .{}), // TODO put this Value into an anonymous Decl and then export it.
    };
    try sema.analyzeExport(block, src, options, decl_index);
}

pub fn analyzeExport(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    borrowed_options: std.builtin.ExportOptions,
    exported_decl_index: Decl.Index,
) !void {
    const Export = Module.Export;
    const mod = sema.mod;

    if (borrowed_options.linkage == .Internal) {
        return;
    }

    try mod.ensureDeclAnalyzed(exported_decl_index);
    const exported_decl = mod.declPtr(exported_decl_index);

    if (!try sema.validateExternType(exported_decl.ty, .other)) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "unable to export type '{}'", .{exported_decl.ty.fmt(sema.mod)});
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsNotExtern(msg, src.toSrcLoc(src_decl), exported_decl.ty, .other);

            try sema.addDeclaredHereNote(msg, exported_decl.ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const gpa = mod.gpa;

    try mod.decl_exports.ensureUnusedCapacity(gpa, 1);
    try mod.export_owners.ensureUnusedCapacity(gpa, 1);

    const new_export = try gpa.create(Export);
    errdefer gpa.destroy(new_export);

    const symbol_name = try gpa.dupe(u8, borrowed_options.name);
    errdefer gpa.free(symbol_name);

    const section: ?[]const u8 = if (borrowed_options.section) |s| try gpa.dupe(u8, s) else null;
    errdefer if (section) |s| gpa.free(s);

    new_export.* = .{
        .options = .{
            .name = symbol_name,
            .linkage = borrowed_options.linkage,
            .section = section,
            .visibility = borrowed_options.visibility,
        },
        .src = src,
        .owner_decl = sema.owner_decl_index,
        .src_decl = block.src_decl,
        .exported_decl = exported_decl_index,
        .status = .in_progress,
    };

    // Add to export_owners table.
    const eo_gop = mod.export_owners.getOrPutAssumeCapacity(sema.owner_decl_index);
    if (!eo_gop.found_existing) {
        eo_gop.value_ptr.* = .{};
    }
    try eo_gop.value_ptr.append(gpa, new_export);
    errdefer _ = eo_gop.value_ptr.pop();

    // Add to exported_decl table.
    const de_gop = mod.decl_exports.getOrPutAssumeCapacity(exported_decl_index);
    if (!de_gop.found_existing) {
        de_gop.value_ptr.* = .{};
    }
    try de_gop.value_ptr.append(gpa, new_export);
    errdefer _ = de_gop.value_ptr.pop();
}

fn zirSetAlignStack(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const src = LazySrcLoc.nodeOffset(extra.node);
    const alignment = try sema.resolveAlign(block, operand_src, extra.operand);
    if (alignment > 256) {
        return sema.fail(block, src, "attempt to @setAlignStack({d}); maximum is 256", .{
            alignment,
        });
    }
    const func = sema.func orelse
        return sema.fail(block, src, "@setAlignStack outside function body", .{});

    const fn_owner_decl = sema.mod.declPtr(func.owner_decl);
    switch (fn_owner_decl.ty.fnCallingConvention()) {
        .Naked => return sema.fail(block, src, "@setAlignStack in naked function", .{}),
        .Inline => return sema.fail(block, src, "@setAlignStack in inline function", .{}),
        else => if (block.inlining != null) {
            return sema.fail(block, src, "@setAlignStack in inline call", .{});
        },
    }

    const gop = try sema.mod.align_stack_fns.getOrPut(sema.mod.gpa, func);
    if (gop.found_existing) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "multiple @setAlignStack in the same function body", .{});
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, gop.value_ptr.src, msg, "other instance here", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    gop.value_ptr.* = .{ .alignment = alignment, .src = src };
}

fn zirSetCold(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const is_cold = try sema.resolveConstBool(block, operand_src, extra.operand, "operand to @setCold must be comptime-known");
    const func = sema.func orelse return; // does nothing outside a function
    func.is_cold = is_cold;
}

fn zirSetFloatMode(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    block.float_mode = try sema.resolveBuiltinEnum(block, src, extra.operand, "FloatMode", "operand to @setFloatMode must be comptime-known");
}

fn zirSetRuntimeSafety(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    block.want_safety = try sema.resolveConstBool(block, operand_src, inst_data.operand, "operand to @setRuntimeSafety must be comptime-known");
}

fn zirFence(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
    if (block.is_comptime) return;

    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const order_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const order = try sema.resolveAtomicOrder(block, order_src, extra.operand, "atomic order of @fence must be comptime-known");

    if (@enumToInt(order) < @enumToInt(std.builtin.AtomicOrder.Acquire)) {
        return sema.fail(block, order_src, "atomic ordering must be Acquire or stricter", .{});
    }

    _ = try block.addInst(.{
        .tag = .fence,
        .data = .{ .fence = order },
    });
}

fn zirBreak(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Index {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].@"break";
    const operand = try sema.resolveInst(inst_data.operand);
    const zir_block = inst_data.block_inst;

    var block = start_block;
    while (true) {
        if (block.label) |label| {
            if (label.zir_block == zir_block) {
                const br_ref = try start_block.addBr(label.merges.block_inst, operand);
                try label.merges.results.append(sema.gpa, operand);
                try label.merges.br_list.append(sema.gpa, Air.refToIndex(br_ref).?);
                block.runtime_index.increment();
                if (block.runtime_cond == null and block.runtime_loop == null) {
                    block.runtime_cond = start_block.runtime_cond orelse start_block.runtime_loop;
                    block.runtime_loop = start_block.runtime_loop;
                }
                return inst;
            }
        }
        block = block.parent.?;
    }
}

fn zirDbgStmt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    // We do not set sema.src here because dbg_stmt instructions are only emitted for
    // ZIR code that possibly will need to generate runtime code. So error messages
    // and other source locations must not rely on sema.src being set from dbg_stmt
    // instructions.
    if (block.is_comptime or sema.mod.comp.bin_file.options.strip) return;

    const inst_data = sema.code.instructions.items(.data)[inst].dbg_stmt;
    _ = try block.addInst(.{
        .tag = .dbg_stmt,
        .data = .{ .dbg_stmt = .{
            .line = inst_data.line,
            .column = inst_data.column,
        } },
    });
}

fn zirDbgBlockBegin(sema: *Sema, block: *Block) CompileError!void {
    if (block.is_comptime or sema.mod.comp.bin_file.options.strip) return;

    _ = try block.addInst(.{
        .tag = .dbg_block_begin,
        .data = undefined,
    });
}

fn zirDbgBlockEnd(sema: *Sema, block: *Block) CompileError!void {
    if (block.is_comptime or sema.mod.comp.bin_file.options.strip) return;

    _ = try block.addInst(.{
        .tag = .dbg_block_end,
        .data = undefined,
    });
}

fn zirDbgVar(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    air_tag: Air.Inst.Tag,
) CompileError!void {
    if (block.is_comptime or sema.mod.comp.bin_file.options.strip) return;

    const str_op = sema.code.instructions.items(.data)[inst].str_op;
    const operand = try sema.resolveInst(str_op.operand);
    const name = str_op.getStr(sema.code);
    try sema.addDbgVar(block, operand, air_tag, name);
}

fn addDbgVar(
    sema: *Sema,
    block: *Block,
    operand: Air.Inst.Ref,
    air_tag: Air.Inst.Tag,
    name: []const u8,
) CompileError!void {
    const operand_ty = sema.typeOf(operand);
    switch (air_tag) {
        .dbg_var_ptr => {
            if (!(try sema.typeHasRuntimeBits(operand_ty.childType()))) return;
        },
        .dbg_var_val => {
            if (!(try sema.typeHasRuntimeBits(operand_ty))) return;
        },
        else => unreachable,
    }

    try sema.queueFullTypeResolution(operand_ty);

    // Add the name to the AIR.
    const name_extra_index = @intCast(u32, sema.air_extra.items.len);
    const elements_used = name.len / 4 + 1;
    try sema.air_extra.ensureUnusedCapacity(sema.gpa, elements_used);
    const buffer = mem.sliceAsBytes(sema.air_extra.unusedCapacitySlice());
    mem.copy(u8, buffer, name);
    buffer[name.len] = 0;
    sema.air_extra.items.len += elements_used;

    _ = try block.addInst(.{
        .tag = air_tag,
        .data = .{ .pl_op = .{
            .payload = name_extra_index,
            .operand = operand,
        } },
    });
}

fn zirDeclRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const src = inst_data.src();
    const decl_name = inst_data.get(sema.code);
    const decl_index = try sema.lookupIdentifier(block, src, decl_name);
    try sema.addReferencedBy(block, src, decl_index);
    return sema.analyzeDeclRef(decl_index);
}

fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const src = inst_data.src();
    const decl_name = inst_data.get(sema.code);
    const decl = try sema.lookupIdentifier(block, src, decl_name);
    return sema.analyzeDeclVal(block, src, decl);
}

fn lookupIdentifier(sema: *Sema, block: *Block, src: LazySrcLoc, name: []const u8) !Decl.Index {
    var namespace = block.namespace;
    while (true) {
        if (try sema.lookupInNamespace(block, src, namespace, name, false)) |decl_index| {
            return decl_index;
        }
        namespace = namespace.parent orelse break;
    }
    unreachable; // AstGen detects use of undeclared identifier errors.
}

/// This looks up a member of a specific namespace. It is affected by `usingnamespace` but
/// only for ones in the specified namespace.
fn lookupInNamespace(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    namespace: *Namespace,
    ident_name: []const u8,
    observe_usingnamespace: bool,
) CompileError!?Decl.Index {
    const mod = sema.mod;

    const namespace_decl_index = namespace.getDeclIndex();
    const namespace_decl = sema.mod.declPtr(namespace_decl_index);
    if (namespace_decl.analysis == .file_failure) {
        try mod.declareDeclDependency(sema.owner_decl_index, namespace_decl_index);
        return error.AnalysisFail;
    }

    if (observe_usingnamespace and namespace.usingnamespace_set.count() != 0) {
        const src_file = block.namespace.file_scope;

        const gpa = sema.gpa;
        var checked_namespaces: std.AutoArrayHashMapUnmanaged(*Namespace, bool) = .{};
        defer checked_namespaces.deinit(gpa);

        // Keep track of name conflicts for error notes.
        var candidates: std.ArrayListUnmanaged(Decl.Index) = .{};
        defer candidates.deinit(gpa);

        try checked_namespaces.put(gpa, namespace, namespace.file_scope == src_file);
        var check_i: usize = 0;

        while (check_i < checked_namespaces.count()) : (check_i += 1) {
            const check_ns = checked_namespaces.keys()[check_i];
            if (check_ns.decls.getKeyAdapted(ident_name, Module.DeclAdapter{ .mod = mod })) |decl_index| {
                // Skip decls which are not marked pub, which are in a different
                // file than the `a.b`/`@hasDecl` syntax.
                const decl = mod.declPtr(decl_index);
                if (decl.is_pub or (src_file == decl.getFileScope() and checked_namespaces.values()[check_i])) {
                    try candidates.append(gpa, decl_index);
                }
            }
            var it = check_ns.usingnamespace_set.iterator();
            while (it.next()) |entry| {
                const sub_usingnamespace_decl_index = entry.key_ptr.*;
                // Skip the decl we're currently analysing.
                if (sub_usingnamespace_decl_index == sema.owner_decl_index) continue;
                const sub_usingnamespace_decl = mod.declPtr(sub_usingnamespace_decl_index);
                const sub_is_pub = entry.value_ptr.*;
                if (!sub_is_pub and src_file != sub_usingnamespace_decl.getFileScope()) {
                    // Skip usingnamespace decls which are not marked pub, which are in
                    // a different file than the `a.b`/`@hasDecl` syntax.
                    continue;
                }
                try sema.ensureDeclAnalyzed(sub_usingnamespace_decl_index);
                const ns_ty = sub_usingnamespace_decl.val.castTag(.ty).?.data;
                const sub_ns = ns_ty.getNamespace().?;
                try checked_namespaces.put(gpa, sub_ns, src_file == sub_usingnamespace_decl.getFileScope());
            }
        }

        {
            var i: usize = 0;
            while (i < candidates.items.len) {
                if (candidates.items[i] == sema.owner_decl_index) {
                    _ = candidates.orderedRemove(i);
                } else {
                    i += 1;
                }
            }
        }

        switch (candidates.items.len) {
            0 => {},
            1 => {
                const decl_index = candidates.items[0];
                try mod.declareDeclDependency(sema.owner_decl_index, decl_index);
                return decl_index;
            },
            else => {
                const msg = msg: {
                    const msg = try sema.errMsg(block, src, "ambiguous reference", .{});
                    errdefer msg.destroy(gpa);
                    for (candidates.items) |candidate_index| {
                        const candidate = mod.declPtr(candidate_index);
                        const src_loc = candidate.srcLoc();
                        try mod.errNoteNonLazy(src_loc, msg, "declared here", .{});
                    }
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            },
        }
    } else if (namespace.decls.getKeyAdapted(ident_name, Module.DeclAdapter{ .mod = mod })) |decl_index| {
        try mod.declareDeclDependency(sema.owner_decl_index, decl_index);
        return decl_index;
    }

    log.debug("{*} ({s}) depends on non-existence of '{s}' in {*} ({s})", .{
        sema.owner_decl, sema.owner_decl.name, ident_name, namespace_decl, namespace_decl.name,
    });
    // TODO This dependency is too strong. Really, it should only be a dependency
    // on the non-existence of `ident_name` in the namespace. We can lessen the number of
    // outdated declarations by making this dependency more sophisticated.
    try mod.declareDeclDependency(sema.owner_decl_index, namespace_decl_index);
    return null;
}

fn funcDeclSrc(sema: *Sema, func_inst: Air.Inst.Ref) !?*Decl {
    const func_val = (try sema.resolveMaybeUndefVal(func_inst)) orelse return null;
    if (func_val.isUndef()) return null;
    const owner_decl_index = switch (func_val.tag()) {
        .extern_fn => func_val.castTag(.extern_fn).?.data.owner_decl,
        .function => func_val.castTag(.function).?.data.owner_decl,
        .decl_ref => sema.mod.declPtr(func_val.castTag(.decl_ref).?.data).val.castTag(.function).?.data.owner_decl,
        else => return null,
    };
    return sema.mod.declPtr(owner_decl_index);
}

pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref {
    const src = sema.src;

    if (!sema.mod.backendSupportsFeature(.error_return_trace)) return .none;
    if (!sema.mod.comp.bin_file.options.error_return_tracing) return .none;

    if (block.is_comptime)
        return .none;

    const unresolved_stack_trace_ty = sema.getBuiltinType("StackTrace") catch |err| switch (err) {
        error.NeededSourceLocation, error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
        else => |e| return e,
    };
    const stack_trace_ty = sema.resolveTypeFields(unresolved_stack_trace_ty) catch |err| switch (err) {
        error.NeededSourceLocation, error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
        else => |e| return e,
    };
    const field_index = sema.structFieldIndex(block, stack_trace_ty, "index", src) catch |err| switch (err) {
        error.NeededSourceLocation, error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
        else => |e| return e,
    };

    return try block.addInst(.{
        .tag = .save_err_return_trace_index,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(stack_trace_ty),
            .payload = @intCast(u32, field_index),
        } },
    });
}

/// Add instructions to block to "pop" the error return trace.
/// If `operand` is provided, only pops if operand is non-error.
fn popErrorReturnTrace(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
    saved_error_trace_index: Air.Inst.Ref,
) CompileError!void {
    var is_non_error: ?bool = null;
    var is_non_error_inst: Air.Inst.Ref = undefined;
    if (operand != .none) {
        is_non_error_inst = try sema.analyzeIsNonErr(block, src, operand);
        if (try sema.resolveDefinedValue(block, src, is_non_error_inst)) |cond_val|
            is_non_error = cond_val.toBool();
    } else is_non_error = true; // no operand means pop unconditionally

    if (is_non_error == true) {
        // AstGen determined this result does not go to an error-handling expr (try/catch/return etc.), or
        // the result is comptime-known to be a non-error. Either way, pop unconditionally.

        const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
        const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
        const ptr_stack_trace_ty = try Type.Tag.single_mut_pointer.create(sema.arena, stack_trace_ty);
        const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
        const field_ptr = try sema.structFieldPtr(block, src, err_return_trace, "index", src, stack_trace_ty, true);
        try sema.storePtr2(block, src, field_ptr, src, saved_error_trace_index, src, .store);
    } else if (is_non_error == null) {
        // The result might be an error. If it is, we leave the error trace alone. If it isn't, we need
        // to pop any error trace that may have been propagated from our arguments.

        try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.Block).Struct.fields.len);
        const cond_block_inst = try block.addInstAsIndex(.{
            .tag = .block,
            .data = .{
                .ty_pl = .{
                    .ty = Air.Inst.Ref.void_type,
                    .payload = undefined, // updated below
                },
            },
        });

        var then_block = block.makeSubBlock();
        defer then_block.instructions.deinit(sema.gpa);

        // If non-error, then pop the error return trace by restoring the index.
        const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
        const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
        const ptr_stack_trace_ty = try Type.Tag.single_mut_pointer.create(sema.arena, stack_trace_ty);
        const err_return_trace = try then_block.addTy(.err_return_trace, ptr_stack_trace_ty);
        const field_ptr = try sema.structFieldPtr(&then_block, src, err_return_trace, "index", src, stack_trace_ty, true);
        try sema.storePtr2(&then_block, src, field_ptr, src, saved_error_trace_index, src, .store);
        _ = try then_block.addBr(cond_block_inst, Air.Inst.Ref.void_value);

        // Otherwise, do nothing
        var else_block = block.makeSubBlock();
        defer else_block.instructions.deinit(sema.gpa);
        _ = try else_block.addBr(cond_block_inst, Air.Inst.Ref.void_value);

        try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.CondBr).Struct.fields.len +
            then_block.instructions.items.len + else_block.instructions.items.len +
            @typeInfo(Air.Block).Struct.fields.len + 1); // +1 for the sole .cond_br instruction in the .block

        const cond_br_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
        try sema.air_instructions.append(sema.gpa, .{ .tag = .cond_br, .data = .{ .pl_op = .{
            .operand = is_non_error_inst,
            .payload = sema.addExtraAssumeCapacity(Air.CondBr{
                .then_body_len = @intCast(u32, then_block.instructions.items.len),
                .else_body_len = @intCast(u32, else_block.instructions.items.len),
            }),
        } } });
        sema.air_extra.appendSliceAssumeCapacity(then_block.instructions.items);
        sema.air_extra.appendSliceAssumeCapacity(else_block.instructions.items);

        sema.air_instructions.items(.data)[cond_block_inst].ty_pl.payload = sema.addExtraAssumeCapacity(Air.Block{ .body_len = 1 });
        sema.air_extra.appendAssumeCapacity(cond_br_inst);
    }
}

fn zirCall(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const func_src: LazySrcLoc = .{ .node_offset_call_func = inst_data.src_node };
    const call_src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Call, inst_data.payload_index);
    const args_len = extra.data.flags.args_len;

    const modifier = @intToEnum(std.builtin.CallModifier, extra.data.flags.packed_modifier);
    const ensure_result_used = extra.data.flags.ensure_result_used;
    const pop_error_return_trace = extra.data.flags.pop_error_return_trace;

    var func = try sema.resolveInst(extra.data.callee);
    var resolved_args: []Air.Inst.Ref = undefined;
    var arg_index: u32 = 0;

    const func_type = sema.typeOf(func);

    // Desugar bound functions here
    var bound_arg_src: ?LazySrcLoc = null;
    if (func_type.tag() == .bound_fn) {
        bound_arg_src = func_src;
        const bound_func = try sema.resolveValue(block, .unneeded, func, "");
        const bound_data = &bound_func.cast(Value.Payload.BoundFn).?.data;
        func = bound_data.func_inst;
        resolved_args = try sema.arena.alloc(Air.Inst.Ref, args_len + 1);
        resolved_args[arg_index] = bound_data.arg0_inst;
        arg_index += 1;
    } else {
        resolved_args = try sema.arena.alloc(Air.Inst.Ref, args_len);
    }
    const total_args = args_len + @boolToInt(bound_arg_src != null);

    const callee_ty = sema.typeOf(func);
    const func_ty = func_ty: {
        switch (callee_ty.zigTypeTag()) {
            .Fn => break :func_ty callee_ty,
            .Pointer => {
                const ptr_info = callee_ty.ptrInfo().data;
                if (ptr_info.size == .One and ptr_info.pointee_type.zigTypeTag() == .Fn) {
                    break :func_ty ptr_info.pointee_type;
                }
            },
            else => {},
        }
        return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(sema.mod)});
    };
    const func_ty_info = func_ty.fnInfo();

    const fn_params_len = func_ty_info.param_types.len;
    check_args: {
        if (func_ty_info.is_var_args) {
            assert(func_ty_info.cc == .C);
            if (total_args >= fn_params_len) break :check_args;
        } else if (fn_params_len == total_args) {
            break :check_args;
        }

        const maybe_decl = try sema.funcDeclSrc(func);
        const member_str = if (bound_arg_src != null) "member function " else "";
        const variadic_str = if (func_ty_info.is_var_args) "at least " else "";
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                func_src,
                "{s}expected {s}{d} argument(s), found {d}",
                .{
                    member_str,
                    variadic_str,
                    fn_params_len - @boolToInt(bound_arg_src != null),
                    args_len,
                },
            );
            errdefer msg.destroy(sema.gpa);

            if (maybe_decl) |fn_decl| try sema.mod.errNoteNonLazy(fn_decl.srcLoc(), msg, "function declared here", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const args_body = sema.code.extra[extra.end..];

    var input_is_error = false;
    const block_index = @intCast(Air.Inst.Index, block.instructions.items.len);

    const parent_comptime = block.is_comptime;
    // `extra_index` and `arg_index` are separate since the bound function is passed as the first argument.
    var extra_index: usize = 0;
    var arg_start: u32 = args_len;
    while (extra_index < args_len) : ({
        extra_index += 1;
        arg_index += 1;
    }) {
        const arg_end = sema.code.extra[extra.end + extra_index];
        defer arg_start = arg_end;

        const param_ty = if (arg_index >= fn_params_len or
            func_ty_info.param_types[arg_index].tag() == .generic_poison)
            Type.initTag(.var_args_param)
        else
            func_ty_info.param_types[arg_index];

        // Generate args to comptime params in comptime block.
        defer block.is_comptime = parent_comptime;
        if (arg_index < fn_params_len and func_ty_info.comptime_params[arg_index]) {
            block.is_comptime = true;
            // TODO set comptime_reason
        }

        const param_ty_inst = try sema.addType(param_ty);
        sema.inst_map.putAssumeCapacity(inst, param_ty_inst);

        const resolved = try sema.resolveBody(block, args_body[arg_start..arg_end], inst);
        const resolved_ty = sema.typeOf(resolved);
        if (resolved_ty.zigTypeTag() == .NoReturn) {
            return resolved;
        }
        if (resolved_ty.isError()) {
            input_is_error = true;
        }
        resolved_args[arg_index] = resolved;
    }
    if (sema.owner_func == null or !sema.owner_func.?.calls_or_awaits_errorable_fn)
        input_is_error = false; // input was an error type, but no errorable fn's were actually called

    if (sema.mod.backendSupportsFeature(.error_return_trace) and sema.mod.comp.bin_file.options.error_return_tracing and
        !block.is_comptime and !block.is_typeof and (input_is_error or pop_error_return_trace))
    {
        const call_inst: Air.Inst.Ref = if (modifier == .always_tail) undefined else b: {
            break :b try sema.analyzeCall(block, func, func_src, call_src, modifier, ensure_result_used, resolved_args, bound_arg_src);
        };

        const return_ty = sema.typeOf(call_inst);
        if (modifier != .always_tail and return_ty.isNoReturn())
            return call_inst; // call to "fn(...) noreturn", don't pop

        // If any input is an error-type, we might need to pop any trace it generated. Otherwise, we only
        // need to clean-up our own trace if we were passed to a non-error-handling expression.
        if (input_is_error or (pop_error_return_trace and modifier != .always_tail and return_ty.isError())) {
            const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
            const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
            const field_index = try sema.structFieldIndex(block, stack_trace_ty, "index", call_src);

            // Insert a save instruction before the arg resolution + call instructions we just generated
            const save_inst = try block.insertInst(block_index, .{
                .tag = .save_err_return_trace_index,
                .data = .{ .ty_pl = .{
                    .ty = try sema.addType(stack_trace_ty),
                    .payload = @intCast(u32, field_index),
                } },
            });

            // Pop the error return trace, testing the result for non-error if necessary
            const operand = if (pop_error_return_trace or modifier == .always_tail) .none else call_inst;
            try sema.popErrorReturnTrace(block, call_src, operand, save_inst);
        }

        if (modifier == .always_tail) // Perform the call *after* the restore, so that a tail call is possible.
            return sema.analyzeCall(block, func, func_src, call_src, modifier, ensure_result_used, resolved_args, bound_arg_src);

        return call_inst;
    } else {
        return sema.analyzeCall(block, func, func_src, call_src, modifier, ensure_result_used, resolved_args, bound_arg_src);
    }
}

const GenericCallAdapter = struct {
    generic_fn: *Module.Fn,
    precomputed_hash: u64,
    func_ty_info: Type.Payload.Function.Data,
    args: []const Arg,
    module: *Module,

    const Arg = struct {
        ty: Type,
        val: Value,
        is_anytype: bool,
    };

    pub fn eql(ctx: @This(), adapted_key: void, other_key: *Module.Fn) bool {
        _ = adapted_key;
        // Checking for equality may happen on an item that has been inserted
        // into the map but is not yet fully initialized. In such case, the
        // two initialized fields are `hash` and `generic_owner_decl`.
        if (ctx.generic_fn.owner_decl != other_key.generic_owner_decl.unwrap().?) return false;

        const other_comptime_args = other_key.comptime_args.?;
        for (other_comptime_args[0..ctx.func_ty_info.param_types.len], 0..) |other_arg, i| {
            const this_arg = ctx.args[i];
            const this_is_comptime = this_arg.val.tag() != .generic_poison;
            const other_is_comptime = other_arg.val.tag() != .generic_poison;
            const this_is_anytype = this_arg.is_anytype;
            const other_is_anytype = other_key.isAnytypeParam(ctx.module, @intCast(u32, i));

            if (other_is_anytype != this_is_anytype) return false;
            if (other_is_comptime != this_is_comptime) return false;

            if (this_is_anytype) {
                // Both are anytype parameters.
                if (!this_arg.ty.eql(other_arg.ty, ctx.module)) {
                    return false;
                }
                if (this_is_comptime) {
                    // Both are comptime and anytype parameters with matching types.
                    if (!this_arg.val.eql(other_arg.val, other_arg.ty, ctx.module)) {
                        return false;
                    }
                }
            } else if (this_is_comptime) {
                // Both are comptime parameters but not anytype parameters.
                // We assert no error is possible here because any lazy values must be resolved
                // before inserting into the generic function hash map.
                const is_eql = Value.eqlAdvanced(
                    this_arg.val,
                    this_arg.ty,
                    other_arg.val,
                    other_arg.ty,
                    ctx.module,
                    null,
                ) catch unreachable;
                if (!is_eql) {
                    return false;
                }
            }
        }
        return true;
    }

    /// The implementation of the hash is in semantic analysis of function calls, so
    /// that any errors when computing the hash can be properly reported.
    pub fn hash(ctx: @This(), adapted_key: void) u64 {
        _ = adapted_key;
        return ctx.precomputed_hash;
    }
};

fn analyzeCall(
    sema: *Sema,
    block: *Block,
    func: Air.Inst.Ref,
    func_src: LazySrcLoc,
    call_src: LazySrcLoc,
    modifier: std.builtin.CallModifier,
    ensure_result_used: bool,
    uncasted_args: []const Air.Inst.Ref,
    bound_arg_src: ?LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const mod = sema.mod;

    const callee_ty = sema.typeOf(func);
    const func_ty = func_ty: {
        switch (callee_ty.zigTypeTag()) {
            .Fn => break :func_ty callee_ty,
            .Pointer => {
                const ptr_info = callee_ty.ptrInfo().data;
                if (ptr_info.size == .One and ptr_info.pointee_type.zigTypeTag() == .Fn) {
                    break :func_ty ptr_info.pointee_type;
                }
            },
            else => {},
        }
        return sema.fail(block, func_src, "type '{}' is not a function", .{callee_ty.fmt(sema.mod)});
    };

    const func_ty_info = func_ty.fnInfo();
    const cc = func_ty_info.cc;
    if (cc == .Naked) {
        const maybe_decl = try sema.funcDeclSrc(func);
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                func_src,
                "unable to call function with naked calling convention",
                .{},
            );
            errdefer msg.destroy(sema.gpa);

            if (maybe_decl) |fn_decl| try sema.mod.errNoteNonLazy(fn_decl.srcLoc(), msg, "function declared here", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    const fn_params_len = func_ty_info.param_types.len;
    if (func_ty_info.is_var_args) {
        assert(cc == .C);
        if (uncasted_args.len < fn_params_len) {
            // TODO add error note: declared here
            return sema.fail(
                block,
                func_src,
                "expected at least {d} argument(s), found {d}",
                .{ fn_params_len, uncasted_args.len },
            );
        }
    } else if (fn_params_len != uncasted_args.len) {
        // TODO add error note: declared here
        return sema.fail(
            block,
            call_src,
            "expected {d} argument(s), found {d}",
            .{ fn_params_len, uncasted_args.len },
        );
    }

    const call_tag: Air.Inst.Tag = switch (modifier) {
        .auto,
        .always_inline,
        .compile_time,
        .no_async,
        => Air.Inst.Tag.call,

        .never_tail => Air.Inst.Tag.call_never_tail,
        .never_inline => Air.Inst.Tag.call_never_inline,
        .always_tail => Air.Inst.Tag.call_always_tail,

        .async_kw => return sema.failWithUseOfAsync(block, call_src),
    };

    if (modifier == .never_inline and func_ty_info.cc == .Inline) {
        return sema.fail(block, call_src, "no-inline call of inline function", .{});
    }

    const gpa = sema.gpa;

    var is_generic_call = func_ty_info.is_generic;
    var is_comptime_call = block.is_comptime or modifier == .compile_time;
    var comptime_reason_buf: Block.ComptimeReason = undefined;
    var comptime_reason: ?*const Block.ComptimeReason = null;
    if (!is_comptime_call) {
        if (sema.typeRequiresComptime(func_ty_info.return_type)) |ct| {
            is_comptime_call = ct;
            if (ct) {
                // stage1 can't handle doing this directly
                comptime_reason_buf = .{ .comptime_ret_ty = .{
                    .block = block,
                    .func = func,
                    .func_src = func_src,
                    .return_ty = func_ty_info.return_type,
                } };
                comptime_reason = &comptime_reason_buf;
            }
        } else |err| switch (err) {
            error.GenericPoison => is_generic_call = true,
            else => |e| return e,
        }
    }
    var is_inline_call = is_comptime_call or modifier == .always_inline or
        func_ty_info.cc == .Inline;

    if (!is_inline_call and is_generic_call) {
        if (sema.instantiateGenericCall(
            block,
            func,
            func_src,
            call_src,
            func_ty_info,
            ensure_result_used,
            uncasted_args,
            call_tag,
            bound_arg_src,
        )) |some| {
            return some;
        } else |err| switch (err) {
            error.GenericPoison => {
                is_inline_call = true;
            },
            error.ComptimeReturn => {
                is_inline_call = true;
                is_comptime_call = true;
                // stage1 can't handle doing this directly
                comptime_reason_buf = .{ .comptime_ret_ty = .{
                    .block = block,
                    .func = func,
                    .func_src = func_src,
                    .return_ty = func_ty_info.return_type,
                } };
                comptime_reason = &comptime_reason_buf;
            },
            else => |e| return e,
        }
    }

    if (is_comptime_call and modifier == .never_inline) {
        return sema.fail(block, call_src, "unable to perform 'never_inline' call at compile-time", .{});
    }

    const result: Air.Inst.Ref = if (is_inline_call) res: {
        const func_val = sema.resolveConstValue(block, func_src, func, "function being called at comptime must be comptime-known") catch |err| {
            if (err == error.AnalysisFail and comptime_reason != null) try comptime_reason.?.explain(sema, sema.err);
            return err;
        };
        const module_fn = switch (func_val.tag()) {
            .decl_ref => mod.declPtr(func_val.castTag(.decl_ref).?.data).val.castTag(.function).?.data,
            .function => func_val.castTag(.function).?.data,
            .extern_fn => return sema.fail(block, call_src, "{s} call of extern function", .{
                @as([]const u8, if (is_comptime_call) "comptime" else "inline"),
            }),
            else => {
                assert(callee_ty.isPtrAtRuntime());
                return sema.fail(block, call_src, "{s} call of function pointer", .{
                    @as([]const u8, if (is_comptime_call) "comptime" else "inline"),
                });
            },
        };
        if (func_ty_info.is_var_args) {
            return sema.fail(block, call_src, "{s} call of variadic function", .{
                @as([]const u8, if (is_comptime_call) "comptime" else "inline"),
            });
        }

        // Analyze the ZIR. The same ZIR gets analyzed into a runtime function
        // or an inlined call depending on what union tag the `label` field is
        // set to in the `Block`.
        // This block instruction will be used to capture the return value from the
        // inlined function.
        const block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
        try sema.air_instructions.append(gpa, .{
            .tag = .block,
            .data = undefined,
        });
        // This one is shared among sub-blocks within the same callee, but not
        // shared among the entire inline/comptime call stack.
        var inlining: Block.Inlining = .{
            .func = null,
            .comptime_result = undefined,
            .merges = .{
                .results = .{},
                .br_list = .{},
                .block_inst = block_inst,
            },
        };
        // In order to save a bit of stack space, directly modify Sema rather
        // than create a child one.
        const parent_zir = sema.code;
        const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
        sema.code = fn_owner_decl.getFileScope().zir;
        defer sema.code = parent_zir;

        const parent_inst_map = sema.inst_map;
        sema.inst_map = .{};
        defer {
            sema.src = call_src;
            sema.inst_map.deinit(gpa);
            sema.inst_map = parent_inst_map;
        }

        const parent_func = sema.func;
        sema.func = module_fn;
        defer sema.func = parent_func;

        const parent_err_ret_index = sema.error_return_trace_index_on_fn_entry;
        sema.error_return_trace_index_on_fn_entry = block.error_return_trace_index;
        defer sema.error_return_trace_index_on_fn_entry = parent_err_ret_index;

        var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, fn_owner_decl.src_scope);
        defer wip_captures.deinit();

        var child_block: Block = .{
            .parent = null,
            .sema = sema,
            .src_decl = module_fn.owner_decl,
            .namespace = fn_owner_decl.src_namespace,
            .wip_capture_scope = wip_captures.scope,
            .instructions = .{},
            .label = null,
            .inlining = &inlining,
            .is_typeof = block.is_typeof,
            .is_comptime = is_comptime_call,
            .comptime_reason = comptime_reason,
            .error_return_trace_index = block.error_return_trace_index,
        };

        const merges = &child_block.inlining.?.merges;

        defer child_block.instructions.deinit(gpa);
        defer merges.results.deinit(gpa);
        defer merges.br_list.deinit(gpa);

        // If it's a comptime function call, we need to memoize it as long as no external
        // comptime memory is mutated.
        var memoized_call_key: Module.MemoizedCall.Key = undefined;
        var delete_memoized_call_key = false;
        defer if (delete_memoized_call_key) gpa.free(memoized_call_key.args);
        if (is_comptime_call) {
            memoized_call_key = .{
                .func = module_fn,
                .args = try gpa.alloc(TypedValue, func_ty_info.param_types.len),
            };
            delete_memoized_call_key = true;
        }

        try sema.emitBackwardBranch(block, call_src);

        // Whether this call should be memoized, set to false if the call can mutate
        // comptime state.
        var should_memoize = true;

        var new_fn_info = fn_owner_decl.ty.fnInfo();
        new_fn_info.param_types = try sema.arena.alloc(Type, new_fn_info.param_types.len);
        new_fn_info.comptime_params = (try sema.arena.alloc(bool, new_fn_info.param_types.len)).ptr;

        // This will have return instructions analyzed as break instructions to
        // the block_inst above. Here we are performing "comptime/inline semantic analysis"
        // for a function body, which means we must map the parameter ZIR instructions to
        // the AIR instructions of the callsite. The callee could be a generic function
        // which means its parameter type expressions must be resolved in order and used
        // to successively coerce the arguments.
        const fn_info = sema.code.getFnInfo(module_fn.zir_body_inst);
        try sema.inst_map.ensureSpaceForInstructions(sema.gpa, fn_info.param_body);

        var has_comptime_args = false;
        var arg_i: usize = 0;
        for (fn_info.param_body) |inst| {
            sema.analyzeInlineCallArg(
                block,
                &child_block,
                .unneeded,
                inst,
                new_fn_info,
                &arg_i,
                uncasted_args,
                is_comptime_call,
                &should_memoize,
                memoized_call_key,
                func_ty_info.param_types,
                func,
                &has_comptime_args,
            ) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    _ = sema.inst_map.remove(inst);
                    const decl = sema.mod.declPtr(block.src_decl);
                    try sema.analyzeInlineCallArg(
                        block,
                        &child_block,
                        Module.argSrc(call_src.node_offset.x, sema.gpa, decl, arg_i, bound_arg_src),
                        inst,
                        new_fn_info,
                        &arg_i,
                        uncasted_args,
                        is_comptime_call,
                        &should_memoize,
                        memoized_call_key,
                        func_ty_info.param_types,
                        func,
                        &has_comptime_args,
                    );
                    unreachable;
                },
                else => |e| return e,
            };
        }

        if (!has_comptime_args and module_fn.state == .sema_failure) return error.AnalysisFail;

        const recursive_msg = "inline call is recursive";
        var head = if (!has_comptime_args) block else null;
        while (head) |some| {
            const parent_inlining = some.inlining orelse break;
            if (parent_inlining.func == module_fn) {
                return sema.fail(block, call_src, recursive_msg, .{});
            }
            head = some.parent;
        }
        if (!has_comptime_args) inlining.func = module_fn;

        // In case it is a generic function with an expression for the return type that depends
        // on parameters, we must now do the same for the return type as we just did with
        // each of the parameters, resolving the return type and providing it to the child
        // `Sema` so that it can be used for the `ret_ptr` instruction.
        const ret_ty_inst = if (fn_info.ret_ty_body.len != 0)
            try sema.resolveBody(&child_block, fn_info.ret_ty_body, module_fn.zir_body_inst)
        else
            try sema.resolveInst(fn_info.ret_ty_ref);
        const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = 0 };
        const bare_return_type = try sema.analyzeAsType(&child_block, ret_ty_src, ret_ty_inst);
        // Create a fresh inferred error set type for inline/comptime calls.
        const fn_ret_ty = blk: {
            if (module_fn.hasInferredErrorSet(mod)) {
                const node = try sema.gpa.create(Module.Fn.InferredErrorSetListNode);
                node.data = .{ .func = module_fn };
                if (parent_func) |some| {
                    some.inferred_error_sets.prepend(node);
                }

                const error_set_ty = try Type.Tag.error_set_inferred.create(sema.arena, &node.data);
                break :blk try Type.Tag.error_union.create(sema.arena, .{
                    .error_set = error_set_ty,
                    .payload = bare_return_type,
                });
            }
            break :blk bare_return_type;
        };
        new_fn_info.return_type = fn_ret_ty;
        const parent_fn_ret_ty = sema.fn_ret_ty;
        sema.fn_ret_ty = fn_ret_ty;
        defer sema.fn_ret_ty = parent_fn_ret_ty;

        // This `res2` is here instead of directly breaking from `res` due to a stage1
        // bug generating invalid LLVM IR.
        const res2: Air.Inst.Ref = res2: {
            if (should_memoize and is_comptime_call) {
                if (mod.memoized_calls.getContext(memoized_call_key, .{ .module = mod })) |result| {
                    const ty_inst = try sema.addType(fn_ret_ty);
                    try sema.air_values.append(gpa, result.val);
                    sema.air_instructions.set(block_inst, .{
                        .tag = .constant,
                        .data = .{ .ty_pl = .{
                            .ty = ty_inst,
                            .payload = @intCast(u32, sema.air_values.items.len - 1),
                        } },
                    });
                    break :res2 Air.indexToRef(block_inst);
                }
            }

            const new_func_resolved_ty = try Type.Tag.function.create(sema.arena, new_fn_info);
            if (!is_comptime_call and !block.is_typeof) {
                try sema.emitDbgInline(block, parent_func.?, module_fn, new_func_resolved_ty, .dbg_inline_begin);

                const zir_tags = sema.code.instructions.items(.tag);
                for (fn_info.param_body) |param| switch (zir_tags[param]) {
                    .param, .param_comptime => {
                        const inst_data = sema.code.instructions.items(.data)[param].pl_tok;
                        const extra = sema.code.extraData(Zir.Inst.Param, inst_data.payload_index);
                        const param_name = sema.code.nullTerminatedString(extra.data.name);
                        const inst = sema.inst_map.get(param).?;

                        try sema.addDbgVar(&child_block, inst, .dbg_var_val, param_name);
                    },
                    .param_anytype, .param_anytype_comptime => {
                        const inst_data = sema.code.instructions.items(.data)[param].str_tok;
                        const param_name = inst_data.get(sema.code);
                        const inst = sema.inst_map.get(param).?;

                        try sema.addDbgVar(&child_block, inst, .dbg_var_val, param_name);
                    },
                    else => continue,
                };
            }

            if (is_comptime_call and ensure_result_used) {
                try sema.ensureResultUsed(block, fn_ret_ty, call_src);
            }

            const result = result: {
                sema.analyzeBody(&child_block, fn_info.body) catch |err| switch (err) {
                    error.ComptimeReturn => break :result inlining.comptime_result,
                    error.AnalysisFail => {
                        const err_msg = sema.err orelse return err;
                        if (std.mem.eql(u8, err_msg.msg, recursive_msg)) return err;
                        try sema.errNote(block, call_src, err_msg, "called from here", .{});
                        err_msg.clearTrace(sema.gpa);
                        return err;
                    },
                    else => |e| return e,
                };
                break :result try sema.analyzeBlockBody(block, call_src, &child_block, merges);
            };

            if (!is_comptime_call and !block.is_typeof and sema.typeOf(result).zigTypeTag() != .NoReturn) {
                try sema.emitDbgInline(
                    block,
                    module_fn,
                    parent_func.?,
                    mod.declPtr(parent_func.?.owner_decl).ty,
                    .dbg_inline_end,
                );
            }

            if (should_memoize and is_comptime_call) {
                const result_val = try sema.resolveConstMaybeUndefVal(block, .unneeded, result, "");

                // TODO: check whether any external comptime memory was mutated by the
                // comptime function call. If so, then do not memoize the call here.
                // TODO: re-evaluate whether memoized_calls needs its own arena. I think
                // it should be fine to use the Decl arena for the function.
                {
                    var arena_allocator = std.heap.ArenaAllocator.init(gpa);
                    errdefer arena_allocator.deinit();
                    const arena = arena_allocator.allocator();

                    for (memoized_call_key.args) |*arg| {
                        arg.* = try arg.*.copy(arena);
                    }

                    try mod.memoized_calls.putContext(gpa, memoized_call_key, .{
                        .val = try result_val.copy(arena),
                        .arena = arena_allocator.state,
                    }, .{ .module = mod });
                    delete_memoized_call_key = false;
                }
            }

            break :res2 result;
        };

        try wip_captures.finalize();

        break :res res2;
    } else res: {
        assert(!func_ty_info.is_generic);

        const args = try sema.arena.alloc(Air.Inst.Ref, uncasted_args.len);
        for (uncasted_args, 0..) |uncasted_arg, i| {
            if (i < fn_params_len) {
                const opts: CoerceOpts = .{ .param_src = .{
                    .func_inst = func,
                    .param_i = @intCast(u32, i),
                } };
                const param_ty = func_ty.fnParamType(i);
                args[i] = sema.analyzeCallArg(
                    block,
                    .unneeded,
                    param_ty,
                    uncasted_arg,
                    opts,
                ) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const decl = sema.mod.declPtr(block.src_decl);
                        _ = try sema.analyzeCallArg(
                            block,
                            Module.argSrc(call_src.node_offset.x, sema.gpa, decl, i, bound_arg_src),
                            param_ty,
                            uncasted_arg,
                            opts,
                        );
                        unreachable;
                    },
                    else => |e| return e,
                };
            } else {
                args[i] = sema.coerceVarArgParam(block, uncasted_arg, .unneeded) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const decl = sema.mod.declPtr(block.src_decl);
                        _ = try sema.coerceVarArgParam(
                            block,
                            uncasted_arg,
                            Module.argSrc(call_src.node_offset.x, sema.gpa, decl, i, bound_arg_src),
                        );
                        unreachable;
                    },
                    else => |e| return e,
                };
            }
        }

        try sema.queueFullTypeResolution(func_ty_info.return_type);
        if (sema.owner_func != null and func_ty_info.return_type.isError()) {
            sema.owner_func.?.calls_or_awaits_errorable_fn = true;
        }

        try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Call).Struct.fields.len +
            args.len);
        const func_inst = try block.addInst(.{
            .tag = call_tag,
            .data = .{ .pl_op = .{
                .operand = func,
                .payload = sema.addExtraAssumeCapacity(Air.Call{
                    .args_len = @intCast(u32, args.len),
                }),
            } },
        });
        sema.appendRefsAssumeCapacity(args);
        break :res func_inst;
    };

    if (ensure_result_used) {
        try sema.ensureResultUsed(block, sema.typeOf(result), call_src);
    }
    if (call_tag == .call_always_tail) {
        return sema.handleTailCall(block, call_src, func_ty, result);
    }
    return result;
}

fn handleTailCall(sema: *Sema, block: *Block, call_src: LazySrcLoc, func_ty: Type, result: Air.Inst.Ref) !Air.Inst.Ref {
    const target = sema.mod.getTarget();
    const backend = sema.mod.comp.getZigBackend();
    if (!target_util.supportsTailCall(target, backend)) {
        return sema.fail(block, call_src, "unable to perform tail call: compiler backend '{s}' does not support tail calls on target architecture '{s}' with the selected CPU feature flags", .{
            @tagName(backend), @tagName(target.cpu.arch),
        });
    }
    const func_decl = sema.mod.declPtr(sema.owner_func.?.owner_decl);
    if (!func_ty.eql(func_decl.ty, sema.mod)) {
        return sema.fail(block, call_src, "unable to perform tail call: type of function being called '{}' does not match type of calling function '{}'", .{
            func_ty.fmt(sema.mod), func_decl.ty.fmt(sema.mod),
        });
    }
    _ = try block.addUnOp(.ret, result);
    return Air.Inst.Ref.unreachable_value;
}

fn analyzeInlineCallArg(
    sema: *Sema,
    arg_block: *Block,
    param_block: *Block,
    arg_src: LazySrcLoc,
    inst: Zir.Inst.Index,
    new_fn_info: Type.Payload.Function.Data,
    arg_i: *usize,
    uncasted_args: []const Air.Inst.Ref,
    is_comptime_call: bool,
    should_memoize: *bool,
    memoized_call_key: Module.MemoizedCall.Key,
    raw_param_types: []const Type,
    func_inst: Air.Inst.Ref,
    has_comptime_args: *bool,
) !void {
    const zir_tags = sema.code.instructions.items(.tag);
    switch (zir_tags[inst]) {
        .param_comptime, .param_anytype_comptime => has_comptime_args.* = true,
        else => {},
    }
    switch (zir_tags[inst]) {
        .param, .param_comptime => {
            // Evaluate the parameter type expression now that previous ones have
            // been mapped, and coerce the corresponding argument to it.
            const pl_tok = sema.code.instructions.items(.data)[inst].pl_tok;
            const param_src = pl_tok.src();
            const extra = sema.code.extraData(Zir.Inst.Param, pl_tok.payload_index);
            const param_body = sema.code.extra[extra.end..][0..extra.data.body_len];
            const param_ty = param_ty: {
                const raw_param_ty = raw_param_types[arg_i.*];
                if (raw_param_ty.tag() != .generic_poison) break :param_ty raw_param_ty;
                const param_ty_inst = try sema.resolveBody(param_block, param_body, inst);
                break :param_ty try sema.analyzeAsType(param_block, param_src, param_ty_inst);
            };
            new_fn_info.param_types[arg_i.*] = param_ty;
            const uncasted_arg = uncasted_args[arg_i.*];
            if (try sema.typeRequiresComptime(param_ty)) {
                _ = sema.resolveConstMaybeUndefVal(arg_block, arg_src, uncasted_arg, "argument to parameter with comptime-only type must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and param_block.comptime_reason != null) try param_block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
            } else if (!is_comptime_call and zir_tags[inst] == .param_comptime) {
                _ = try sema.resolveConstMaybeUndefVal(arg_block, arg_src, uncasted_arg, "parameter is comptime");
            }
            const casted_arg = sema.coerceExtra(arg_block, param_ty, uncasted_arg, arg_src, .{ .param_src = .{
                .func_inst = func_inst,
                .param_i = @intCast(u32, arg_i.*),
            } }) catch |err| switch (err) {
                error.NotCoercible => unreachable,
                else => |e| return e,
            };

            if (is_comptime_call) {
                sema.inst_map.putAssumeCapacityNoClobber(inst, casted_arg);
                const arg_val = sema.resolveConstMaybeUndefVal(arg_block, arg_src, casted_arg, "argument to function being called at comptime must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and param_block.comptime_reason != null) try param_block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
                switch (arg_val.tag()) {
                    .generic_poison, .generic_poison_type => {
                        // This function is currently evaluated as part of an as-of-yet unresolvable
                        // parameter or return type.
                        return error.GenericPoison;
                    },
                    else => {
                        // Needed so that lazy values do not trigger
                        // assertion due to type not being resolved
                        // when the hash function is called.
                        try sema.resolveLazyValue(arg_val);
                    },
                }
                should_memoize.* = should_memoize.* and !arg_val.canMutateComptimeVarState();
                memoized_call_key.args[arg_i.*] = .{
                    .ty = param_ty,
                    .val = arg_val,
                };
            } else {
                sema.inst_map.putAssumeCapacityNoClobber(inst, casted_arg);
            }

            if (try sema.resolveMaybeUndefVal(casted_arg)) |_| {
                has_comptime_args.* = true;
            }

            arg_i.* += 1;
        },
        .param_anytype, .param_anytype_comptime => {
            // No coercion needed.
            const uncasted_arg = uncasted_args[arg_i.*];
            new_fn_info.param_types[arg_i.*] = sema.typeOf(uncasted_arg);

            if (is_comptime_call) {
                sema.inst_map.putAssumeCapacityNoClobber(inst, uncasted_arg);
                const arg_val = sema.resolveConstMaybeUndefVal(arg_block, arg_src, uncasted_arg, "argument to function being called at comptime must be comptime-known") catch |err| {
                    if (err == error.AnalysisFail and param_block.comptime_reason != null) try param_block.comptime_reason.?.explain(sema, sema.err);
                    return err;
                };
                switch (arg_val.tag()) {
                    .generic_poison, .generic_poison_type => {
                        // This function is currently evaluated as part of an as-of-yet unresolvable
                        // parameter or return type.
                        return error.GenericPoison;
                    },
                    else => {
                        // Needed so that lazy values do not trigger
                        // assertion due to type not being resolved
                        // when the hash function is called.
                        try sema.resolveLazyValue(arg_val);
                    },
                }
                should_memoize.* = should_memoize.* and !arg_val.canMutateComptimeVarState();
                memoized_call_key.args[arg_i.*] = .{
                    .ty = sema.typeOf(uncasted_arg),
                    .val = arg_val,
                };
            } else {
                if (zir_tags[inst] == .param_anytype_comptime) {
                    _ = try sema.resolveConstMaybeUndefVal(arg_block, arg_src, uncasted_arg, "parameter is comptime");
                }
                sema.inst_map.putAssumeCapacityNoClobber(inst, uncasted_arg);
            }

            if (try sema.resolveMaybeUndefVal(uncasted_arg)) |_| {
                has_comptime_args.* = true;
            }

            arg_i.* += 1;
        },
        else => {},
    }
}

fn analyzeCallArg(
    sema: *Sema,
    block: *Block,
    arg_src: LazySrcLoc,
    param_ty: Type,
    uncasted_arg: Air.Inst.Ref,
    opts: CoerceOpts,
) !Air.Inst.Ref {
    try sema.resolveTypeFully(param_ty);
    return sema.coerceExtra(block, param_ty, uncasted_arg, arg_src, opts) catch |err| switch (err) {
        error.NotCoercible => unreachable,
        else => |e| return e,
    };
}

fn analyzeGenericCallArg(
    sema: *Sema,
    block: *Block,
    arg_src: LazySrcLoc,
    uncasted_arg: Air.Inst.Ref,
    comptime_arg: TypedValue,
    runtime_args: []Air.Inst.Ref,
    new_fn_info: Type.Payload.Function.Data,
    runtime_i: *u32,
) !void {
    const is_runtime = comptime_arg.val.tag() == .generic_poison and
        comptime_arg.ty.hasRuntimeBits() and
        !(try sema.typeRequiresComptime(comptime_arg.ty));
    if (is_runtime) {
        const param_ty = new_fn_info.param_types[runtime_i.*];
        const casted_arg = try sema.coerce(block, param_ty, uncasted_arg, arg_src);
        try sema.queueFullTypeResolution(param_ty);
        runtime_args[runtime_i.*] = casted_arg;
        runtime_i.* += 1;
    } else if (try sema.typeHasOnePossibleValue(comptime_arg.ty)) |_| {
        _ = try sema.coerce(block, comptime_arg.ty, uncasted_arg, arg_src);
    }
}

fn analyzeGenericCallArgVal(sema: *Sema, block: *Block, arg_src: LazySrcLoc, uncasted_arg: Air.Inst.Ref) !Value {
    const arg_val = try sema.resolveValue(block, arg_src, uncasted_arg, "parameter is comptime");
    try sema.resolveLazyValue(arg_val);
    return arg_val;
}

fn instantiateGenericCall(
    sema: *Sema,
    block: *Block,
    func: Air.Inst.Ref,
    func_src: LazySrcLoc,
    call_src: LazySrcLoc,
    func_ty_info: Type.Payload.Function.Data,
    ensure_result_used: bool,
    uncasted_args: []const Air.Inst.Ref,
    call_tag: Air.Inst.Tag,
    bound_arg_src: ?LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const mod = sema.mod;
    const gpa = sema.gpa;

    const func_val = try sema.resolveConstValue(block, func_src, func, "generic function being called must be comptime-known");
    const module_fn = switch (func_val.tag()) {
        .function => func_val.castTag(.function).?.data,
        .decl_ref => mod.declPtr(func_val.castTag(.decl_ref).?.data).val.castTag(.function).?.data,
        else => unreachable,
    };
    // Check the Module's generic function map with an adapted context, so that we
    // can match against `uncasted_args` rather than doing the work below to create a
    // generic Scope only to junk it if it matches an existing instantiation.
    const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
    const namespace = fn_owner_decl.src_namespace;
    const fn_zir = namespace.file_scope.zir;
    const fn_info = fn_zir.getFnInfo(module_fn.zir_body_inst);
    const zir_tags = fn_zir.instructions.items(.tag);

    // This hash must match `Module.MonomorphedFuncsContext.hash`.
    // For parameters explicitly marked comptime and simple parameter type expressions,
    // we know whether a parameter is elided from a monomorphed function, and can
    // use it in the hash here. However, for parameter type expressions that are not
    // explicitly marked comptime and rely on previous parameter comptime values, we
    // don't find out until after generating a monomorphed function whether the parameter
    // type ended up being a "must-be-comptime-known" type.
    var hasher = std.hash.Wyhash.init(0);
    std.hash.autoHash(&hasher, module_fn.owner_decl);

    const generic_args = try sema.arena.alloc(GenericCallAdapter.Arg, func_ty_info.param_types.len);
    {
        var i: usize = 0;
        for (fn_info.param_body) |inst| {
            var is_comptime = false;
            var is_anytype = false;
            switch (zir_tags[inst]) {
                .param => {
                    is_comptime = func_ty_info.paramIsComptime(i);
                },
                .param_comptime => {
                    is_comptime = true;
                },
                .param_anytype => {
                    is_anytype = true;
                    is_comptime = func_ty_info.paramIsComptime(i);
                },
                .param_anytype_comptime => {
                    is_anytype = true;
                    is_comptime = true;
                },
                else => continue,
            }

            const arg_ty = sema.typeOf(uncasted_args[i]);
            if (is_comptime or is_anytype) {
                // Tuple default values are a part of the type and need to be
                // resolved to hash the type.
                try sema.resolveTupleLazyValues(block, call_src, arg_ty);
            }

            if (is_comptime) {
                const arg_val = sema.analyzeGenericCallArgVal(block, .unneeded, uncasted_args[i]) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const decl = sema.mod.declPtr(block.src_decl);
                        const arg_src = Module.argSrc(call_src.node_offset.x, sema.gpa, decl, i, bound_arg_src);
                        _ = try sema.analyzeGenericCallArgVal(block, arg_src, uncasted_args[i]);
                        unreachable;
                    },
                    else => |e| return e,
                };
                arg_val.hashUncoerced(arg_ty, &hasher, mod);
                if (is_anytype) {
                    arg_ty.hashWithHasher(&hasher, mod);
                    generic_args[i] = .{
                        .ty = arg_ty,
                        .val = arg_val,
                        .is_anytype = true,
                    };
                } else {
                    generic_args[i] = .{
                        .ty = arg_ty,
                        .val = arg_val,
                        .is_anytype = false,
                    };
                }
            } else if (is_anytype) {
                arg_ty.hashWithHasher(&hasher, mod);
                generic_args[i] = .{
                    .ty = arg_ty,
                    .val = Value.initTag(.generic_poison),
                    .is_anytype = true,
                };
            } else {
                generic_args[i] = .{
                    .ty = arg_ty,
                    .val = Value.initTag(.generic_poison),
                    .is_anytype = false,
                };
            }

            i += 1;
        }
    }

    const precomputed_hash = hasher.final();

    const adapter: GenericCallAdapter = .{
        .generic_fn = module_fn,
        .precomputed_hash = precomputed_hash,
        .func_ty_info = func_ty_info,
        .args = generic_args,
        .module = mod,
    };
    const gop = try mod.monomorphed_funcs.getOrPutAdapted(gpa, {}, adapter);
    const callee = if (!gop.found_existing) callee: {
        const new_module_func = try gpa.create(Module.Fn);

        // This ensures that we can operate on the hash map before the Module.Fn
        // struct is fully initialized.
        new_module_func.hash = precomputed_hash;
        new_module_func.generic_owner_decl = module_fn.owner_decl.toOptional();
        new_module_func.comptime_args = null;
        gop.key_ptr.* = new_module_func;

        try namespace.anon_decls.ensureUnusedCapacity(gpa, 1);

        // Create a Decl for the new function.
        const src_decl_index = namespace.getDeclIndex();
        const src_decl = mod.declPtr(src_decl_index);
        const new_decl_index = try mod.allocateNewDecl(namespace, fn_owner_decl.src_node, src_decl.src_scope);
        const new_decl = mod.declPtr(new_decl_index);
        // TODO better names for generic function instantiations
        const decl_name = try std.fmt.allocPrintZ(gpa, "{s}__anon_{d}", .{
            fn_owner_decl.name, @enumToInt(new_decl_index),
        });
        new_decl.name = decl_name;
        new_decl.src_line = fn_owner_decl.src_line;
        new_decl.is_pub = fn_owner_decl.is_pub;
        new_decl.is_exported = fn_owner_decl.is_exported;
        new_decl.has_align = fn_owner_decl.has_align;
        new_decl.has_linksection_or_addrspace = fn_owner_decl.has_linksection_or_addrspace;
        new_decl.@"linksection" = fn_owner_decl.@"linksection";
        new_decl.@"addrspace" = fn_owner_decl.@"addrspace";
        new_decl.zir_decl_index = fn_owner_decl.zir_decl_index;
        new_decl.alive = true; // This Decl is called at runtime.
        new_decl.analysis = .in_progress;
        new_decl.generation = mod.generation;

        namespace.anon_decls.putAssumeCapacityNoClobber(new_decl_index, {});

        // The generic function Decl is guaranteed to be the first dependency
        // of each of its instantiations.
        assert(new_decl.dependencies.keys().len == 0);
        try mod.declareDeclDependency(new_decl_index, module_fn.owner_decl);

        var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
        const new_decl_arena_allocator = new_decl_arena.allocator();

        const new_func = sema.resolveGenericInstantiationType(
            block,
            new_decl_arena_allocator,
            fn_zir,
            new_decl,
            new_decl_index,
            uncasted_args,
            module_fn,
            new_module_func,
            namespace,
            func_ty_info,
            call_src,
            bound_arg_src,
        ) catch |err| switch (err) {
            error.GenericPoison, error.ComptimeReturn => {
                new_decl_arena.deinit();
                // Resolving the new function type below will possibly declare more decl dependencies
                // and so we remove them all here in case of error.
                for (new_decl.dependencies.keys()) |dep_index| {
                    const dep = mod.declPtr(dep_index);
                    dep.removeDependant(new_decl_index);
                }
                assert(namespace.anon_decls.orderedRemove(new_decl_index));
                mod.destroyDecl(new_decl_index);
                assert(mod.monomorphed_funcs.remove(new_module_func));
                gpa.destroy(new_module_func);
                return err;
            },
            else => {
                assert(mod.monomorphed_funcs.remove(new_module_func));
                {
                    errdefer new_decl_arena.deinit();
                    try new_decl.finalizeNewArena(&new_decl_arena);
                }
                // TODO look up the compile error that happened here and attach a note to it
                // pointing here, at the generic instantiation callsite.
                if (sema.owner_func) |owner_func| {
                    owner_func.state = .dependency_failure;
                } else {
                    sema.owner_decl.analysis = .dependency_failure;
                }
                return err;
            },
        };
        errdefer new_decl_arena.deinit();

        try new_decl.finalizeNewArena(&new_decl_arena);
        break :callee new_func;
    } else gop.key_ptr.*;

    callee.branch_quota = @max(callee.branch_quota, sema.branch_quota);

    const callee_inst = try sema.analyzeDeclVal(block, func_src, callee.owner_decl);

    // Make a runtime call to the new function, making sure to omit the comptime args.
    const comptime_args = callee.comptime_args.?;
    const func_ty = mod.declPtr(callee.owner_decl).ty;
    const new_fn_info = func_ty.fnInfo();
    const runtime_args_len = @intCast(u32, new_fn_info.param_types.len);
    const runtime_args = try sema.arena.alloc(Air.Inst.Ref, runtime_args_len);
    {
        var runtime_i: u32 = 0;
        var total_i: u32 = 0;
        for (fn_info.param_body) |inst| {
            switch (zir_tags[inst]) {
                .param_comptime, .param_anytype_comptime, .param, .param_anytype => {},
                else => continue,
            }
            sema.analyzeGenericCallArg(
                block,
                .unneeded,
                uncasted_args[total_i],
                comptime_args[total_i],
                runtime_args,
                new_fn_info,
                &runtime_i,
            ) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const decl = sema.mod.declPtr(block.src_decl);
                    _ = try sema.analyzeGenericCallArg(
                        block,
                        Module.argSrc(call_src.node_offset.x, sema.gpa, decl, total_i, bound_arg_src),
                        uncasted_args[total_i],
                        comptime_args[total_i],
                        runtime_args,
                        new_fn_info,
                        &runtime_i,
                    );
                    unreachable;
                },
                else => |e| return e,
            };
            total_i += 1;
        }

        try sema.queueFullTypeResolution(new_fn_info.return_type);
    }

    if (sema.owner_func != null and new_fn_info.return_type.isError()) {
        sema.owner_func.?.calls_or_awaits_errorable_fn = true;
    }

    try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.Call).Struct.fields.len +
        runtime_args_len);
    const result = try block.addInst(.{
        .tag = call_tag,
        .data = .{ .pl_op = .{
            .operand = callee_inst,
            .payload = sema.addExtraAssumeCapacity(Air.Call{
                .args_len = runtime_args_len,
            }),
        } },
    });
    sema.appendRefsAssumeCapacity(runtime_args);

    if (ensure_result_used) {
        try sema.ensureResultUsed(block, sema.typeOf(result), call_src);
    }
    if (call_tag == .call_always_tail) {
        return sema.handleTailCall(block, call_src, func_ty, result);
    }
    return result;
}

fn resolveGenericInstantiationType(
    sema: *Sema,
    block: *Block,
    new_decl_arena_allocator: Allocator,
    fn_zir: Zir,
    new_decl: *Decl,
    new_decl_index: Decl.Index,
    uncasted_args: []const Air.Inst.Ref,
    module_fn: *Module.Fn,
    new_module_func: *Module.Fn,
    namespace: *Namespace,
    func_ty_info: Type.Payload.Function.Data,
    call_src: LazySrcLoc,
    bound_arg_src: ?LazySrcLoc,
) !*Module.Fn {
    const mod = sema.mod;
    const gpa = sema.gpa;

    const zir_tags = fn_zir.instructions.items(.tag);
    const fn_info = fn_zir.getFnInfo(module_fn.zir_body_inst);

    // Re-run the block that creates the function, with the comptime parameters
    // pre-populated inside `inst_map`. This causes `param_comptime` and
    // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
    // new, monomorphized function, with the comptime parameters elided.
    var child_sema: Sema = .{
        .mod = mod,
        .gpa = gpa,
        .arena = sema.arena,
        .perm_arena = new_decl_arena_allocator,
        .code = fn_zir,
        .owner_decl = new_decl,
        .owner_decl_index = new_decl_index,
        .func = null,
        .fn_ret_ty = Type.void,
        .owner_func = null,
        .comptime_args = try new_decl_arena_allocator.alloc(TypedValue, uncasted_args.len),
        .comptime_args_fn_inst = module_fn.zir_body_inst,
        .preallocated_new_func = new_module_func,
        .is_generic_instantiation = true,
        .branch_quota = sema.branch_quota,
        .branch_count = sema.branch_count,
    };
    defer child_sema.deinit();

    var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, new_decl.src_scope);
    defer wip_captures.deinit();

    var child_block: Block = .{
        .parent = null,
        .sema = &child_sema,
        .src_decl = new_decl_index,
        .namespace = namespace,
        .wip_capture_scope = wip_captures.scope,
        .instructions = .{},
        .inlining = null,
        .is_comptime = true,
    };
    defer {
        child_block.instructions.deinit(gpa);
        child_block.params.deinit(gpa);
    }

    try child_sema.inst_map.ensureSpaceForInstructions(gpa, fn_info.param_body);

    var arg_i: usize = 0;
    for (fn_info.param_body) |inst| {
        var is_comptime = false;
        var is_anytype = false;
        switch (zir_tags[inst]) {
            .param => {
                is_comptime = func_ty_info.paramIsComptime(arg_i);
            },
            .param_comptime => {
                is_comptime = true;
            },
            .param_anytype => {
                is_anytype = true;
                is_comptime = func_ty_info.paramIsComptime(arg_i);
            },
            .param_anytype_comptime => {
                is_anytype = true;
                is_comptime = true;
            },
            else => continue,
        }
        const arg = uncasted_args[arg_i];
        if (is_comptime) {
            const arg_val = (try sema.resolveMaybeUndefVal(arg)).?;
            const child_arg = try child_sema.addConstant(sema.typeOf(arg), arg_val);
            child_sema.inst_map.putAssumeCapacityNoClobber(inst, child_arg);
        } else if (is_anytype) {
            const arg_ty = sema.typeOf(arg);
            if (try sema.typeRequiresComptime(arg_ty)) {
                const arg_val = sema.resolveConstValue(block, .unneeded, arg, "") catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const decl = sema.mod.declPtr(block.src_decl);
                        const arg_src = Module.argSrc(call_src.node_offset.x, sema.gpa, decl, arg_i, bound_arg_src);
                        _ = try sema.resolveConstValue(block, arg_src, arg, "argument to parameter with comptime-only type must be comptime-known");
                        unreachable;
                    },
                    else => |e| return e,
                };
                const child_arg = try child_sema.addConstant(arg_ty, arg_val);
                child_sema.inst_map.putAssumeCapacityNoClobber(inst, child_arg);
            } else {
                // We insert into the map an instruction which is runtime-known
                // but has the type of the argument.
                const child_arg = try child_block.addInst(.{
                    .tag = .arg,
                    .data = .{ .arg = .{
                        .ty = try child_sema.addType(arg_ty),
                        .src_index = @intCast(u32, arg_i),
                    } },
                });
                child_sema.inst_map.putAssumeCapacityNoClobber(inst, child_arg);
            }
        }
        arg_i += 1;
    }

    // Save the error trace as our first action in the function.
    // If this is unnecessary after all, Liveness will clean it up for us.
    const error_return_trace_index = try sema.analyzeSaveErrRetIndex(&child_block);
    child_sema.error_return_trace_index_on_fn_entry = error_return_trace_index;
    child_block.error_return_trace_index = error_return_trace_index;

    const new_func_inst = try child_sema.resolveBody(&child_block, fn_info.param_body, fn_info.param_body_inst);
    const new_func_val = child_sema.resolveConstValue(&child_block, .unneeded, new_func_inst, undefined) catch unreachable;
    const new_func = new_func_val.castTag(.function).?.data;
    errdefer new_func.deinit(gpa);
    assert(new_func == new_module_func);

    arg_i = 0;
    for (fn_info.param_body) |inst| {
        var is_comptime = false;
        switch (zir_tags[inst]) {
            .param => {
                is_comptime = func_ty_info.paramIsComptime(arg_i);
            },
            .param_comptime => {
                is_comptime = true;
            },
            .param_anytype => {
                is_comptime = func_ty_info.paramIsComptime(arg_i);
            },
            .param_anytype_comptime => {
                is_comptime = true;
            },
            else => continue,
        }

        // We populate the Type here regardless because it is needed by
        // `GenericCallAdapter.eql` as well as function body analysis.
        // Whether it is anytype is communicated by `isAnytypeParam`.
        const arg = child_sema.inst_map.get(inst).?;
        const copied_arg_ty = try child_sema.typeOf(arg).copy(new_decl_arena_allocator);

        if (try sema.typeRequiresComptime(copied_arg_ty)) {
            is_comptime = true;
        }

        if (is_comptime) {
            const arg_val = (child_sema.resolveMaybeUndefValAllowVariables(arg) catch unreachable).?;
            child_sema.comptime_args[arg_i] = .{
                .ty = copied_arg_ty,
                .val = try arg_val.copy(new_decl_arena_allocator),
            };
        } else {
            child_sema.comptime_args[arg_i] = .{
                .ty = copied_arg_ty,
                .val = Value.initTag(.generic_poison),
            };
        }

        arg_i += 1;
    }

    try wip_captures.finalize();

    // Populate the Decl ty/val with the function and its type.
    new_decl.ty = try child_sema.typeOf(new_func_inst).copy(new_decl_arena_allocator);
    // If the call evaluated to a return type that requires comptime, never mind
    // our generic instantiation. Instead we need to perform a comptime call.
    const new_fn_info = new_decl.ty.fnInfo();
    if (try sema.typeRequiresComptime(new_fn_info.return_type)) {
        return error.ComptimeReturn;
    }
    // Similarly, if the call evaluated to a generic type we need to instead
    // call it inline.
    if (new_fn_info.is_generic or new_fn_info.cc == .Inline) {
        return error.GenericPoison;
    }

    new_decl.val = try Value.Tag.function.create(new_decl_arena_allocator, new_func);
    new_decl.@"align" = 0;
    new_decl.has_tv = true;
    new_decl.owns_tv = true;
    new_decl.analysis = .complete;

    log.debug("generic function '{s}' instantiated with type {}", .{
        new_decl.name, new_decl.ty.fmtDebug(),
    });

    // Queue up a `codegen_func` work item for the new Fn. The `comptime_args` field
    // will be populated, ensuring it will have `analyzeBody` called with the ZIR
    // parameters mapped appropriately.
    try mod.comp.work_queue.writeItem(.{ .codegen_func = new_func });
    return new_func;
}

fn resolveTupleLazyValues(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
    if (!ty.isSimpleTupleOrAnonStruct()) return;
    const tuple = ty.tupleFields();
    for (tuple.values, 0..) |field_val, i| {
        try sema.resolveTupleLazyValues(block, src, tuple.types[i]);
        if (field_val.tag() == .unreachable_value) continue;
        try sema.resolveLazyValue(field_val);
    }
}

fn emitDbgInline(
    sema: *Sema,
    block: *Block,
    old_func: *Module.Fn,
    new_func: *Module.Fn,
    new_func_ty: Type,
    tag: Air.Inst.Tag,
) CompileError!void {
    if (sema.mod.comp.bin_file.options.strip) return;

    // Recursive inline call; no dbg_inline needed.
    if (old_func == new_func) return;

    try sema.air_values.append(sema.gpa, try Value.Tag.function.create(sema.arena, new_func));
    _ = try block.addInst(.{
        .tag = tag,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(new_func_ty),
            .payload = @intCast(u32, sema.air_values.items.len - 1),
        } },
    });
}

fn zirIntType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const tracy = trace(@src());
    defer tracy.end();

    const int_type = sema.code.instructions.items(.data)[inst].int_type;
    const ty = try Module.makeIntType(sema.arena, int_type.signedness, int_type.bit_count);

    return sema.addType(ty);
}

fn zirOptionalType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_un_op = inst_data.src_node };
    const child_type = try sema.resolveType(block, operand_src, inst_data.operand);
    if (child_type.zigTypeTag() == .Opaque) {
        return sema.fail(block, operand_src, "opaque type '{}' cannot be optional", .{child_type.fmt(sema.mod)});
    } else if (child_type.zigTypeTag() == .Null) {
        return sema.fail(block, operand_src, "type '{}' cannot be optional", .{child_type.fmt(sema.mod)});
    }
    const opt_type = try Type.optional(sema.arena, child_type);

    return sema.addType(opt_type);
}

fn zirElemTypeIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const bin = sema.code.instructions.items(.data)[inst].bin;
    const indexable_ty = try sema.resolveType(block, .unneeded, bin.lhs);
    assert(indexable_ty.isIndexable()); // validated by a previous instruction
    if (indexable_ty.zigTypeTag() == .Struct) {
        const elem_type = indexable_ty.structFieldType(@enumToInt(bin.rhs));
        return sema.addType(elem_type);
    } else {
        const elem_type = indexable_ty.elemType2();
        return sema.addType(elem_type);
    }
}

fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const elem_type_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const len_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const len = try sema.resolveInt(block, len_src, extra.lhs, Type.u32, "vector length must be comptime-known");
    const elem_type = try sema.resolveType(block, elem_type_src, extra.rhs);
    try sema.checkVectorElemType(block, elem_type_src, elem_type);
    const vector_type = try Type.Tag.vector.create(sema.arena, .{
        .len = @intCast(u32, len),
        .elem_type = elem_type,
    });
    return sema.addType(vector_type);
}

fn zirArrayType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const len_src: LazySrcLoc = .{ .node_offset_array_type_len = inst_data.src_node };
    const elem_src: LazySrcLoc = .{ .node_offset_array_type_elem = inst_data.src_node };
    const len = try sema.resolveInt(block, len_src, extra.lhs, Type.usize, "array length must be comptime-known");
    const elem_type = try sema.resolveType(block, elem_src, extra.rhs);
    const array_ty = try Type.array(sema.arena, len, null, elem_type, sema.mod);

    return sema.addType(array_ty);
}

fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.ArrayTypeSentinel, inst_data.payload_index).data;
    const len_src: LazySrcLoc = .{ .node_offset_array_type_len = inst_data.src_node };
    const sentinel_src: LazySrcLoc = .{ .node_offset_array_type_sentinel = inst_data.src_node };
    const elem_src: LazySrcLoc = .{ .node_offset_array_type_elem = inst_data.src_node };
    const len = try sema.resolveInt(block, len_src, extra.len, Type.usize, "array length must be comptime-known");
    const elem_type = try sema.resolveType(block, elem_src, extra.elem_type);
    const uncasted_sentinel = try sema.resolveInst(extra.sentinel);
    const sentinel = try sema.coerce(block, elem_type, uncasted_sentinel, sentinel_src);
    const sentinel_val = try sema.resolveConstValue(block, sentinel_src, sentinel, "array sentinel value must be comptime-known");
    const array_ty = try Type.array(sema.arena, len, sentinel_val, elem_type, sema.mod);

    return sema.addType(array_ty);
}

fn zirAnyframeType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    if (true) {
        return sema.failWithUseOfAsync(block, inst_data.src());
    }
    const operand_src: LazySrcLoc = .{ .node_offset_anyframe_type = inst_data.src_node };
    const return_type = try sema.resolveType(block, operand_src, inst_data.operand);
    const anyframe_type = try Type.Tag.anyframe_T.create(sema.arena, return_type);

    return sema.addType(anyframe_type);
}

fn zirErrorUnionType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const error_set = try sema.resolveType(block, lhs_src, extra.lhs);
    const payload = try sema.resolveType(block, rhs_src, extra.rhs);

    if (error_set.zigTypeTag() != .ErrorSet) {
        return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{
            error_set.fmt(sema.mod),
        });
    }
    try sema.validateErrorUnionPayloadType(block, payload, rhs_src);
    const err_union_ty = try Type.errorUnion(sema.arena, error_set, payload, sema.mod);
    return sema.addType(err_union_ty);
}

fn validateErrorUnionPayloadType(sema: *Sema, block: *Block, payload_ty: Type, payload_src: LazySrcLoc) !void {
    if (payload_ty.zigTypeTag() == .Opaque) {
        return sema.fail(block, payload_src, "error union with payload of opaque type '{}' not allowed", .{
            payload_ty.fmt(sema.mod),
        });
    } else if (payload_ty.zigTypeTag() == .ErrorSet) {
        return sema.fail(block, payload_src, "error union with payload of error set type '{}' not allowed", .{
            payload_ty.fmt(sema.mod),
        });
    }
}

fn zirErrorValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;

    // Create an anonymous error set type with only this error value, and return the value.
    const kv = try sema.mod.getErrorValue(inst_data.get(sema.code));
    const result_type = try Type.Tag.error_set_single.create(sema.arena, kv.key);
    return sema.addConstant(
        result_type,
        try Value.Tag.@"error".create(sema.arena, .{
            .name = kv.key,
        }),
    );
}

fn zirErrorToInt(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const uncasted_operand = try sema.resolveInst(extra.operand);
    const operand = try sema.coerce(block, Type.anyerror, uncasted_operand, operand_src);

    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        if (val.isUndef()) {
            return sema.addConstUndef(Type.err_int);
        }
        switch (val.tag()) {
            .@"error" => {
                const payload = try sema.arena.create(Value.Payload.U64);
                payload.* = .{
                    .base = .{ .tag = .int_u64 },
                    .data = (try sema.mod.getErrorValue(val.castTag(.@"error").?.data.name)).value,
                };
                return sema.addConstant(Type.err_int, Value.initPayload(&payload.base));
            },

            // This is not a valid combination with the type `anyerror`.
            .the_only_possible_value => unreachable,

            // Assume it's already encoded as an integer.
            else => return sema.addConstant(Type.err_int, val),
        }
    }

    const op_ty = sema.typeOf(uncasted_operand);
    try sema.resolveInferredErrorSetTy(block, src, op_ty);
    if (!op_ty.isAnyError()) {
        const names = op_ty.errorSetNames();
        switch (names.len) {
            0 => return sema.addConstant(Type.err_int, Value.zero),
            1 => return sema.addIntUnsigned(Type.err_int, sema.mod.global_error_set.get(names[0]).?),
            else => {},
        }
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    return block.addBitCast(Type.err_int, operand);
}

fn zirIntToError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const uncasted_operand = try sema.resolveInst(extra.operand);
    const operand = try sema.coerce(block, Type.err_int, uncasted_operand, operand_src);
    const target = sema.mod.getTarget();

    if (try sema.resolveDefinedValue(block, operand_src, operand)) |value| {
        const int = try sema.usizeCast(block, operand_src, value.toUnsignedInt(target));
        if (int > sema.mod.global_error_set.count() or int == 0)
            return sema.fail(block, operand_src, "integer value '{d}' represents no error", .{int});
        const payload = try sema.arena.create(Value.Payload.Error);
        payload.* = .{
            .base = .{ .tag = .@"error" },
            .data = .{ .name = sema.mod.error_name_list.items[int] },
        };
        return sema.addConstant(Type.anyerror, Value.initPayload(&payload.base));
    }
    try sema.requireRuntimeBlock(block, src, operand_src);
    if (block.wantSafety()) {
        const is_lt_len = try block.addUnOp(.cmp_lt_errors_len, operand);
        const zero_val = try sema.addConstant(Type.err_int, Value.zero);
        const is_non_zero = try block.addBinOp(.cmp_neq, operand, zero_val);
        const ok = try block.addBinOp(.bit_and, is_lt_len, is_non_zero);
        try sema.addSafetyCheck(block, ok, .invalid_error_code);
    }
    return block.addInst(.{
        .tag = .bitcast,
        .data = .{ .ty_op = .{
            .ty = Air.Inst.Ref.anyerror_type,
            .operand = operand,
        } },
    });
}

fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    if (sema.typeOf(lhs).zigTypeTag() == .Bool and sema.typeOf(rhs).zigTypeTag() == .Bool) {
        const msg = msg: {
            const msg = try sema.errMsg(block, lhs_src, "expected error set type, found 'bool'", .{});
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, src, msg, "'||' merges error sets; 'or' performs boolean OR", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    const lhs_ty = try sema.analyzeAsType(block, lhs_src, lhs);
    const rhs_ty = try sema.analyzeAsType(block, rhs_src, rhs);
    if (lhs_ty.zigTypeTag() != .ErrorSet)
        return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{lhs_ty.fmt(sema.mod)});
    if (rhs_ty.zigTypeTag() != .ErrorSet)
        return sema.fail(block, rhs_src, "expected error set type, found '{}'", .{rhs_ty.fmt(sema.mod)});

    // Anything merged with anyerror is anyerror.
    if (lhs_ty.tag() == .anyerror or rhs_ty.tag() == .anyerror) {
        return Air.Inst.Ref.anyerror_type;
    }

    if (lhs_ty.castTag(.error_set_inferred)) |payload| {
        try sema.resolveInferredErrorSet(block, src, payload.data);
        // isAnyError might have changed from a false negative to a true positive after resolution.
        if (lhs_ty.isAnyError()) {
            return Air.Inst.Ref.anyerror_type;
        }
    }
    if (rhs_ty.castTag(.error_set_inferred)) |payload| {
        try sema.resolveInferredErrorSet(block, src, payload.data);
        // isAnyError might have changed from a false negative to a true positive after resolution.
        if (rhs_ty.isAnyError()) {
            return Air.Inst.Ref.anyerror_type;
        }
    }

    const err_set_ty = try lhs_ty.errorSetMerge(sema.arena, rhs_ty);
    return sema.addType(err_set_ty);
}

fn zirEnumLiteral(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const duped_name = try sema.arena.dupe(u8, inst_data.get(sema.code));
    return sema.addConstant(
        Type.initTag(.enum_literal),
        try Value.Tag.enum_literal.create(sema.arena, duped_name),
    );
}

fn zirEnumToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const arena = sema.arena;
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);

    const enum_tag: Air.Inst.Ref = switch (operand_ty.zigTypeTag()) {
        .Enum => operand,
        .Union => blk: {
            const union_ty = try sema.resolveTypeFields(operand_ty);
            const tag_ty = union_ty.unionTagType() orelse {
                return sema.fail(
                    block,
                    operand_src,
                    "untagged union '{}' cannot be converted to integer",
                    .{src},
                );
            };
            break :blk try sema.unionToTag(block, tag_ty, operand, operand_src);
        },
        else => {
            return sema.fail(block, operand_src, "expected enum or tagged union, found '{}'", .{
                operand_ty.fmt(sema.mod),
            });
        },
    };
    const enum_tag_ty = sema.typeOf(enum_tag);

    var int_tag_type_buffer: Type.Payload.Bits = undefined;
    const int_tag_ty = try enum_tag_ty.intTagType(&int_tag_type_buffer).copy(arena);

    if (try sema.typeHasOnePossibleValue(enum_tag_ty)) |opv| {
        return sema.addConstant(int_tag_ty, opv);
    }

    if (try sema.resolveMaybeUndefVal(enum_tag)) |enum_tag_val| {
        var buffer: Value.Payload.U64 = undefined;
        const val = enum_tag_val.enumToInt(enum_tag_ty, &buffer);
        return sema.addConstant(int_tag_ty, try val.copy(sema.arena));
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    return block.addBitCast(int_tag_ty, enum_tag);
}

fn zirIntToEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const src = inst_data.src();
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);

    if (dest_ty.zigTypeTag() != .Enum) {
        return sema.fail(block, dest_ty_src, "expected enum, found '{}'", .{dest_ty.fmt(sema.mod)});
    }
    _ = try sema.checkIntType(block, operand_src, sema.typeOf(operand));

    if (try sema.resolveMaybeUndefVal(operand)) |int_val| {
        if (dest_ty.isNonexhaustiveEnum()) {
            var buffer: Type.Payload.Bits = undefined;
            const int_tag_ty = dest_ty.intTagType(&buffer);
            if (try sema.intFitsInType(int_val, int_tag_ty, null)) {
                return sema.addConstant(dest_ty, int_val);
            }
            const msg = msg: {
                const msg = try sema.errMsg(
                    block,
                    src,
                    "int value '{}' out of range of non-exhaustive enum '{}'",
                    .{ int_val.fmtValue(sema.typeOf(operand), sema.mod), dest_ty.fmt(sema.mod) },
                );
                errdefer msg.destroy(sema.gpa);
                try sema.addDeclaredHereNote(msg, dest_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (int_val.isUndef()) {
            return sema.failWithUseOfUndef(block, operand_src);
        }
        if (!(try sema.enumHasInt(dest_ty, int_val))) {
            const msg = msg: {
                const msg = try sema.errMsg(
                    block,
                    src,
                    "enum '{}' has no tag with value '{}'",
                    .{ dest_ty.fmt(sema.mod), int_val.fmtValue(sema.typeOf(operand), sema.mod) },
                );
                errdefer msg.destroy(sema.gpa);
                try sema.addDeclaredHereNote(msg, dest_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        return sema.addConstant(dest_ty, int_val);
    }

    if (try sema.typeHasOnePossibleValue(dest_ty)) |opv| {
        const result = try sema.addConstant(dest_ty, opv);
        // The operand is runtime-known but the result is comptime-known. In
        // this case we still need a safety check.
        // TODO add a safety check here. we can't use is_named_enum_value -
        // it needs to convert the enum back to int and make sure it equals the operand int.
        return result;
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    const result = try block.addTyOp(.intcast, dest_ty, operand);
    if (block.wantSafety() and !dest_ty.isNonexhaustiveEnum() and
        sema.mod.backendSupportsFeature(.is_named_enum_value))
    {
        const ok = try block.addUnOp(.is_named_enum_value, result);
        try sema.addSafetyCheck(block, ok, .invalid_enum_value);
    }
    return result;
}

/// Pointer in, pointer out.
fn zirOptionalPayloadPtr(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    safety_check: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const optional_ptr = try sema.resolveInst(inst_data.operand);
    const src = inst_data.src();

    return sema.analyzeOptionalPayloadPtr(block, src, optional_ptr, safety_check, false);
}

fn analyzeOptionalPayloadPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    optional_ptr: Air.Inst.Ref,
    safety_check: bool,
    initializing: bool,
) CompileError!Air.Inst.Ref {
    const optional_ptr_ty = sema.typeOf(optional_ptr);
    assert(optional_ptr_ty.zigTypeTag() == .Pointer);

    const opt_type = optional_ptr_ty.elemType();
    if (opt_type.zigTypeTag() != .Optional) {
        return sema.fail(block, src, "expected optional type, found '{}'", .{opt_type.fmt(sema.mod)});
    }

    const child_type = try opt_type.optionalChildAlloc(sema.arena);
    const child_pointer = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = child_type,
        .mutable = !optional_ptr_ty.isConstPtr(),
        .@"addrspace" = optional_ptr_ty.ptrAddressSpace(),
    });

    if (try sema.resolveDefinedValue(block, src, optional_ptr)) |ptr_val| {
        if (initializing) {
            if (!ptr_val.isComptimeMutablePtr()) {
                // If the pointer resulting from this function was stored at comptime,
                // the optional non-null bit would be set that way. But in this case,
                // we need to emit a runtime instruction to do it.
                _ = try block.addTyOp(.optional_payload_ptr_set, child_pointer, optional_ptr);
            }
            return sema.addConstant(
                child_pointer,
                try Value.Tag.opt_payload_ptr.create(sema.arena, .{
                    .container_ptr = ptr_val,
                    .container_ty = optional_ptr_ty.childType(),
                }),
            );
        }
        if (try sema.pointerDeref(block, src, ptr_val, optional_ptr_ty)) |val| {
            if (val.isNull()) {
                return sema.fail(block, src, "unable to unwrap null", .{});
            }
            // The same Value represents the pointer to the optional and the payload.
            return sema.addConstant(
                child_pointer,
                try Value.Tag.opt_payload_ptr.create(sema.arena, .{
                    .container_ptr = ptr_val,
                    .container_ty = optional_ptr_ty.childType(),
                }),
            );
        }
    }

    try sema.requireRuntimeBlock(block, src, null);
    if (safety_check and block.wantSafety()) {
        const is_non_null = try block.addUnOp(.is_non_null_ptr, optional_ptr);
        try sema.addSafetyCheck(block, is_non_null, .unwrap_null);
    }
    const air_tag: Air.Inst.Tag = if (initializing)
        .optional_payload_ptr_set
    else
        .optional_payload_ptr;
    return block.addTyOp(air_tag, child_pointer, optional_ptr);
}

/// Value in, value out.
fn zirOptionalPayload(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    safety_check: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    const result_ty = switch (operand_ty.zigTypeTag()) {
        .Optional => try operand_ty.optionalChildAlloc(sema.arena),
        .Pointer => t: {
            if (operand_ty.ptrSize() != .C) {
                return sema.failWithExpectedOptionalType(block, src, operand_ty);
            }
            // TODO https://github.com/ziglang/zig/issues/6597
            if (true) break :t operand_ty;
            const ptr_info = operand_ty.ptrInfo().data;
            break :t try Type.ptr(sema.arena, sema.mod, .{
                .pointee_type = try ptr_info.pointee_type.copy(sema.arena),
                .@"align" = ptr_info.@"align",
                .@"addrspace" = ptr_info.@"addrspace",
                .mutable = ptr_info.mutable,
                .@"allowzero" = ptr_info.@"allowzero",
                .@"volatile" = ptr_info.@"volatile",
                .size = .One,
            });
        },
        else => return sema.failWithExpectedOptionalType(block, src, operand_ty),
    };

    if (try sema.resolveDefinedValue(block, src, operand)) |val| {
        if (val.isNull()) {
            return sema.fail(block, src, "unable to unwrap null", .{});
        }
        if (val.castTag(.opt_payload)) |payload| {
            return sema.addConstant(result_ty, payload.data);
        }
        return sema.addConstant(result_ty, val);
    }

    try sema.requireRuntimeBlock(block, src, null);
    if (safety_check and block.wantSafety()) {
        const is_non_null = try block.addUnOp(.is_non_null, operand);
        try sema.addSafetyCheck(block, is_non_null, .unwrap_null);
    }
    return block.addTyOp(.optional_payload, result_ty, operand);
}

/// Value in, value out
fn zirErrUnionPayload(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_src = src;
    const err_union_ty = sema.typeOf(operand);
    if (err_union_ty.zigTypeTag() != .ErrorUnion) {
        return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
            err_union_ty.fmt(sema.mod),
        });
    }
    return sema.analyzeErrUnionPayload(block, src, err_union_ty, operand, operand_src, false);
}

fn analyzeErrUnionPayload(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    err_union_ty: Type,
    operand: Zir.Inst.Ref,
    operand_src: LazySrcLoc,
    safety_check: bool,
) CompileError!Air.Inst.Ref {
    const payload_ty = err_union_ty.errorUnionPayload();
    if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
        if (val.getError()) |name| {
            return sema.fail(block, src, "caught unexpected error '{s}'", .{name});
        }
        const data = val.castTag(.eu_payload).?.data;
        return sema.addConstant(payload_ty, data);
    }

    try sema.requireRuntimeBlock(block, src, null);

    // If the error set has no fields then no safety check is needed.
    if (safety_check and block.wantSafety() and
        !err_union_ty.errorUnionSet().errorSetIsEmpty())
    {
        try sema.panicUnwrapError(block, operand, .unwrap_errunion_err, .is_non_err);
    }

    return block.addTyOp(.unwrap_errunion_payload, payload_ty, operand);
}

/// Pointer in, pointer out.
fn zirErrUnionPayloadPtr(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const src = inst_data.src();

    return sema.analyzeErrUnionPayloadPtr(block, src, operand, false, false);
}

fn analyzeErrUnionPayloadPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
    safety_check: bool,
    initializing: bool,
) CompileError!Air.Inst.Ref {
    const operand_ty = sema.typeOf(operand);
    assert(operand_ty.zigTypeTag() == .Pointer);

    if (operand_ty.elemType().zigTypeTag() != .ErrorUnion) {
        return sema.fail(block, src, "expected error union type, found '{}'", .{
            operand_ty.elemType().fmt(sema.mod),
        });
    }

    const err_union_ty = operand_ty.elemType();
    const payload_ty = err_union_ty.errorUnionPayload();
    const operand_pointer_ty = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = payload_ty,
        .mutable = !operand_ty.isConstPtr(),
        .@"addrspace" = operand_ty.ptrAddressSpace(),
    });

    if (try sema.resolveDefinedValue(block, src, operand)) |ptr_val| {
        if (initializing) {
            if (!ptr_val.isComptimeMutablePtr()) {
                // If the pointer resulting from this function was stored at comptime,
                // the error union error code would be set that way. But in this case,
                // we need to emit a runtime instruction to do it.
                try sema.requireRuntimeBlock(block, src, null);
                _ = try block.addTyOp(.errunion_payload_ptr_set, operand_pointer_ty, operand);
            }
            return sema.addConstant(
                operand_pointer_ty,
                try Value.Tag.eu_payload_ptr.create(sema.arena, .{
                    .container_ptr = ptr_val,
                    .container_ty = operand_ty.elemType(),
                }),
            );
        }
        if (try sema.pointerDeref(block, src, ptr_val, operand_ty)) |val| {
            if (val.getError()) |name| {
                return sema.fail(block, src, "caught unexpected error '{s}'", .{name});
            }

            return sema.addConstant(
                operand_pointer_ty,
                try Value.Tag.eu_payload_ptr.create(sema.arena, .{
                    .container_ptr = ptr_val,
                    .container_ty = operand_ty.elemType(),
                }),
            );
        }
    }

    try sema.requireRuntimeBlock(block, src, null);

    // If the error set has no fields then no safety check is needed.
    if (safety_check and block.wantSafety() and
        !err_union_ty.errorUnionSet().errorSetIsEmpty())
    {
        try sema.panicUnwrapError(block, operand, .unwrap_errunion_err_ptr, .is_non_err_ptr);
    }

    const air_tag: Air.Inst.Tag = if (initializing)
        .errunion_payload_ptr_set
    else
        .unwrap_errunion_payload_ptr;
    return block.addTyOp(air_tag, operand_pointer_ty, operand);
}

/// Value in, value out
fn zirErrUnionCode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    return sema.analyzeErrUnionCode(block, src, operand);
}

fn analyzeErrUnionCode(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref) CompileError!Air.Inst.Ref {
    const operand_ty = sema.typeOf(operand);
    if (operand_ty.zigTypeTag() != .ErrorUnion) {
        return sema.fail(block, src, "expected error union type, found '{}'", .{
            operand_ty.fmt(sema.mod),
        });
    }

    const result_ty = operand_ty.errorUnionSet();

    if (try sema.resolveDefinedValue(block, src, operand)) |val| {
        assert(val.getError() != null);
        return sema.addConstant(result_ty, val);
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.unwrap_errunion_err, result_ty, operand);
}

/// Pointer in, value out
fn zirErrUnionCodePtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    assert(operand_ty.zigTypeTag() == .Pointer);

    if (operand_ty.elemType().zigTypeTag() != .ErrorUnion) {
        return sema.fail(block, src, "expected error union type, found '{}'", .{
            operand_ty.elemType().fmt(sema.mod),
        });
    }

    const result_ty = operand_ty.elemType().errorUnionSet();

    if (try sema.resolveDefinedValue(block, src, operand)) |pointer_val| {
        if (try sema.pointerDeref(block, src, pointer_val, operand_ty)) |val| {
            assert(val.getError() != null);
            return sema.addConstant(result_ty, val);
        }
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.unwrap_errunion_err_ptr, result_ty, operand);
}

fn zirFunc(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    inferred_error_set: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index);
    const target = sema.mod.getTarget();
    const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = inst_data.src_node };

    var extra_index = extra.end;

    const ret_ty: Type = switch (extra.data.ret_body_len) {
        0 => Type.void,
        1 => blk: {
            const ret_ty_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
            extra_index += 1;
            if (sema.resolveType(block, ret_ty_src, ret_ty_ref)) |ret_ty| {
                break :blk ret_ty;
            } else |err| switch (err) {
                error.GenericPoison => {
                    break :blk Type.initTag(.generic_poison);
                },
                else => |e| return e,
            }
        },
        else => blk: {
            const ret_ty_body = sema.code.extra[extra_index..][0..extra.data.ret_body_len];
            extra_index += ret_ty_body.len;

            const ret_ty_val = try sema.resolveGenericBody(block, ret_ty_src, ret_ty_body, inst, Type.type, "return type must be comptime-known");
            var buffer: Value.ToTypeBuffer = undefined;
            break :blk try ret_ty_val.toType(&buffer).copy(sema.arena);
        },
    };

    var src_locs: Zir.Inst.Func.SrcLocs = undefined;
    const has_body = extra.data.body_len != 0;
    if (has_body) {
        extra_index += extra.data.body_len;
        src_locs = sema.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
    }

    // If this instruction has a body it means it's the type of the `owner_decl`
    // otherwise it's a function type without a `callconv` attribute and should
    // never be `.C`.
    // NOTE: revisit when doing #1717
    const cc: std.builtin.CallingConvention = if (sema.owner_decl.is_exported and has_body)
        .C
    else
        .Unspecified;

    return sema.funcCommon(
        block,
        inst_data.src_node,
        inst,
        0,
        target_util.defaultAddressSpace(target, .function),
        FuncLinkSection.default,
        cc,
        ret_ty,
        false,
        inferred_error_set,
        false,
        has_body,
        src_locs,
        null,
        0,
        false,
    );
}

fn resolveGenericBody(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    body: []const Zir.Inst.Index,
    func_inst: Zir.Inst.Index,
    dest_ty: Type,
    reason: []const u8,
) !Value {
    assert(body.len != 0);

    const err = err: {
        // Make sure any nested param instructions don't clobber our work.
        const prev_params = block.params;
        block.params = .{};
        defer {
            block.params.deinit(sema.gpa);
            block.params = prev_params;
        }

        const uncasted = sema.resolveBody(block, body, func_inst) catch |err| break :err err;
        const result = sema.coerce(block, dest_ty, uncasted, src) catch |err| break :err err;
        const val = sema.resolveConstValue(block, src, result, reason) catch |err| break :err err;
        return val;
    };
    switch (err) {
        error.GenericPoison => {
            if (dest_ty.tag() == .type) {
                return Value.initTag(.generic_poison_type);
            } else {
                return Value.initTag(.generic_poison);
            }
        },
        else => |e| return e,
    }
}

/// Given a library name, examines if the library name should end up in
/// `link.File.Options.system_libs` table (for example, libc is always
/// specified via dedicated flag `link.File.Options.link_libc` instead),
/// and puts it there if it doesn't exist.
/// It also dupes the library name which can then be saved as part of the
/// respective `Decl` (either `ExternFn` or `Var`).
/// The liveness of the duped library name is tied to liveness of `Module`.
/// To deallocate, call `deinit` on the respective `Decl` (`ExternFn` or `Var`).
fn handleExternLibName(
    sema: *Sema,
    block: *Block,
    src_loc: LazySrcLoc,
    lib_name: []const u8,
) CompileError![:0]u8 {
    blk: {
        const mod = sema.mod;
        const comp = mod.comp;
        const target = mod.getTarget();
        log.debug("extern fn symbol expected in lib '{s}'", .{lib_name});
        if (target_util.is_libc_lib_name(target, lib_name)) {
            if (!comp.bin_file.options.link_libc and !comp.bin_file.options.parent_compilation_link_libc) {
                return sema.fail(
                    block,
                    src_loc,
                    "dependency on libc must be explicitly specified in the build command",
                    .{},
                );
            }
            comp.bin_file.options.link_libc = true;
            break :blk;
        }
        if (target_util.is_libcpp_lib_name(target, lib_name)) {
            if (!comp.bin_file.options.link_libcpp) {
                return sema.fail(
                    block,
                    src_loc,
                    "dependency on libc++ must be explicitly specified in the build command",
                    .{},
                );
            }
            comp.bin_file.options.link_libcpp = true;
            break :blk;
        }
        if (mem.eql(u8, lib_name, "unwind")) {
            comp.bin_file.options.link_libunwind = true;
            break :blk;
        }
        if (!target.isWasm() and !comp.bin_file.options.pic) {
            return sema.fail(
                block,
                src_loc,
                "dependency on dynamic library '{s}' requires enabling Position Independent Code. Fixed by '-l{s}' or '-fPIC'.",
                .{ lib_name, lib_name },
            );
        }
        comp.addLinkLib(lib_name) catch |err| {
            return sema.fail(block, src_loc, "unable to add link lib '{s}': {s}", .{
                lib_name, @errorName(err),
            });
        };
    }
    return sema.gpa.dupeZ(u8, lib_name);
}

const FuncLinkSection = union(enum) {
    generic,
    default,
    explicit: []const u8,
};

fn funcCommon(
    sema: *Sema,
    block: *Block,
    src_node_offset: i32,
    func_inst: Zir.Inst.Index,
    /// null means generic poison
    alignment: ?u32,
    /// null means generic poison
    address_space: ?std.builtin.AddressSpace,
    /// outer null means generic poison; inner null means default link section
    section: FuncLinkSection,
    /// null means generic poison
    cc: ?std.builtin.CallingConvention,
    /// this might be Type.generic_poison
    bare_return_type: Type,
    var_args: bool,
    inferred_error_set: bool,
    is_extern: bool,
    has_body: bool,
    src_locs: Zir.Inst.Func.SrcLocs,
    opt_lib_name: ?[]const u8,
    noalias_bits: u32,
    is_noinline: bool,
) CompileError!Air.Inst.Ref {
    const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = src_node_offset };
    const cc_src: LazySrcLoc = .{ .node_offset_fn_type_cc = src_node_offset };
    const func_src = LazySrcLoc.nodeOffset(src_node_offset);

    var is_generic = bare_return_type.tag() == .generic_poison or
        alignment == null or
        address_space == null or
        section == .generic or
        cc == null;

    if (var_args) {
        if (is_generic) {
            return sema.fail(block, func_src, "generic function cannot be variadic", .{});
        }
        if (cc.? != .C) {
            return sema.fail(block, cc_src, "variadic function must have 'C' calling convention", .{});
        }
    }

    var destroy_fn_on_error = false;
    const new_func: *Module.Fn = new_func: {
        if (!has_body) break :new_func undefined;
        if (sema.comptime_args_fn_inst == func_inst) {
            const new_func = sema.preallocated_new_func.?;
            sema.preallocated_new_func = null; // take ownership
            break :new_func new_func;
        }
        destroy_fn_on_error = true;
        const new_func = try sema.gpa.create(Module.Fn);
        // Set this here so that the inferred return type can be printed correctly if it appears in an error.
        new_func.owner_decl = sema.owner_decl_index;
        break :new_func new_func;
    };
    errdefer if (destroy_fn_on_error) sema.gpa.destroy(new_func);

    var maybe_inferred_error_set_node: ?*Module.Fn.InferredErrorSetListNode = null;
    errdefer if (maybe_inferred_error_set_node) |node| sema.gpa.destroy(node);
    // Note: no need to errdefer since this will still be in its default state at the end of the function.

    const target = sema.mod.getTarget();
    const fn_ty: Type = fn_ty: {
        // Hot path for some common function types.
        // TODO can we eliminate some of these Type tag values? seems unnecessarily complicated.
        if (!is_generic and block.params.items.len == 0 and !var_args and !inferred_error_set and
            alignment.? == 0 and
            address_space.? == target_util.defaultAddressSpace(target, .function) and
            section == .default)
        {
            if (bare_return_type.zigTypeTag() == .NoReturn and cc.? == .Unspecified) {
                break :fn_ty Type.initTag(.fn_noreturn_no_args);
            }

            if (bare_return_type.zigTypeTag() == .Void and cc.? == .Unspecified) {
                break :fn_ty Type.initTag(.fn_void_no_args);
            }

            if (bare_return_type.zigTypeTag() == .NoReturn and cc.? == .Naked) {
                break :fn_ty Type.initTag(.fn_naked_noreturn_no_args);
            }

            if (bare_return_type.zigTypeTag() == .Void and cc.? == .C) {
                break :fn_ty Type.initTag(.fn_ccc_void_no_args);
            }
        }

        // In the case of generic calling convention, or generic alignment, we use
        // default values which are only meaningful for the generic function, *not*
        // the instantiation, which can depend on comptime parameters.
        // Related proposal: https://github.com/ziglang/zig/issues/11834
        const cc_resolved = cc orelse .Unspecified;
        const param_types = try sema.arena.alloc(Type, block.params.items.len);
        const comptime_params = try sema.arena.alloc(bool, block.params.items.len);
        for (block.params.items, 0..) |param, i| {
            const is_noalias = blk: {
                const index = std.math.cast(u5, i) orelse break :blk false;
                break :blk @truncate(u1, noalias_bits >> index) != 0;
            };
            param_types[i] = param.ty;
            sema.analyzeParameter(
                block,
                .unneeded,
                param,
                comptime_params,
                i,
                &is_generic,
                cc_resolved,
                has_body,
                is_noalias,
            ) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const decl = sema.mod.declPtr(block.src_decl);
                    try sema.analyzeParameter(
                        block,
                        Module.paramSrc(src_node_offset, sema.gpa, decl, i),
                        param,
                        comptime_params,
                        i,
                        &is_generic,
                        cc_resolved,
                        has_body,
                        is_noalias,
                    );
                    unreachable;
                },
                else => |e| return e,
            };
        }

        var ret_ty_requires_comptime = false;
        const ret_poison = if (sema.typeRequiresComptime(bare_return_type)) |ret_comptime| rp: {
            ret_ty_requires_comptime = ret_comptime;
            break :rp bare_return_type.tag() == .generic_poison;
        } else |err| switch (err) {
            error.GenericPoison => rp: {
                is_generic = true;
                break :rp true;
            },
            else => |e| return e,
        };

        const return_type = if (!inferred_error_set or ret_poison)
            bare_return_type
        else blk: {
            try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
            const node = try sema.gpa.create(Module.Fn.InferredErrorSetListNode);
            node.data = .{ .func = new_func };
            maybe_inferred_error_set_node = node;

            const error_set_ty = try Type.Tag.error_set_inferred.create(sema.arena, &node.data);
            break :blk try Type.Tag.error_union.create(sema.arena, .{
                .error_set = error_set_ty,
                .payload = bare_return_type,
            });
        };

        if (!return_type.isValidReturnType()) {
            const opaque_str = if (return_type.zigTypeTag() == .Opaque) "opaque " else "";
            const msg = msg: {
                const msg = try sema.errMsg(block, ret_ty_src, "{s}return type '{}' not allowed", .{
                    opaque_str, return_type.fmt(sema.mod),
                });
                errdefer msg.destroy(sema.gpa);

                try sema.addDeclaredHereNote(msg, return_type);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (!ret_poison and !Type.fnCallingConventionAllowsZigTypes(cc_resolved) and !try sema.validateExternType(return_type, .ret_ty)) {
            const msg = msg: {
                const msg = try sema.errMsg(block, ret_ty_src, "return type '{}' not allowed in function with calling convention '{s}'", .{
                    return_type.fmt(sema.mod), @tagName(cc_resolved),
                });
                errdefer msg.destroy(sema.gpa);

                const src_decl = sema.mod.declPtr(block.src_decl);
                try sema.explainWhyTypeIsNotExtern(msg, ret_ty_src.toSrcLoc(src_decl), return_type, .ret_ty);

                try sema.addDeclaredHereNote(msg, return_type);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }

        // If the return type is comptime-only but not dependent on parameters then all parameter types also need to be comptime
        if (!sema.is_generic_instantiation and has_body and ret_ty_requires_comptime) comptime_check: {
            for (block.params.items) |param| {
                if (!param.is_comptime) break;
            } else break :comptime_check;

            const msg = try sema.errMsg(
                block,
                ret_ty_src,
                "function with comptime-only return type '{}' requires all parameters to be comptime",
                .{return_type.fmt(sema.mod)},
            );
            try sema.explainWhyTypeIsComptime(block, ret_ty_src, msg, ret_ty_src.toSrcLoc(sema.owner_decl), return_type);

            const tags = sema.code.instructions.items(.tag);
            const data = sema.code.instructions.items(.data);
            const param_body = sema.code.getParamBody(func_inst);
            for (block.params.items, 0..) |param, i| {
                if (!param.is_comptime) {
                    const param_index = param_body[i];
                    const param_src = switch (tags[param_index]) {
                        .param => data[param_index].pl_tok.src(),
                        .param_anytype => data[param_index].str_tok.src(),
                        else => unreachable,
                    };
                    if (param.name.len != 0) {
                        try sema.errNote(block, param_src, msg, "param '{s}' is required to be comptime", .{param.name});
                    } else {
                        try sema.errNote(block, param_src, msg, "param is required to be comptime", .{});
                    }
                }
            }
            return sema.failWithOwnedErrorMsg(msg);
        }

        const arch = sema.mod.getTarget().cpu.arch;
        if (switch (cc_resolved) {
            .Unspecified, .C, .Naked, .Async, .Inline => null,
            .Interrupt => switch (arch) {
                .x86, .x86_64, .avr, .msp430 => null,
                else => @as([]const u8, "x86, x86_64, AVR, and MSP430"),
            },
            .Signal => switch (arch) {
                .avr => null,
                else => @as([]const u8, "AVR"),
            },
            .Stdcall, .Fastcall, .Thiscall => switch (arch) {
                .x86 => null,
                else => @as([]const u8, "x86"),
            },
            .Vectorcall => switch (arch) {
                .x86, .aarch64, .aarch64_be, .aarch64_32 => null,
                else => @as([]const u8, "x86 and AArch64"),
            },
            .APCS, .AAPCS, .AAPCSVFP => switch (arch) {
                .arm, .armeb, .aarch64, .aarch64_be, .aarch64_32, .thumb, .thumbeb => null,
                else => @as([]const u8, "ARM"),
            },
            .SysV, .Win64 => switch (arch) {
                .x86_64 => null,
                else => @as([]const u8, "x86_64"),
            },
            .PtxKernel => switch (arch) {
                .nvptx, .nvptx64 => null,
                else => @as([]const u8, "nvptx and nvptx64"),
            },
            .AmdgpuKernel => switch (arch) {
                .amdgcn => null,
                else => @as([]const u8, "amdgcn"),
            },
        }) |allowed_platform| {
            return sema.fail(block, cc_src, "callconv '{s}' is only available on {s}, not {s}", .{
                @tagName(cc_resolved),
                allowed_platform,
                @tagName(arch),
            });
        }

        if (cc_resolved == .Inline and is_noinline) {
            return sema.fail(block, cc_src, "'noinline' function cannot have callconv 'Inline'", .{});
        }
        if (is_generic and sema.no_partial_func_ty) return error.GenericPoison;
        for (comptime_params) |ct| is_generic = is_generic or ct;
        is_generic = is_generic or ret_ty_requires_comptime;

        if (!is_generic and sema.wantErrorReturnTracing(return_type)) {
            // Make sure that StackTrace's fields are resolved so that the backend can
            // lower this fn type.
            const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
            _ = try sema.resolveTypeFields(unresolved_stack_trace_ty);
        }

        break :fn_ty try Type.Tag.function.create(sema.arena, .{
            .param_types = param_types,
            .comptime_params = comptime_params.ptr,
            .return_type = return_type,
            .cc = cc_resolved,
            .cc_is_generic = cc == null,
            .alignment = alignment orelse 0,
            .align_is_generic = alignment == null,
            .section_is_generic = section == .generic,
            .addrspace_is_generic = address_space == null,
            .is_var_args = var_args,
            .is_generic = is_generic,
            .noalias_bits = noalias_bits,
        });
    };

    sema.owner_decl.@"linksection" = switch (section) {
        .generic => undefined,
        .default => null,
        .explicit => |section_name| try sema.perm_arena.dupeZ(u8, section_name),
    };
    sema.owner_decl.@"align" = alignment orelse 0;
    sema.owner_decl.@"addrspace" = address_space orelse .generic;

    if (is_extern) {
        const new_extern_fn = try sema.gpa.create(Module.ExternFn);
        errdefer sema.gpa.destroy(new_extern_fn);

        new_extern_fn.* = Module.ExternFn{
            .owner_decl = sema.owner_decl_index,
            .lib_name = null,
        };

        if (opt_lib_name) |lib_name| {
            new_extern_fn.lib_name = try sema.handleExternLibName(block, .{
                .node_offset_lib_name = src_node_offset,
            }, lib_name);
        }

        const extern_fn_payload = try sema.arena.create(Value.Payload.ExternFn);
        extern_fn_payload.* = .{
            .base = .{ .tag = .extern_fn },
            .data = new_extern_fn,
        };
        return sema.addConstant(fn_ty, Value.initPayload(&extern_fn_payload.base));
    }

    if (!has_body) {
        return sema.addType(fn_ty);
    }

    const is_inline = fn_ty.fnCallingConvention() == .Inline;
    const anal_state: Module.Fn.Analysis = if (is_inline) .inline_only else .queued;

    const comptime_args: ?[*]TypedValue = if (sema.comptime_args_fn_inst == func_inst) blk: {
        break :blk if (sema.comptime_args.len == 0) null else sema.comptime_args.ptr;
    } else null;

    const hash = new_func.hash;
    const generic_owner_decl = if (comptime_args == null) .none else new_func.generic_owner_decl;
    const fn_payload = try sema.arena.create(Value.Payload.Function);
    new_func.* = .{
        .state = anal_state,
        .zir_body_inst = func_inst,
        .owner_decl = sema.owner_decl_index,
        .generic_owner_decl = generic_owner_decl,
        .comptime_args = comptime_args,
        .hash = hash,
        .lbrace_line = src_locs.lbrace_line,
        .rbrace_line = src_locs.rbrace_line,
        .lbrace_column = @truncate(u16, src_locs.columns),
        .rbrace_column = @truncate(u16, src_locs.columns >> 16),
        .branch_quota = default_branch_quota,
        .is_noinline = is_noinline,
    };
    if (maybe_inferred_error_set_node) |node| {
        new_func.inferred_error_sets.prepend(node);
    }
    maybe_inferred_error_set_node = null;
    fn_payload.* = .{
        .base = .{ .tag = .function },
        .data = new_func,
    };
    return sema.addConstant(fn_ty, Value.initPayload(&fn_payload.base));
}

fn analyzeParameter(
    sema: *Sema,
    block: *Block,
    param_src: LazySrcLoc,
    param: Block.Param,
    comptime_params: []bool,
    i: usize,
    is_generic: *bool,
    cc: std.builtin.CallingConvention,
    has_body: bool,
    is_noalias: bool,
) !void {
    const requires_comptime = try sema.typeRequiresComptime(param.ty);
    comptime_params[i] = param.is_comptime or requires_comptime;
    const this_generic = param.ty.tag() == .generic_poison;
    is_generic.* = is_generic.* or this_generic;
    if (param.is_comptime and !Type.fnCallingConventionAllowsZigTypes(cc)) {
        return sema.fail(block, param_src, "comptime parameters not allowed in function with calling convention '{s}'", .{@tagName(cc)});
    }
    if (this_generic and !sema.no_partial_func_ty and !Type.fnCallingConventionAllowsZigTypes(cc)) {
        return sema.fail(block, param_src, "generic parameters not allowed in function with calling convention '{s}'", .{@tagName(cc)});
    }
    if (!param.ty.isValidParamType()) {
        const opaque_str = if (param.ty.zigTypeTag() == .Opaque) "opaque " else "";
        const msg = msg: {
            const msg = try sema.errMsg(block, param_src, "parameter of {s}type '{}' not allowed", .{
                opaque_str, param.ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);

            try sema.addDeclaredHereNote(msg, param.ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    if (!this_generic and !Type.fnCallingConventionAllowsZigTypes(cc) and !try sema.validateExternType(param.ty, .param_ty)) {
        const msg = msg: {
            const msg = try sema.errMsg(block, param_src, "parameter of type '{}' not allowed in function with calling convention '{s}'", .{
                param.ty.fmt(sema.mod), @tagName(cc),
            });
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsNotExtern(msg, param_src.toSrcLoc(src_decl), param.ty, .param_ty);

            try sema.addDeclaredHereNote(msg, param.ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    if (!sema.is_generic_instantiation and requires_comptime and !param.is_comptime and has_body) {
        const msg = msg: {
            const msg = try sema.errMsg(block, param_src, "parameter of type '{}' must be declared comptime", .{
                param.ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsComptime(block, param_src, msg, param_src.toSrcLoc(src_decl), param.ty);

            try sema.addDeclaredHereNote(msg, param.ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    if (!sema.is_generic_instantiation and !this_generic and is_noalias and
        !(param.ty.zigTypeTag() == .Pointer or param.ty.isPtrLikeOptional()))
    {
        return sema.fail(block, param_src, "non-pointer parameter declared noalias", .{});
    }
}

fn zirParam(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    comptime_syntax: bool,
) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_tok;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Param, inst_data.payload_index);
    const param_name = sema.code.nullTerminatedString(extra.data.name);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];

    // We could be in a generic function instantiation, or we could be evaluating a generic
    // function without any comptime args provided.
    const param_ty = param_ty: {
        const err = err: {
            // Make sure any nested param instructions don't clobber our work.
            const prev_params = block.params;
            const prev_preallocated_new_func = sema.preallocated_new_func;
            const prev_no_partial_func_type = sema.no_partial_func_ty;
            block.params = .{};
            sema.preallocated_new_func = null;
            sema.no_partial_func_ty = true;
            defer {
                block.params.deinit(sema.gpa);
                block.params = prev_params;
                sema.preallocated_new_func = prev_preallocated_new_func;
                sema.no_partial_func_ty = prev_no_partial_func_type;
            }

            if (sema.resolveBody(block, body, inst)) |param_ty_inst| {
                if (sema.analyzeAsType(block, src, param_ty_inst)) |param_ty| {
                    break :param_ty param_ty;
                } else |err| break :err err;
            } else |err| break :err err;
        };
        switch (err) {
            error.GenericPoison => {
                if (sema.inst_map.get(inst)) |_| {
                    // A generic function is about to evaluate to another generic function.
                    // Return an error instead.
                    return error.GenericPoison;
                }
                // The type is not available until the generic instantiation.
                // We result the param instruction with a poison value and
                // insert an anytype parameter.
                try block.params.append(sema.gpa, .{
                    .ty = Type.initTag(.generic_poison),
                    .is_comptime = comptime_syntax,
                    .name = param_name,
                });
                sema.inst_map.putAssumeCapacityNoClobber(inst, .generic_poison);
                return;
            },
            else => |e| return e,
        }
    };
    const is_comptime = sema.typeRequiresComptime(param_ty) catch |err| switch (err) {
        error.GenericPoison => {
            if (sema.inst_map.get(inst)) |_| {
                // A generic function is about to evaluate to another generic function.
                // Return an error instead.
                return error.GenericPoison;
            }
            // The type is not available until the generic instantiation.
            // We result the param instruction with a poison value and
            // insert an anytype parameter.
            try block.params.append(sema.gpa, .{
                .ty = Type.initTag(.generic_poison),
                .is_comptime = comptime_syntax,
                .name = param_name,
            });
            sema.inst_map.putAssumeCapacityNoClobber(inst, .generic_poison);
            return;
        },
        else => |e| return e,
    } or comptime_syntax;
    if (sema.inst_map.get(inst)) |arg| {
        if (is_comptime and sema.preallocated_new_func != null) {
            // We have a comptime value for this parameter so it should be elided from the
            // function type of the function instruction in this block.
            const coerced_arg = sema.coerce(block, param_ty, arg, .unneeded) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    // We are instantiating a generic function and a comptime arg
                    // cannot be coerced to the param type, but since we don't
                    // have the callee source location return `GenericPoison`
                    // so that the instantiation is failed and the coercion
                    // is handled by comptime call logic instead.
                    assert(sema.is_generic_instantiation);
                    return error.GenericPoison;
                },
                else => return err,
            };
            sema.inst_map.putAssumeCapacity(inst, coerced_arg);
            return;
        }
        // Even though a comptime argument is provided, the generic function wants to treat
        // this as a runtime parameter.
        assert(sema.inst_map.remove(inst));
    }

    if (sema.preallocated_new_func != null) {
        if (try sema.typeHasOnePossibleValue(param_ty)) |opv| {
            // In this case we are instantiating a generic function call with a non-comptime
            // non-anytype parameter that ended up being a one-possible-type.
            // We don't want the parameter to be part of the instantiated function type.
            const result = try sema.addConstant(param_ty, opv);
            sema.inst_map.putAssumeCapacity(inst, result);
            return;
        }
    }

    try block.params.append(sema.gpa, .{
        .ty = param_ty,
        .is_comptime = comptime_syntax,
        .name = param_name,
    });

    if (is_comptime) {
        // If this is a comptime parameter we can add a constant generic_poison
        // since this is also a generic parameter.
        const result = try sema.addConstant(param_ty, Value.initTag(.generic_poison));
        sema.inst_map.putAssumeCapacityNoClobber(inst, result);
    } else {
        // Otherwise we need a dummy runtime instruction.
        const result_index = @intCast(Air.Inst.Index, sema.air_instructions.len);
        try sema.air_instructions.append(sema.gpa, .{
            .tag = .alloc,
            .data = .{ .ty = param_ty },
        });
        const result = Air.indexToRef(result_index);
        sema.inst_map.putAssumeCapacityNoClobber(inst, result);
    }
}

fn zirParamAnytype(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    comptime_syntax: bool,
) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const param_name = inst_data.get(sema.code);

    if (sema.inst_map.get(inst)) |air_ref| {
        const param_ty = sema.typeOf(air_ref);
        if (comptime_syntax or try sema.typeRequiresComptime(param_ty)) {
            // We have a comptime value for this parameter so it should be elided from the
            // function type of the function instruction in this block.
            return;
        }
        if (null != try sema.typeHasOnePossibleValue(param_ty)) {
            return;
        }
        // The map is already populated but we do need to add a runtime parameter.
        try block.params.append(sema.gpa, .{
            .ty = param_ty,
            .is_comptime = false,
            .name = param_name,
        });
        return;
    }

    // We are evaluating a generic function without any comptime args provided.

    try block.params.append(sema.gpa, .{
        .ty = Type.initTag(.generic_poison),
        .is_comptime = comptime_syntax,
        .name = param_name,
    });
    sema.inst_map.putAssumeCapacity(inst, .generic_poison);
}

fn zirAs(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const bin_inst = sema.code.instructions.items(.data)[inst].bin;
    return sema.analyzeAs(block, sema.src, bin_inst.lhs, bin_inst.rhs, false);
}

fn zirAsNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.As, inst_data.payload_index).data;
    sema.src = src;
    return sema.analyzeAs(block, src, extra.dest_type, extra.operand, false);
}

fn zirAsShiftOperand(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.As, inst_data.payload_index).data;
    return sema.analyzeAs(block, src, extra.dest_type, extra.operand, true);
}

fn analyzeAs(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_dest_type: Zir.Inst.Ref,
    zir_operand: Zir.Inst.Ref,
    no_cast_to_comptime_int: bool,
) CompileError!Air.Inst.Ref {
    const is_ret = if (Zir.refToIndex(zir_dest_type)) |ptr_index|
        sema.code.instructions.items(.tag)[ptr_index] == .ret_type
    else
        false;
    const dest_ty = try sema.resolveType(block, src, zir_dest_type);
    const operand = try sema.resolveInst(zir_operand);
    if (dest_ty.tag() == .var_args_param) return operand;
    if (dest_ty.zigTypeTag() == .NoReturn) {
        return sema.fail(block, src, "cannot cast to noreturn", .{});
    }
    return sema.coerceExtra(block, dest_ty, operand, src, .{ .is_ret = is_ret, .no_cast_to_comptime_int = no_cast_to_comptime_int }) catch |err| switch (err) {
        error.NotCoercible => unreachable,
        else => |e| return e,
    };
}

fn zirPtrToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ptr = try sema.resolveInst(inst_data.operand);
    const ptr_ty = sema.typeOf(ptr);
    if (!ptr_ty.isPtrAtRuntime()) {
        return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)});
    }
    if (try sema.resolveMaybeUndefValIntable(ptr)) |ptr_val| {
        return sema.addConstant(Type.usize, ptr_val);
    }
    try sema.requireRuntimeBlock(block, inst_data.src(), ptr_src);
    return block.addUnOp(.ptrtoint, ptr);
}

fn zirFieldVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const field_name_src: LazySrcLoc = .{ .node_offset_field_name = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
    const field_name = sema.code.nullTerminatedString(extra.field_name_start);
    const object = try sema.resolveInst(extra.lhs);
    return sema.fieldVal(block, src, object, field_name, field_name_src);
}

fn zirFieldPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index, initializing: bool) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const field_name_src: LazySrcLoc = .{ .node_offset_field_name = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
    const field_name = sema.code.nullTerminatedString(extra.field_name_start);
    const object_ptr = try sema.resolveInst(extra.lhs);
    return sema.fieldPtr(block, src, object_ptr, field_name, field_name_src, initializing);
}

fn zirFieldCallBind(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const field_name_src: LazySrcLoc = .{ .node_offset_field_name = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
    const field_name = sema.code.nullTerminatedString(extra.field_name_start);
    const object_ptr = try sema.resolveInst(extra.lhs);
    return sema.fieldCallBind(block, src, object_ptr, field_name, field_name_src);
}

fn zirFieldValNamed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const field_name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
    const object = try sema.resolveInst(extra.lhs);
    const field_name = try sema.resolveConstString(block, field_name_src, extra.field_name, "field name must be comptime-known");
    return sema.fieldVal(block, src, object, field_name, field_name_src);
}

fn zirFieldPtrNamed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const field_name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
    const object_ptr = try sema.resolveInst(extra.lhs);
    const field_name = try sema.resolveConstString(block, field_name_src, extra.field_name, "field name must be comptime-known");
    return sema.fieldPtr(block, src, object_ptr, field_name, field_name_src, false);
}

fn zirFieldCallBindNamed(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.FieldNamedNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const field_name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
    const object_ptr = try sema.resolveInst(extra.lhs);
    const field_name = try sema.resolveConstString(block, field_name_src, extra.field_name, "field name must be comptime-known");
    return sema.fieldCallBind(block, src, object_ptr, field_name, field_name_src);
}

fn zirIntCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;

    const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);

    return sema.intCast(block, inst_data.src(), dest_ty, dest_ty_src, operand, operand_src, true);
}

fn intCast(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    dest_ty: Type,
    dest_ty_src: LazySrcLoc,
    operand: Air.Inst.Ref,
    operand_src: LazySrcLoc,
    runtime_safety: bool,
) CompileError!Air.Inst.Ref {
    const operand_ty = sema.typeOf(operand);
    const dest_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, dest_ty, dest_ty_src);
    const operand_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, operand_ty, operand_src);

    if (try sema.isComptimeKnown(operand)) {
        return sema.coerce(block, dest_ty, operand, operand_src);
    } else if (dest_scalar_ty.zigTypeTag() == .ComptimeInt) {
        return sema.fail(block, operand_src, "unable to cast runtime value to 'comptime_int'", .{});
    }

    try sema.checkVectorizableBinaryOperands(block, operand_src, dest_ty, operand_ty, dest_ty_src, operand_src);
    const is_vector = dest_ty.zigTypeTag() == .Vector;

    if ((try sema.typeHasOnePossibleValue(dest_ty))) |opv| {
        // requirement: intCast(u0, input) iff input == 0
        if (runtime_safety and block.wantSafety()) {
            try sema.requireRuntimeBlock(block, src, operand_src);
            const target = sema.mod.getTarget();
            const wanted_info = dest_scalar_ty.intInfo(target);
            const wanted_bits = wanted_info.bits;

            if (wanted_bits == 0) {
                const ok = if (is_vector) ok: {
                    const zeros = try Value.Tag.repeated.create(sema.arena, Value.zero);
                    const zero_inst = try sema.addConstant(sema.typeOf(operand), zeros);
                    const is_in_range = try block.addCmpVector(operand, zero_inst, .eq);
                    const all_in_range = try block.addInst(.{
                        .tag = .reduce,
                        .data = .{ .reduce = .{ .operand = is_in_range, .operation = .And } },
                    });
                    break :ok all_in_range;
                } else ok: {
                    const zero_inst = try sema.addConstant(sema.typeOf(operand), Value.zero);
                    const is_in_range = try block.addBinOp(.cmp_lte, operand, zero_inst);
                    break :ok is_in_range;
                };
                try sema.addSafetyCheck(block, ok, .cast_truncated_data);
            }
        }

        return sema.addConstant(dest_ty, opv);
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    if (runtime_safety and block.wantSafety()) {
        const target = sema.mod.getTarget();
        const actual_info = operand_scalar_ty.intInfo(target);
        const wanted_info = dest_scalar_ty.intInfo(target);
        const actual_bits = actual_info.bits;
        const wanted_bits = wanted_info.bits;
        const actual_value_bits = actual_bits - @boolToInt(actual_info.signedness == .signed);
        const wanted_value_bits = wanted_bits - @boolToInt(wanted_info.signedness == .signed);

        // range shrinkage
        // requirement: int value fits into target type
        if (wanted_value_bits < actual_value_bits) {
            const dest_max_val_scalar = try dest_scalar_ty.maxInt(sema.arena, target);
            const dest_max_val = if (is_vector)
                try Value.Tag.repeated.create(sema.arena, dest_max_val_scalar)
            else
                dest_max_val_scalar;
            const dest_max = try sema.addConstant(operand_ty, dest_max_val);
            const diff = try block.addBinOp(.subwrap, dest_max, operand);

            if (actual_info.signedness == .signed) {
                // Reinterpret the sign-bit as part of the value. This will make
                // negative differences (`operand` > `dest_max`) appear too big.
                const unsigned_operand_ty = try Type.Tag.int_unsigned.create(sema.arena, actual_bits);
                const diff_unsigned = try block.addBitCast(unsigned_operand_ty, diff);

                // If the destination type is signed, then we need to double its
                // range to account for negative values.
                const dest_range_val = if (wanted_info.signedness == .signed) range_val: {
                    const range_minus_one = try dest_max_val.shl(Value.one, unsigned_operand_ty, sema.arena, sema.mod);
                    break :range_val try sema.intAdd(range_minus_one, Value.one, unsigned_operand_ty);
                } else dest_max_val;
                const dest_range = try sema.addConstant(unsigned_operand_ty, dest_range_val);

                const ok = if (is_vector) ok: {
                    const is_in_range = try block.addCmpVector(diff_unsigned, dest_range, .lte);
                    const all_in_range = try block.addInst(.{
                        .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
                        .data = .{ .reduce = .{
                            .operand = is_in_range,
                            .operation = .And,
                        } },
                    });
                    break :ok all_in_range;
                } else ok: {
                    const is_in_range = try block.addBinOp(.cmp_lte, diff_unsigned, dest_range);
                    break :ok is_in_range;
                };
                // TODO negative_to_unsigned?
                try sema.addSafetyCheck(block, ok, .cast_truncated_data);
            } else {
                const ok = if (is_vector) ok: {
                    const is_in_range = try block.addCmpVector(diff, dest_max, .lte);
                    const all_in_range = try block.addInst(.{
                        .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
                        .data = .{ .reduce = .{
                            .operand = is_in_range,
                            .operation = .And,
                        } },
                    });
                    break :ok all_in_range;
                } else ok: {
                    const is_in_range = try block.addBinOp(.cmp_lte, diff, dest_max);
                    break :ok is_in_range;
                };
                try sema.addSafetyCheck(block, ok, .cast_truncated_data);
            }
        } else if (actual_info.signedness == .signed and wanted_info.signedness == .unsigned) {
            // no shrinkage, yes sign loss
            // requirement: signed to unsigned >= 0
            const ok = if (is_vector) ok: {
                const zero_val = try Value.Tag.repeated.create(sema.arena, Value.zero);
                const zero_inst = try sema.addConstant(operand_ty, zero_val);
                const is_in_range = try block.addCmpVector(operand, zero_inst, .gte);
                const all_in_range = try block.addInst(.{
                    .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
                    .data = .{ .reduce = .{
                        .operand = is_in_range,
                        .operation = .And,
                    } },
                });
                break :ok all_in_range;
            } else ok: {
                const zero_inst = try sema.addConstant(operand_ty, Value.zero);
                const is_in_range = try block.addBinOp(.cmp_gte, operand, zero_inst);
                break :ok is_in_range;
            };
            try sema.addSafetyCheck(block, ok, .negative_to_unsigned);
        }
    }
    return block.addTyOp(.intcast, dest_ty, operand);
}

fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;

    const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);
    const operand_ty = sema.typeOf(operand);
    switch (dest_ty.zigTypeTag()) {
        .AnyFrame,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .ErrorSet,
        .ErrorUnion,
        .Fn,
        .Frame,
        .NoReturn,
        .Null,
        .Opaque,
        .Optional,
        .Type,
        .Undefined,
        .Void,
        => return sema.fail(block, dest_ty_src, "cannot @bitCast to '{}'", .{dest_ty.fmt(sema.mod)}),

        .Enum => {
            const msg = msg: {
                const msg = try sema.errMsg(block, dest_ty_src, "cannot @bitCast to '{}'", .{dest_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);
                switch (operand_ty.zigTypeTag()) {
                    .Int, .ComptimeInt => try sema.errNote(block, dest_ty_src, msg, "use @intToEnum to cast from '{}'", .{operand_ty.fmt(sema.mod)}),
                    else => {},
                }

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },

        .Pointer => {
            const msg = msg: {
                const msg = try sema.errMsg(block, dest_ty_src, "cannot @bitCast to '{}'", .{dest_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);
                switch (operand_ty.zigTypeTag()) {
                    .Int, .ComptimeInt => try sema.errNote(block, dest_ty_src, msg, "use @intToPtr to cast from '{}'", .{operand_ty.fmt(sema.mod)}),
                    .Pointer => try sema.errNote(block, dest_ty_src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(sema.mod)}),
                    else => {},
                }

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        .Struct, .Union => if (dest_ty.containerLayout() == .Auto) {
            const container = switch (dest_ty.zigTypeTag()) {
                .Struct => "struct",
                .Union => "union",
                else => unreachable,
            };
            return sema.fail(block, dest_ty_src, "cannot @bitCast to '{}', {s} does not have a guaranteed in-memory layout", .{
                dest_ty.fmt(sema.mod), container,
            });
        },

        .Array,
        .Bool,
        .Float,
        .Int,
        .Vector,
        => {},
    }
    switch (operand_ty.zigTypeTag()) {
        .AnyFrame,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .ErrorSet,
        .ErrorUnion,
        .Fn,
        .Frame,
        .NoReturn,
        .Null,
        .Opaque,
        .Optional,
        .Type,
        .Undefined,
        .Void,
        => return sema.fail(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(sema.mod)}),

        .Enum => {
            const msg = msg: {
                const msg = try sema.errMsg(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);
                switch (dest_ty.zigTypeTag()) {
                    .Int, .ComptimeInt => try sema.errNote(block, operand_src, msg, "use @enumToInt to cast to '{}'", .{dest_ty.fmt(sema.mod)}),
                    else => {},
                }

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        .Pointer => {
            const msg = msg: {
                const msg = try sema.errMsg(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);
                switch (dest_ty.zigTypeTag()) {
                    .Int, .ComptimeInt => try sema.errNote(block, operand_src, msg, "use @ptrToInt to cast to '{}'", .{dest_ty.fmt(sema.mod)}),
                    .Pointer => try sema.errNote(block, operand_src, msg, "use @ptrCast to cast to '{}'", .{dest_ty.fmt(sema.mod)}),
                    else => {},
                }

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        .Struct, .Union => if (operand_ty.containerLayout() == .Auto) {
            const container = switch (operand_ty.zigTypeTag()) {
                .Struct => "struct",
                .Union => "union",
                else => unreachable,
            };
            return sema.fail(block, operand_src, "cannot @bitCast from '{}', {s} does not have a guaranteed in-memory layout", .{
                operand_ty.fmt(sema.mod), container,
            });
        },

        .Array,
        .Bool,
        .Float,
        .Int,
        .Vector,
        => {},
    }
    return sema.bitCast(block, dest_ty, operand, inst_data.src(), operand_src);
}

fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;

    const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);

    const target = sema.mod.getTarget();
    const dest_is_comptime_float = switch (dest_ty.zigTypeTag()) {
        .ComptimeFloat => true,
        .Float => false,
        else => return sema.fail(
            block,
            dest_ty_src,
            "expected float type, found '{}'",
            .{dest_ty.fmt(sema.mod)},
        ),
    };

    const operand_ty = sema.typeOf(operand);
    switch (operand_ty.zigTypeTag()) {
        .ComptimeFloat, .Float, .ComptimeInt => {},
        else => return sema.fail(
            block,
            operand_src,
            "expected float type, found '{}'",
            .{operand_ty.fmt(sema.mod)},
        ),
    }

    if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
        return sema.addConstant(dest_ty, try operand_val.floatCast(sema.arena, dest_ty, target));
    }
    if (dest_is_comptime_float) {
        return sema.fail(block, operand_src, "unable to cast runtime value to 'comptime_float'", .{});
    }
    const src_bits = operand_ty.floatBits(target);
    const dst_bits = dest_ty.floatBits(target);
    if (dst_bits >= src_bits) {
        return sema.coerce(block, dest_ty, operand, operand_src);
    }
    try sema.requireRuntimeBlock(block, inst_data.src(), operand_src);
    return block.addTyOp(.fptrunc, dest_ty, operand);
}

fn zirElemVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const array = try sema.resolveInst(extra.lhs);
    const elem_index = try sema.resolveInst(extra.rhs);
    return sema.elemVal(block, src, array, elem_index, src, false);
}

fn zirElemValNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const elem_index_src: LazySrcLoc = .{ .node_offset_array_access_index = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const array = try sema.resolveInst(extra.lhs);
    const elem_index = try sema.resolveInst(extra.rhs);
    return sema.elemVal(block, src, array, elem_index, elem_index_src, true);
}

fn zirElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const array_ptr = try sema.resolveInst(extra.lhs);
    const elem_index = try sema.resolveInst(extra.rhs);
    const indexable_ty = sema.typeOf(array_ptr);
    if (indexable_ty.zigTypeTag() != .Pointer) {
        const capture_src: LazySrcLoc = .{ .for_capture_from_input = inst_data.src_node };
        const msg = msg: {
            const msg = try sema.errMsg(block, capture_src, "pointer capture of non pointer type '{}'", .{
                indexable_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            if (indexable_ty.zigTypeTag() == .Array) {
                try sema.errNote(block, src, msg, "consider using '&' here", .{});
            }
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    return sema.elemPtrOneLayerOnly(block, src, array_ptr, elem_index, src, false, false);
}

fn zirElemPtrNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const elem_index_src: LazySrcLoc = .{ .node_offset_array_access_index = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const array_ptr = try sema.resolveInst(extra.lhs);
    const elem_index = try sema.resolveInst(extra.rhs);
    return sema.elemPtr(block, src, array_ptr, elem_index, elem_index_src, false, true);
}

fn zirElemPtrImm(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.ElemPtrImm, inst_data.payload_index).data;
    const array_ptr = try sema.resolveInst(extra.ptr);
    const elem_index = try sema.addIntUnsigned(Type.usize, extra.index);
    return sema.elemPtr(block, src, array_ptr, elem_index, src, true, true);
}

fn zirSliceStart(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.SliceStart, inst_data.payload_index).data;
    const array_ptr = try sema.resolveInst(extra.lhs);
    const start = try sema.resolveInst(extra.start);

    return sema.analyzeSlice(block, src, array_ptr, start, .none, .none, .unneeded);
}

fn zirSliceEnd(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.SliceEnd, inst_data.payload_index).data;
    const array_ptr = try sema.resolveInst(extra.lhs);
    const start = try sema.resolveInst(extra.start);
    const end = try sema.resolveInst(extra.end);

    return sema.analyzeSlice(block, src, array_ptr, start, end, .none, .unneeded);
}

fn zirSliceSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const sentinel_src: LazySrcLoc = .{ .node_offset_slice_sentinel = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.SliceSentinel, inst_data.payload_index).data;
    const array_ptr = try sema.resolveInst(extra.lhs);
    const start = try sema.resolveInst(extra.start);
    const end = try sema.resolveInst(extra.end);
    const sentinel = try sema.resolveInst(extra.sentinel);

    return sema.analyzeSlice(block, src, array_ptr, start, end, sentinel, sentinel_src);
}

fn zirSwitchCapture(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_multi: bool,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const zir_datas = sema.code.instructions.items(.data);
    const capture_info = zir_datas[inst].switch_capture;
    const switch_info = zir_datas[capture_info.switch_inst].pl_node;
    const switch_extra = sema.code.extraData(Zir.Inst.SwitchBlock, switch_info.payload_index);
    const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = switch_info.src_node };
    const cond_inst = Zir.refToIndex(switch_extra.data.operand).?;
    const cond_info = zir_datas[cond_inst].un_node;
    const cond_tag = sema.code.instructions.items(.tag)[cond_inst];
    const operand_is_ref = cond_tag == .switch_cond_ref;
    const operand_ptr = try sema.resolveInst(cond_info.operand);
    const operand_ptr_ty = sema.typeOf(operand_ptr);
    const operand_ty = if (operand_is_ref) operand_ptr_ty.childType() else operand_ptr_ty;

    if (block.inline_case_capture != .none) {
        const item_val = sema.resolveConstValue(block, .unneeded, block.inline_case_capture, undefined) catch unreachable;
        if (operand_ty.zigTypeTag() == .Union) {
            const field_index = @intCast(u32, operand_ty.unionTagFieldIndex(item_val, sema.mod).?);
            const union_obj = operand_ty.cast(Type.Payload.Union).?.data;
            const field_ty = union_obj.fields.values()[field_index].ty;
            if (is_ref) {
                const ptr_field_ty = try Type.ptr(sema.arena, sema.mod, .{
                    .pointee_type = field_ty,
                    .mutable = operand_ptr_ty.ptrIsMutable(),
                    .@"volatile" = operand_ptr_ty.isVolatilePtr(),
                    .@"addrspace" = operand_ptr_ty.ptrAddressSpace(),
                });
                return block.addStructFieldPtr(operand_ptr, field_index, ptr_field_ty);
            } else {
                return block.addStructFieldVal(operand_ptr, field_index, field_ty);
            }
        } else if (is_ref) {
            return sema.addConstantMaybeRef(block, operand_ty, item_val, true);
        } else {
            return block.inline_case_capture;
        }
    }

    const operand = if (operand_is_ref)
        try sema.analyzeLoad(block, operand_src, operand_ptr, operand_src)
    else
        operand_ptr;

    if (capture_info.prong_index == std.math.maxInt(@TypeOf(capture_info.prong_index))) {
        // It is the else/`_` prong.
        if (is_ref) {
            return operand_ptr;
        }

        switch (operand_ty.zigTypeTag()) {
            .ErrorSet => if (block.switch_else_err_ty) |some| {
                return sema.bitCast(block, some, operand, operand_src, null);
            } else {
                try block.addUnreachable(false);
                return Air.Inst.Ref.unreachable_value;
            },
            else => return operand,
        }
    }

    const items = if (is_multi)
        switch_extra.data.getMultiProng(sema.code, switch_extra.end, capture_info.prong_index).items
    else
        &[_]Zir.Inst.Ref{
            switch_extra.data.getScalarProng(sema.code, switch_extra.end, capture_info.prong_index).item,
        };

    switch (operand_ty.zigTypeTag()) {
        .Union => {
            const union_obj = operand_ty.cast(Type.Payload.Union).?.data;
            const first_item = try sema.resolveInst(items[0]);
            // Previous switch validation ensured this will succeed
            const first_item_val = sema.resolveConstValue(block, .unneeded, first_item, "") catch unreachable;

            const first_field_index = @intCast(u32, operand_ty.unionTagFieldIndex(first_item_val, sema.mod).?);
            const first_field = union_obj.fields.values()[first_field_index];

            for (items[1..], 0..) |item, i| {
                const item_ref = try sema.resolveInst(item);
                // Previous switch validation ensured this will succeed
                const item_val = sema.resolveConstValue(block, .unneeded, item_ref, "") catch unreachable;

                const field_index = operand_ty.unionTagFieldIndex(item_val, sema.mod).?;
                const field = union_obj.fields.values()[field_index];
                if (!field.ty.eql(first_field.ty, sema.mod)) {
                    const msg = msg: {
                        const raw_capture_src = Module.SwitchProngSrc{ .multi_capture = capture_info.prong_index };
                        const capture_src = raw_capture_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), switch_info.src_node, .first);

                        const msg = try sema.errMsg(block, capture_src, "capture group with incompatible types", .{});
                        errdefer msg.destroy(sema.gpa);

                        const raw_first_item_src = Module.SwitchProngSrc{ .multi = .{ .prong = capture_info.prong_index, .item = 0 } };
                        const first_item_src = raw_first_item_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), switch_info.src_node, .first);
                        const raw_item_src = Module.SwitchProngSrc{ .multi = .{ .prong = capture_info.prong_index, .item = 1 + @intCast(u32, i) } };
                        const item_src = raw_item_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), switch_info.src_node, .first);
                        try sema.errNote(block, first_item_src, msg, "type '{}' here", .{first_field.ty.fmt(sema.mod)});
                        try sema.errNote(block, item_src, msg, "type '{}' here", .{field.ty.fmt(sema.mod)});
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            }

            if (is_ref) {
                const field_ty_ptr = try Type.ptr(sema.arena, sema.mod, .{
                    .pointee_type = first_field.ty,
                    .@"addrspace" = .generic,
                    .mutable = operand_ptr_ty.ptrIsMutable(),
                });

                if (try sema.resolveDefinedValue(block, operand_src, operand_ptr)) |op_ptr_val| {
                    return sema.addConstant(
                        field_ty_ptr,
                        try Value.Tag.field_ptr.create(sema.arena, .{
                            .container_ptr = op_ptr_val,
                            .container_ty = operand_ty,
                            .field_index = first_field_index,
                        }),
                    );
                }
                try sema.requireRuntimeBlock(block, operand_src, null);
                return block.addStructFieldPtr(operand_ptr, first_field_index, field_ty_ptr);
            }

            if (try sema.resolveDefinedValue(block, operand_src, operand)) |operand_val| {
                return sema.addConstant(
                    first_field.ty,
                    operand_val.castTag(.@"union").?.data.val,
                );
            }
            try sema.requireRuntimeBlock(block, operand_src, null);
            return block.addStructFieldVal(operand, first_field_index, first_field.ty);
        },
        .ErrorSet => {
            if (is_multi) {
                var names: Module.ErrorSet.NameMap = .{};
                try names.ensureUnusedCapacity(sema.arena, items.len);
                for (items) |item| {
                    const item_ref = try sema.resolveInst(item);
                    // Previous switch validation ensured this will succeed
                    const item_val = sema.resolveConstValue(block, .unneeded, item_ref, "") catch unreachable;
                    names.putAssumeCapacityNoClobber(
                        item_val.getError().?,
                        {},
                    );
                }
                // names must be sorted
                Module.ErrorSet.sortNames(&names);
                const else_error_ty = try Type.Tag.error_set_merged.create(sema.arena, names);

                return sema.bitCast(block, else_error_ty, operand, operand_src, null);
            } else {
                const item_ref = try sema.resolveInst(items[0]);
                // Previous switch validation ensured this will succeed
                const item_val = sema.resolveConstValue(block, .unneeded, item_ref, "") catch unreachable;

                const item_ty = try Type.Tag.error_set_single.create(sema.arena, item_val.getError().?);
                return sema.bitCast(block, item_ty, operand, operand_src, null);
            }
        },
        else => {
            // In this case the capture value is just the passed-through value of the
            // switch condition.
            if (is_ref) {
                return operand_ptr;
            } else {
                return operand;
            }
        },
    }
}

fn zirSwitchCaptureTag(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const zir_datas = sema.code.instructions.items(.data);
    const inst_data = zir_datas[inst].un_tok;
    const src = inst_data.src();

    const switch_tag = sema.code.instructions.items(.tag)[Zir.refToIndex(inst_data.operand).?];
    const is_ref = switch_tag == .switch_cond_ref;
    const cond_data = zir_datas[Zir.refToIndex(inst_data.operand).?].un_node;
    const operand_ptr = try sema.resolveInst(cond_data.operand);
    const operand_ptr_ty = sema.typeOf(operand_ptr);
    const operand_ty = if (is_ref) operand_ptr_ty.childType() else operand_ptr_ty;

    if (operand_ty.zigTypeTag() != .Union) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "cannot capture tag of non-union type '{}'", .{
                operand_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.addDeclaredHereNote(msg, operand_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    return block.inline_case_capture;
}

fn zirSwitchCond(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = inst_data.src_node };
    const operand_ptr = try sema.resolveInst(inst_data.operand);
    const operand = if (is_ref)
        try sema.analyzeLoad(block, src, operand_ptr, operand_src)
    else
        operand_ptr;
    const operand_ty = sema.typeOf(operand);

    switch (operand_ty.zigTypeTag()) {
        .Type,
        .Void,
        .Bool,
        .Int,
        .Float,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .Pointer,
        .Fn,
        .ErrorSet,
        .Enum,
        => {
            if (operand_ty.isSlice()) {
                return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(sema.mod)});
            }
            if ((try sema.typeHasOnePossibleValue(operand_ty))) |opv| {
                return sema.addConstant(operand_ty, opv);
            }
            return operand;
        },

        .Union => {
            const union_ty = try sema.resolveTypeFields(operand_ty);
            const enum_ty = union_ty.unionTagType() orelse {
                const msg = msg: {
                    const msg = try sema.errMsg(block, src, "switch on union with no attached enum", .{});
                    errdefer msg.destroy(sema.gpa);
                    if (union_ty.declSrcLocOrNull(sema.mod)) |union_src| {
                        try sema.mod.errNoteNonLazy(union_src, msg, "consider 'union(enum)' here", .{});
                    }
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            };
            return sema.unionToTag(block, enum_ty, operand, src);
        },

        .ErrorUnion,
        .NoReturn,
        .Array,
        .Struct,
        .Undefined,
        .Null,
        .Optional,
        .Opaque,
        .Vector,
        .Frame,
        .AnyFrame,
        => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(sema.mod)}),
    }
}

const SwitchErrorSet = std.StringHashMap(Module.SwitchProngSrc);

fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const gpa = sema.gpa;
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const src_node_offset = inst_data.src_node;
    const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = src_node_offset };
    const special_prong_src: LazySrcLoc = .{ .node_offset_switch_special_prong = src_node_offset };
    const extra = sema.code.extraData(Zir.Inst.SwitchBlock, inst_data.payload_index);

    const operand = try sema.resolveInst(extra.data.operand);
    // AstGen guarantees that the instruction immediately following
    // switch_cond(_ref) is a dbg_stmt
    const cond_dbg_node_index = Zir.refToIndex(extra.data.operand).? + 1;

    var header_extra_index: usize = extra.end;

    const scalar_cases_len = extra.data.bits.scalar_cases_len;
    const multi_cases_len = if (extra.data.bits.has_multi_cases) blk: {
        const multi_cases_len = sema.code.extra[header_extra_index];
        header_extra_index += 1;
        break :blk multi_cases_len;
    } else 0;

    const special_prong = extra.data.bits.specialProng();
    const special: struct { body: []const Zir.Inst.Index, end: usize, is_inline: bool } = switch (special_prong) {
        .none => .{ .body = &.{}, .end = header_extra_index, .is_inline = false },
        .under, .@"else" => blk: {
            const body_len = @truncate(u31, sema.code.extra[header_extra_index]);
            const extra_body_start = header_extra_index + 1;
            break :blk .{
                .body = sema.code.extra[extra_body_start..][0..body_len],
                .end = extra_body_start + body_len,
                .is_inline = sema.code.extra[header_extra_index] >> 31 != 0,
            };
        },
    };

    const maybe_union_ty = blk: {
        const zir_tags = sema.code.instructions.items(.tag);
        const zir_data = sema.code.instructions.items(.data);
        const cond_index = Zir.refToIndex(extra.data.operand).?;
        const raw_operand = sema.resolveInst(zir_data[cond_index].un_node.operand) catch unreachable;
        const target_ty = sema.typeOf(raw_operand);
        break :blk if (zir_tags[cond_index] == .switch_cond_ref) target_ty.elemType() else target_ty;
    };
    const union_originally = maybe_union_ty.zigTypeTag() == .Union;

    // Duplicate checking variables later also used for `inline else`.
    var seen_enum_fields: []?Module.SwitchProngSrc = &.{};
    var seen_errors = SwitchErrorSet.init(gpa);
    var range_set = RangeSet.init(gpa, sema.mod);
    var true_count: u8 = 0;
    var false_count: u8 = 0;

    defer {
        range_set.deinit();
        gpa.free(seen_enum_fields);
        seen_errors.deinit();
    }

    var empty_enum = false;

    const operand_ty = sema.typeOf(operand);
    const err_set = operand_ty.zigTypeTag() == .ErrorSet;

    var else_error_ty: ?Type = null;

    // Validate usage of '_' prongs.
    if (special_prong == .under and (!operand_ty.isNonexhaustiveEnum() or union_originally)) {
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                src,
                "'_' prong only allowed when switching on non-exhaustive enums",
                .{},
            );
            errdefer msg.destroy(gpa);
            try sema.errNote(
                block,
                special_prong_src,
                msg,
                "'_' prong here",
                .{},
            );
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const target = sema.mod.getTarget();

    // Validate for duplicate items, missing else prong, and invalid range.
    switch (operand_ty.zigTypeTag()) {
        .Union => unreachable, // handled in zirSwitchCond
        .Enum => {
            seen_enum_fields = try gpa.alloc(?Module.SwitchProngSrc, operand_ty.enumFieldCount());
            empty_enum = seen_enum_fields.len == 0 and !operand_ty.isNonexhaustiveEnum();
            mem.set(?Module.SwitchProngSrc, seen_enum_fields, null);
            // `range_set` is used for non-exhaustive enum values that do not correspond to any tags.

            var extra_index: usize = special.end;
            {
                var scalar_i: u32 = 0;
                while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
                    const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    extra_index += body_len;

                    try sema.validateSwitchItemEnum(
                        block,
                        seen_enum_fields,
                        &range_set,
                        item_ref,
                        src_node_offset,
                        .{ .scalar = scalar_i },
                    );
                }
            }
            {
                var multi_i: u32 = 0;
                while (multi_i < multi_cases_len) : (multi_i += 1) {
                    const items_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const ranges_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const items = sema.code.refSlice(extra_index, items_len);
                    extra_index += items_len + body_len;

                    for (items, 0..) |item_ref, item_i| {
                        try sema.validateSwitchItemEnum(
                            block,
                            seen_enum_fields,
                            &range_set,
                            item_ref,
                            src_node_offset,
                            .{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
                        );
                    }

                    try sema.validateSwitchNoRange(block, ranges_len, operand_ty, src_node_offset);
                }
            }
            const all_tags_handled = for (seen_enum_fields) |seen_src| {
                if (seen_src == null) break false;
            } else true;

            if (special_prong == .@"else") {
                if (all_tags_handled and !operand_ty.isNonexhaustiveEnum()) return sema.fail(
                    block,
                    special_prong_src,
                    "unreachable else prong; all cases already handled",
                    .{},
                );
            } else if (!all_tags_handled) {
                const msg = msg: {
                    const msg = try sema.errMsg(
                        block,
                        src,
                        "switch must handle all possibilities",
                        .{},
                    );
                    errdefer msg.destroy(sema.gpa);
                    for (seen_enum_fields, 0..) |seen_src, i| {
                        if (seen_src != null) continue;

                        const field_name = operand_ty.enumFieldName(i);
                        try sema.addFieldErrNote(
                            operand_ty,
                            i,
                            msg,
                            "unhandled enumeration value: '{s}'",
                            .{field_name},
                        );
                    }
                    try sema.mod.errNoteNonLazy(
                        operand_ty.declSrcLoc(sema.mod),
                        msg,
                        "enum '{}' declared here",
                        .{operand_ty.fmt(sema.mod)},
                    );
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            } else if (special_prong == .none and operand_ty.isNonexhaustiveEnum() and !union_originally) {
                return sema.fail(
                    block,
                    src,
                    "switch on non-exhaustive enum must include 'else' or '_' prong",
                    .{},
                );
            }
        },
        .ErrorSet => {
            var extra_index: usize = special.end;
            {
                var scalar_i: u32 = 0;
                while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
                    const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    extra_index += body_len;

                    try sema.validateSwitchItemError(
                        block,
                        &seen_errors,
                        item_ref,
                        src_node_offset,
                        .{ .scalar = scalar_i },
                    );
                }
            }
            {
                var multi_i: u32 = 0;
                while (multi_i < multi_cases_len) : (multi_i += 1) {
                    const items_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const ranges_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const items = sema.code.refSlice(extra_index, items_len);
                    extra_index += items_len + body_len;

                    for (items, 0..) |item_ref, item_i| {
                        try sema.validateSwitchItemError(
                            block,
                            &seen_errors,
                            item_ref,
                            src_node_offset,
                            .{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
                        );
                    }

                    try sema.validateSwitchNoRange(block, ranges_len, operand_ty, src_node_offset);
                }
            }

            try sema.resolveInferredErrorSetTy(block, src, operand_ty);

            if (operand_ty.isAnyError()) {
                if (special_prong != .@"else") {
                    return sema.fail(
                        block,
                        src,
                        "else prong required when switching on type 'anyerror'",
                        .{},
                    );
                }
                else_error_ty = Type.anyerror;
            } else else_validation: {
                var maybe_msg: ?*Module.ErrorMsg = null;
                errdefer if (maybe_msg) |msg| msg.destroy(sema.gpa);

                for (operand_ty.errorSetNames()) |error_name| {
                    if (!seen_errors.contains(error_name) and special_prong != .@"else") {
                        const msg = maybe_msg orelse blk: {
                            maybe_msg = try sema.errMsg(
                                block,
                                src,
                                "switch must handle all possibilities",
                                .{},
                            );
                            break :blk maybe_msg.?;
                        };

                        try sema.errNote(
                            block,
                            src,
                            msg,
                            "unhandled error value: 'error.{s}'",
                            .{error_name},
                        );
                    }
                }

                if (maybe_msg) |msg| {
                    maybe_msg = null;
                    try sema.addDeclaredHereNote(msg, operand_ty);
                    return sema.failWithOwnedErrorMsg(msg);
                }

                if (special_prong == .@"else" and seen_errors.count() == operand_ty.errorSetNames().len) {
                    // In order to enable common patterns for generic code allow simple else bodies
                    // else => unreachable,
                    // else => return,
                    // else => |e| return e,
                    // even if all the possible errors were already handled.
                    const tags = sema.code.instructions.items(.tag);
                    for (special.body) |else_inst| switch (tags[else_inst]) {
                        .dbg_block_begin,
                        .dbg_block_end,
                        .dbg_stmt,
                        .dbg_var_val,
                        .switch_capture,
                        .ret_type,
                        .as_node,
                        .ret_node,
                        .@"unreachable",
                        .@"defer",
                        .defer_err_code,
                        .err_union_code,
                        .ret_err_value_code,
                        .restore_err_ret_index,
                        .is_non_err,
                        .ret_is_non_err,
                        .condbr,
                        => {},
                        else => break,
                    } else break :else_validation;

                    return sema.fail(
                        block,
                        special_prong_src,
                        "unreachable else prong; all cases already handled",
                        .{},
                    );
                }

                const error_names = operand_ty.errorSetNames();
                var names: Module.ErrorSet.NameMap = .{};
                try names.ensureUnusedCapacity(sema.arena, error_names.len);
                for (error_names) |error_name| {
                    if (seen_errors.contains(error_name)) continue;

                    names.putAssumeCapacityNoClobber(error_name, {});
                }

                // names must be sorted
                Module.ErrorSet.sortNames(&names);
                else_error_ty = try Type.Tag.error_set_merged.create(sema.arena, names);
            }
        },
        .Int, .ComptimeInt => {
            var extra_index: usize = special.end;
            {
                var scalar_i: u32 = 0;
                while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
                    const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    extra_index += body_len;

                    try sema.validateSwitchItem(
                        block,
                        &range_set,
                        item_ref,
                        operand_ty,
                        src_node_offset,
                        .{ .scalar = scalar_i },
                    );
                }
            }
            {
                var multi_i: u32 = 0;
                while (multi_i < multi_cases_len) : (multi_i += 1) {
                    const items_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const ranges_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const items = sema.code.refSlice(extra_index, items_len);
                    extra_index += items_len;

                    for (items, 0..) |item_ref, item_i| {
                        try sema.validateSwitchItem(
                            block,
                            &range_set,
                            item_ref,
                            operand_ty,
                            src_node_offset,
                            .{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
                        );
                    }

                    var range_i: u32 = 0;
                    while (range_i < ranges_len) : (range_i += 1) {
                        const item_first = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                        extra_index += 1;
                        const item_last = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                        extra_index += 1;

                        try sema.validateSwitchRange(
                            block,
                            &range_set,
                            item_first,
                            item_last,
                            operand_ty,
                            src_node_offset,
                            .{ .range = .{ .prong = multi_i, .item = range_i } },
                        );
                    }

                    extra_index += body_len;
                }
            }

            check_range: {
                if (operand_ty.zigTypeTag() == .Int) {
                    var arena = std.heap.ArenaAllocator.init(gpa);
                    defer arena.deinit();

                    const min_int = try operand_ty.minInt(arena.allocator(), target);
                    const max_int = try operand_ty.maxInt(arena.allocator(), target);
                    if (try range_set.spans(min_int, max_int, operand_ty)) {
                        if (special_prong == .@"else") {
                            return sema.fail(
                                block,
                                special_prong_src,
                                "unreachable else prong; all cases already handled",
                                .{},
                            );
                        }
                        break :check_range;
                    }
                }
                if (special_prong != .@"else") {
                    return sema.fail(
                        block,
                        src,
                        "switch must handle all possibilities",
                        .{},
                    );
                }
            }
        },
        .Bool => {
            var extra_index: usize = special.end;
            {
                var scalar_i: u32 = 0;
                while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
                    const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    extra_index += body_len;

                    try sema.validateSwitchItemBool(
                        block,
                        &true_count,
                        &false_count,
                        item_ref,
                        src_node_offset,
                        .{ .scalar = scalar_i },
                    );
                }
            }
            {
                var multi_i: u32 = 0;
                while (multi_i < multi_cases_len) : (multi_i += 1) {
                    const items_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const ranges_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const items = sema.code.refSlice(extra_index, items_len);
                    extra_index += items_len + body_len;

                    for (items, 0..) |item_ref, item_i| {
                        try sema.validateSwitchItemBool(
                            block,
                            &true_count,
                            &false_count,
                            item_ref,
                            src_node_offset,
                            .{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
                        );
                    }

                    try sema.validateSwitchNoRange(block, ranges_len, operand_ty, src_node_offset);
                }
            }
            switch (special_prong) {
                .@"else" => {
                    if (true_count + false_count == 2) {
                        return sema.fail(
                            block,
                            special_prong_src,
                            "unreachable else prong; all cases already handled",
                            .{},
                        );
                    }
                },
                .under, .none => {
                    if (true_count + false_count < 2) {
                        return sema.fail(
                            block,
                            src,
                            "switch must handle all possibilities",
                            .{},
                        );
                    }
                },
            }
        },
        .EnumLiteral, .Void, .Fn, .Pointer, .Type => {
            if (special_prong != .@"else") {
                return sema.fail(
                    block,
                    src,
                    "else prong required when switching on type '{}'",
                    .{operand_ty.fmt(sema.mod)},
                );
            }

            var seen_values = ValueSrcMap.initContext(gpa, .{
                .ty = operand_ty,
                .mod = sema.mod,
            });
            defer seen_values.deinit();

            var extra_index: usize = special.end;
            {
                var scalar_i: u32 = 0;
                while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
                    const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    extra_index += body_len;

                    try sema.validateSwitchItemSparse(
                        block,
                        &seen_values,
                        item_ref,
                        src_node_offset,
                        .{ .scalar = scalar_i },
                    );
                }
            }
            {
                var multi_i: u32 = 0;
                while (multi_i < multi_cases_len) : (multi_i += 1) {
                    const items_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const ranges_len = sema.code.extra[extra_index];
                    extra_index += 1;
                    const body_len = @truncate(u31, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const items = sema.code.refSlice(extra_index, items_len);
                    extra_index += items_len + body_len;

                    for (items, 0..) |item_ref, item_i| {
                        try sema.validateSwitchItemSparse(
                            block,
                            &seen_values,
                            item_ref,
                            src_node_offset,
                            .{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } },
                        );
                    }

                    try sema.validateSwitchNoRange(block, ranges_len, operand_ty, src_node_offset);
                }
            }
        },

        .ErrorUnion,
        .NoReturn,
        .Array,
        .Struct,
        .Undefined,
        .Null,
        .Optional,
        .Opaque,
        .Vector,
        .Frame,
        .AnyFrame,
        .ComptimeFloat,
        .Float,
        => return sema.fail(block, operand_src, "invalid switch operand type '{}'", .{
            operand_ty.fmt(sema.mod),
        }),
    }

    const block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
    try sema.air_instructions.append(gpa, .{
        .tag = .block,
        .data = undefined,
    });
    var label: Block.Label = .{
        .zir_block = inst,
        .merges = .{
            .results = .{},
            .br_list = .{},
            .block_inst = block_inst,
        },
    };

    var child_block: Block = .{
        .parent = block,
        .sema = sema,
        .src_decl = block.src_decl,
        .namespace = block.namespace,
        .wip_capture_scope = block.wip_capture_scope,
        .instructions = .{},
        .label = &label,
        .inlining = block.inlining,
        .is_comptime = block.is_comptime,
        .comptime_reason = block.comptime_reason,
        .is_typeof = block.is_typeof,
        .switch_else_err_ty = else_error_ty,
        .c_import_buf = block.c_import_buf,
        .runtime_cond = block.runtime_cond,
        .runtime_loop = block.runtime_loop,
        .runtime_index = block.runtime_index,
        .error_return_trace_index = block.error_return_trace_index,
    };
    const merges = &child_block.label.?.merges;
    defer child_block.instructions.deinit(gpa);
    defer merges.results.deinit(gpa);
    defer merges.br_list.deinit(gpa);

    if (try sema.resolveDefinedValue(&child_block, src, operand)) |operand_val| {
        var extra_index: usize = special.end;
        {
            var scalar_i: usize = 0;
            while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
                const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                extra_index += 1;
                const body_len = @truncate(u31, sema.code.extra[extra_index]);
                const is_inline = sema.code.extra[extra_index] >> 31 != 0;
                extra_index += 1;
                const body = sema.code.extra[extra_index..][0..body_len];
                extra_index += body_len;

                const item = try sema.resolveInst(item_ref);
                // Validation above ensured these will succeed.
                const item_val = sema.resolveConstValue(&child_block, .unneeded, item, "") catch unreachable;
                if (operand_val.eql(item_val, operand_ty, sema.mod)) {
                    if (is_inline) child_block.inline_case_capture = operand;

                    if (err_set) try sema.maybeErrorUnwrapComptime(&child_block, body, operand);
                    return sema.resolveBlockBody(block, src, &child_block, body, inst, merges);
                }
            }
        }
        {
            var multi_i: usize = 0;
            while (multi_i < multi_cases_len) : (multi_i += 1) {
                const items_len = sema.code.extra[extra_index];
                extra_index += 1;
                const ranges_len = sema.code.extra[extra_index];
                extra_index += 1;
                const body_len = @truncate(u31, sema.code.extra[extra_index]);
                const is_inline = sema.code.extra[extra_index] >> 31 != 0;
                extra_index += 1;
                const items = sema.code.refSlice(extra_index, items_len);
                extra_index += items_len;
                const body = sema.code.extra[extra_index + 2 * ranges_len ..][0..body_len];

                for (items) |item_ref| {
                    const item = try sema.resolveInst(item_ref);
                    // Validation above ensured these will succeed.
                    const item_val = sema.resolveConstValue(&child_block, .unneeded, item, "") catch unreachable;
                    if (operand_val.eql(item_val, operand_ty, sema.mod)) {
                        if (is_inline) child_block.inline_case_capture = operand;

                        if (err_set) try sema.maybeErrorUnwrapComptime(&child_block, body, operand);
                        return sema.resolveBlockBody(block, src, &child_block, body, inst, merges);
                    }
                }

                var range_i: usize = 0;
                while (range_i < ranges_len) : (range_i += 1) {
                    const item_first = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;
                    const item_last = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                    extra_index += 1;

                    // Validation above ensured these will succeed.
                    const first_tv = sema.resolveInstConst(&child_block, .unneeded, item_first, "") catch unreachable;
                    const last_tv = sema.resolveInstConst(&child_block, .unneeded, item_last, "") catch unreachable;
                    if ((try sema.compareAll(operand_val, .gte, first_tv.val, operand_ty)) and
                        (try sema.compareAll(operand_val, .lte, last_tv.val, operand_ty)))
                    {
                        if (is_inline) child_block.inline_case_capture = operand;
                        if (err_set) try sema.maybeErrorUnwrapComptime(&child_block, body, operand);
                        return sema.resolveBlockBody(block, src, &child_block, body, inst, merges);
                    }
                }

                extra_index += body_len;
            }
        }
        if (err_set) try sema.maybeErrorUnwrapComptime(&child_block, special.body, operand);
        if (special.is_inline) child_block.inline_case_capture = operand;
        if (empty_enum) {
            return Air.Inst.Ref.void_value;
        }
        return sema.resolveBlockBody(block, src, &child_block, special.body, inst, merges);
    }

    if (scalar_cases_len + multi_cases_len == 0 and !special.is_inline) {
        if (empty_enum) {
            return Air.Inst.Ref.void_value;
        }
        if (special_prong == .none) {
            return sema.fail(block, src, "switch must handle all possibilities", .{});
        }
        if (err_set and try sema.maybeErrorUnwrap(block, special.body, operand)) {
            return Air.Inst.Ref.unreachable_value;
        }
        if (sema.mod.backendSupportsFeature(.is_named_enum_value) and block.wantSafety() and operand_ty.zigTypeTag() == .Enum and
            (!operand_ty.isNonexhaustiveEnum() or union_originally))
        {
            try sema.zirDbgStmt(block, cond_dbg_node_index);
            const ok = try block.addUnOp(.is_named_enum_value, operand);
            try sema.addSafetyCheck(block, ok, .corrupt_switch);
        }
        return sema.resolveBlockBody(block, src, &child_block, special.body, inst, merges);
    }

    if (child_block.is_comptime) {
        _ = sema.resolveConstValue(&child_block, operand_src, operand, "condition in comptime switch must be comptime-known") catch |err| {
            if (err == error.AnalysisFail and child_block.comptime_reason != null) try child_block.comptime_reason.?.explain(sema, sema.err);
            return err;
        };
        unreachable;
    }

    const estimated_cases_extra = (scalar_cases_len + multi_cases_len) *
        @typeInfo(Air.SwitchBr.Case).Struct.fields.len + 2;
    var cases_extra = try std.ArrayListUnmanaged(u32).initCapacity(gpa, estimated_cases_extra);
    defer cases_extra.deinit(gpa);

    var case_block = child_block.makeSubBlock();
    case_block.runtime_loop = null;
    case_block.runtime_cond = operand_src;
    case_block.runtime_index.increment();
    defer case_block.instructions.deinit(gpa);

    var extra_index: usize = special.end;

    var scalar_i: usize = 0;
    while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
        const item_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const body_len = @truncate(u31, sema.code.extra[extra_index]);
        const is_inline = sema.code.extra[extra_index] >> 31 != 0;
        extra_index += 1;
        const body = sema.code.extra[extra_index..][0..body_len];
        extra_index += body_len;

        var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, child_block.wip_capture_scope);
        defer wip_captures.deinit();

        case_block.instructions.shrinkRetainingCapacity(0);
        case_block.wip_capture_scope = wip_captures.scope;
        case_block.inline_case_capture = .none;

        const item = try sema.resolveInst(item_ref);
        if (is_inline) case_block.inline_case_capture = item;
        // `item` is already guaranteed to be constant known.

        const analyze_body = if (union_originally) blk: {
            const item_val = sema.resolveConstValue(block, .unneeded, item, "") catch unreachable;
            const field_ty = maybe_union_ty.unionFieldType(item_val, sema.mod);
            break :blk field_ty.zigTypeTag() != .NoReturn;
        } else true;

        if (err_set and try sema.maybeErrorUnwrap(&case_block, body, operand)) {
            // nothing to do here
        } else if (analyze_body) {
            try sema.analyzeBodyRuntimeBreak(&case_block, body);
        } else {
            _ = try case_block.addNoOp(.unreach);
        }

        try wip_captures.finalize();

        try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
        cases_extra.appendAssumeCapacity(1); // items_len
        cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
        cases_extra.appendAssumeCapacity(@enumToInt(item));
        cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
    }

    var is_first = true;
    var prev_cond_br: Air.Inst.Index = undefined;
    var first_else_body: []const Air.Inst.Index = &.{};
    defer gpa.free(first_else_body);
    var prev_then_body: []const Air.Inst.Index = &.{};
    defer gpa.free(prev_then_body);

    var cases_len = scalar_cases_len;
    var multi_i: u32 = 0;
    while (multi_i < multi_cases_len) : (multi_i += 1) {
        const items_len = sema.code.extra[extra_index];
        extra_index += 1;
        const ranges_len = sema.code.extra[extra_index];
        extra_index += 1;
        const body_len = @truncate(u31, sema.code.extra[extra_index]);
        const is_inline = sema.code.extra[extra_index] >> 31 != 0;
        extra_index += 1;
        const items = sema.code.refSlice(extra_index, items_len);
        extra_index += items_len;

        case_block.instructions.shrinkRetainingCapacity(0);
        case_block.wip_capture_scope = child_block.wip_capture_scope;
        case_block.inline_case_capture = .none;

        // Generate all possible cases as scalar prongs.
        if (is_inline) {
            const body_start = extra_index + 2 * ranges_len;
            const body = sema.code.extra[body_start..][0..body_len];
            var emit_bb = false;

            var range_i: u32 = 0;
            while (range_i < ranges_len) : (range_i += 1) {
                const first_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                extra_index += 1;
                const last_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                extra_index += 1;

                const item_first_ref = try sema.resolveInst(first_ref);
                var item = sema.resolveConstValue(block, .unneeded, item_first_ref, undefined) catch unreachable;
                const item_last_ref = try sema.resolveInst(last_ref);
                const item_last = sema.resolveConstValue(block, .unneeded, item_last_ref, undefined) catch unreachable;

                while (item.compareAll(.lte, item_last, operand_ty, sema.mod)) : ({
                    // Previous validation has resolved any possible lazy values.
                    item = try sema.intAddScalar(item, Value.one);
                }) {
                    cases_len += 1;

                    const item_ref = try sema.addConstant(operand_ty, item);
                    case_block.inline_case_capture = item_ref;

                    case_block.instructions.shrinkRetainingCapacity(0);
                    case_block.wip_capture_scope = child_block.wip_capture_scope;

                    if (emit_bb) sema.emitBackwardBranch(block, .unneeded) catch |err| switch (err) {
                        error.NeededSourceLocation => {
                            const case_src = Module.SwitchProngSrc{ .range = .{ .prong = multi_i, .item = range_i } };
                            const decl = sema.mod.declPtr(case_block.src_decl);
                            try sema.emitBackwardBranch(block, case_src.resolve(sema.gpa, decl, src_node_offset, .none));
                            unreachable;
                        },
                        else => return err,
                    };
                    emit_bb = true;

                    try sema.analyzeBodyRuntimeBreak(&case_block, body);

                    try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                    cases_extra.appendAssumeCapacity(1); // items_len
                    cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                    cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                    cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
                }
            }

            for (items, 0..) |item_ref, item_i| {
                cases_len += 1;

                const item = try sema.resolveInst(item_ref);
                case_block.inline_case_capture = item;

                case_block.instructions.shrinkRetainingCapacity(0);
                case_block.wip_capture_scope = child_block.wip_capture_scope;

                const analyze_body = if (union_originally) blk: {
                    const item_val = sema.resolveConstValue(block, .unneeded, item, undefined) catch unreachable;
                    const field_ty = maybe_union_ty.unionFieldType(item_val, sema.mod);
                    break :blk field_ty.zigTypeTag() != .NoReturn;
                } else true;

                if (emit_bb) sema.emitBackwardBranch(block, .unneeded) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const case_src = Module.SwitchProngSrc{ .multi = .{ .prong = multi_i, .item = @intCast(u32, item_i) } };
                        const decl = sema.mod.declPtr(case_block.src_decl);
                        try sema.emitBackwardBranch(block, case_src.resolve(sema.gpa, decl, src_node_offset, .none));
                        unreachable;
                    },
                    else => return err,
                };
                emit_bb = true;

                if (analyze_body) {
                    try sema.analyzeBodyRuntimeBreak(&case_block, body);
                } else {
                    _ = try case_block.addNoOp(.unreach);
                }

                try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                cases_extra.appendAssumeCapacity(1); // items_len
                cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
            }

            extra_index += body_len;
            continue;
        }

        var any_ok: Air.Inst.Ref = .none;

        // If there are any ranges, we have to put all the items into the
        // else prong. Otherwise, we can take advantage of multiple items
        // mapping to the same body.
        if (ranges_len == 0) {
            cases_len += 1;

            const analyze_body = if (union_originally)
                for (items) |item_ref| {
                    const item = try sema.resolveInst(item_ref);
                    const item_val = sema.resolveConstValue(block, .unneeded, item, "") catch unreachable;
                    const field_ty = maybe_union_ty.unionFieldType(item_val, sema.mod);
                    if (field_ty.zigTypeTag() != .NoReturn) break true;
                } else false
            else
                true;

            const body = sema.code.extra[extra_index..][0..body_len];
            extra_index += body_len;
            if (err_set and try sema.maybeErrorUnwrap(&case_block, body, operand)) {
                // nothing to do here
            } else if (analyze_body) {
                try sema.analyzeBodyRuntimeBreak(&case_block, body);
            } else {
                _ = try case_block.addNoOp(.unreach);
            }

            try cases_extra.ensureUnusedCapacity(gpa, 2 + items.len +
                case_block.instructions.items.len);

            cases_extra.appendAssumeCapacity(@intCast(u32, items.len));
            cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));

            for (items) |item_ref| {
                const item = try sema.resolveInst(item_ref);
                cases_extra.appendAssumeCapacity(@enumToInt(item));
            }

            cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
        } else {
            for (items) |item_ref| {
                const item = try sema.resolveInst(item_ref);
                const cmp_ok = try case_block.addBinOp(if (case_block.float_mode == .Optimized) .cmp_eq_optimized else .cmp_eq, operand, item);
                if (any_ok != .none) {
                    any_ok = try case_block.addBinOp(.bool_or, any_ok, cmp_ok);
                } else {
                    any_ok = cmp_ok;
                }
            }

            var range_i: usize = 0;
            while (range_i < ranges_len) : (range_i += 1) {
                const first_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                extra_index += 1;
                const last_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
                extra_index += 1;

                const item_first = try sema.resolveInst(first_ref);
                const item_last = try sema.resolveInst(last_ref);

                // operand >= first and operand <= last
                const range_first_ok = try case_block.addBinOp(
                    if (case_block.float_mode == .Optimized) .cmp_gte_optimized else .cmp_gte,
                    operand,
                    item_first,
                );
                const range_last_ok = try case_block.addBinOp(
                    if (case_block.float_mode == .Optimized) .cmp_lte_optimized else .cmp_lte,
                    operand,
                    item_last,
                );
                const range_ok = try case_block.addBinOp(
                    .bool_and,
                    range_first_ok,
                    range_last_ok,
                );
                if (any_ok != .none) {
                    any_ok = try case_block.addBinOp(.bool_or, any_ok, range_ok);
                } else {
                    any_ok = range_ok;
                }
            }

            const new_cond_br = try case_block.addInstAsIndex(.{ .tag = .cond_br, .data = .{
                .pl_op = .{
                    .operand = any_ok,
                    .payload = undefined,
                },
            } });
            var cond_body = try case_block.instructions.toOwnedSlice(gpa);
            defer gpa.free(cond_body);

            var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, child_block.wip_capture_scope);
            defer wip_captures.deinit();

            case_block.instructions.shrinkRetainingCapacity(0);
            case_block.wip_capture_scope = wip_captures.scope;

            const body = sema.code.extra[extra_index..][0..body_len];
            extra_index += body_len;
            if (err_set and try sema.maybeErrorUnwrap(&case_block, body, operand)) {
                // nothing to do here
            } else {
                try sema.analyzeBodyRuntimeBreak(&case_block, body);
            }

            try wip_captures.finalize();

            if (is_first) {
                is_first = false;
                first_else_body = cond_body;
                cond_body = &.{};
            } else {
                try sema.air_extra.ensureUnusedCapacity(
                    gpa,
                    @typeInfo(Air.CondBr).Struct.fields.len + prev_then_body.len + cond_body.len,
                );

                sema.air_instructions.items(.data)[prev_cond_br].pl_op.payload =
                    sema.addExtraAssumeCapacity(Air.CondBr{
                    .then_body_len = @intCast(u32, prev_then_body.len),
                    .else_body_len = @intCast(u32, cond_body.len),
                });
                sema.air_extra.appendSliceAssumeCapacity(prev_then_body);
                sema.air_extra.appendSliceAssumeCapacity(cond_body);
            }
            gpa.free(prev_then_body);
            prev_then_body = try case_block.instructions.toOwnedSlice(gpa);
            prev_cond_br = new_cond_br;
        }
    }

    var final_else_body: []const Air.Inst.Index = &.{};
    if (special.body.len != 0 or !is_first or case_block.wantSafety()) {
        var emit_bb = false;
        if (special.is_inline) switch (operand_ty.zigTypeTag()) {
            .Enum => {
                if (operand_ty.isNonexhaustiveEnum() and !union_originally) {
                    return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
                        operand_ty.fmt(sema.mod),
                    });
                }
                for (seen_enum_fields, 0..) |f, i| {
                    if (f != null) continue;
                    cases_len += 1;

                    const item_val = try Value.Tag.enum_field_index.create(sema.arena, @intCast(u32, i));
                    const item_ref = try sema.addConstant(operand_ty, item_val);
                    case_block.inline_case_capture = item_ref;

                    case_block.instructions.shrinkRetainingCapacity(0);
                    case_block.wip_capture_scope = child_block.wip_capture_scope;

                    const analyze_body = if (union_originally) blk: {
                        const field_ty = maybe_union_ty.unionFieldType(item_val, sema.mod);
                        break :blk field_ty.zigTypeTag() != .NoReturn;
                    } else true;

                    if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
                    emit_bb = true;

                    if (analyze_body) {
                        try sema.analyzeBodyRuntimeBreak(&case_block, special.body);
                    } else {
                        _ = try case_block.addNoOp(.unreach);
                    }

                    try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                    cases_extra.appendAssumeCapacity(1); // items_len
                    cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                    cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                    cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
                }
            },
            .ErrorSet => {
                if (operand_ty.isAnyError()) {
                    return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
                        operand_ty.fmt(sema.mod),
                    });
                }
                for (operand_ty.errorSetNames()) |error_name| {
                    if (seen_errors.contains(error_name)) continue;
                    cases_len += 1;

                    const item_val = try Value.Tag.@"error".create(sema.arena, .{ .name = error_name });
                    const item_ref = try sema.addConstant(operand_ty, item_val);
                    case_block.inline_case_capture = item_ref;

                    case_block.instructions.shrinkRetainingCapacity(0);
                    case_block.wip_capture_scope = child_block.wip_capture_scope;

                    if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
                    emit_bb = true;

                    try sema.analyzeBodyRuntimeBreak(&case_block, special.body);

                    try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                    cases_extra.appendAssumeCapacity(1); // items_len
                    cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                    cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                    cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
                }
            },
            .Int => {
                var it = try RangeSetUnhandledIterator.init(sema, operand_ty, range_set);
                while (try it.next()) |cur| {
                    cases_len += 1;

                    const item_ref = try sema.addConstant(operand_ty, cur);
                    case_block.inline_case_capture = item_ref;

                    case_block.instructions.shrinkRetainingCapacity(0);
                    case_block.wip_capture_scope = child_block.wip_capture_scope;

                    if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
                    emit_bb = true;

                    try sema.analyzeBodyRuntimeBreak(&case_block, special.body);

                    try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                    cases_extra.appendAssumeCapacity(1); // items_len
                    cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                    cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                    cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
                }
            },
            .Bool => {
                if (true_count == 0) {
                    cases_len += 1;
                    case_block.inline_case_capture = Air.Inst.Ref.bool_true;

                    case_block.instructions.shrinkRetainingCapacity(0);
                    case_block.wip_capture_scope = child_block.wip_capture_scope;

                    if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
                    emit_bb = true;

                    try sema.analyzeBodyRuntimeBreak(&case_block, special.body);

                    try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                    cases_extra.appendAssumeCapacity(1); // items_len
                    cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                    cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                    cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
                }
                if (false_count == 0) {
                    cases_len += 1;
                    case_block.inline_case_capture = Air.Inst.Ref.bool_false;

                    case_block.instructions.shrinkRetainingCapacity(0);
                    case_block.wip_capture_scope = child_block.wip_capture_scope;

                    if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
                    emit_bb = true;

                    try sema.analyzeBodyRuntimeBreak(&case_block, special.body);

                    try cases_extra.ensureUnusedCapacity(gpa, 3 + case_block.instructions.items.len);
                    cases_extra.appendAssumeCapacity(1); // items_len
                    cases_extra.appendAssumeCapacity(@intCast(u32, case_block.instructions.items.len));
                    cases_extra.appendAssumeCapacity(@enumToInt(case_block.inline_case_capture));
                    cases_extra.appendSliceAssumeCapacity(case_block.instructions.items);
                }
            },
            else => return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
                operand_ty.fmt(sema.mod),
            }),
        };

        var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, child_block.wip_capture_scope);
        defer wip_captures.deinit();

        case_block.instructions.shrinkRetainingCapacity(0);
        case_block.wip_capture_scope = wip_captures.scope;
        case_block.inline_case_capture = .none;

        if (sema.mod.backendSupportsFeature(.is_named_enum_value) and special.body.len != 0 and block.wantSafety() and
            operand_ty.zigTypeTag() == .Enum and (!operand_ty.isNonexhaustiveEnum() or union_originally))
        {
            try sema.zirDbgStmt(&case_block, cond_dbg_node_index);
            const ok = try case_block.addUnOp(.is_named_enum_value, operand);
            try sema.addSafetyCheck(&case_block, ok, .corrupt_switch);
        }

        const analyze_body = if (union_originally and !special.is_inline)
            for (seen_enum_fields, 0..) |seen_field, index| {
                if (seen_field != null) continue;
                const union_obj = maybe_union_ty.cast(Type.Payload.Union).?.data;
                const field_ty = union_obj.fields.values()[index].ty;
                if (field_ty.zigTypeTag() != .NoReturn) break true;
            } else false
        else
            true;
        if (special.body.len != 0 and err_set and
            try sema.maybeErrorUnwrap(&case_block, special.body, operand))
        {
            // nothing to do here
        } else if (special.body.len != 0 and analyze_body and !special.is_inline) {
            try sema.analyzeBodyRuntimeBreak(&case_block, special.body);
        } else {
            // We still need a terminator in this block, but we have proven
            // that it is unreachable.
            if (case_block.wantSafety()) {
                try sema.zirDbgStmt(&case_block, cond_dbg_node_index);
                try sema.safetyPanic(&case_block, .corrupt_switch);
            } else {
                _ = try case_block.addNoOp(.unreach);
            }
        }

        try wip_captures.finalize();

        if (is_first) {
            final_else_body = case_block.instructions.items;
        } else {
            try sema.air_extra.ensureUnusedCapacity(gpa, prev_then_body.len +
                @typeInfo(Air.CondBr).Struct.fields.len + case_block.instructions.items.len);

            sema.air_instructions.items(.data)[prev_cond_br].pl_op.payload =
                sema.addExtraAssumeCapacity(Air.CondBr{
                .then_body_len = @intCast(u32, prev_then_body.len),
                .else_body_len = @intCast(u32, case_block.instructions.items.len),
            });
            sema.air_extra.appendSliceAssumeCapacity(prev_then_body);
            sema.air_extra.appendSliceAssumeCapacity(case_block.instructions.items);
            final_else_body = first_else_body;
        }
    }

    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.SwitchBr).Struct.fields.len +
        cases_extra.items.len + final_else_body.len);

    _ = try child_block.addInst(.{ .tag = .switch_br, .data = .{ .pl_op = .{
        .operand = operand,
        .payload = sema.addExtraAssumeCapacity(Air.SwitchBr{
            .cases_len = @intCast(u32, cases_len),
            .else_body_len = @intCast(u32, final_else_body.len),
        }),
    } } });
    sema.air_extra.appendSliceAssumeCapacity(cases_extra.items);
    sema.air_extra.appendSliceAssumeCapacity(final_else_body);

    return sema.analyzeBlockBody(block, src, &child_block, merges);
}

const RangeSetUnhandledIterator = struct {
    sema: *Sema,
    ty: Type,
    cur: Value,
    max: Value,
    ranges: []const RangeSet.Range,
    range_i: usize = 0,
    first: bool = true,

    fn init(sema: *Sema, ty: Type, range_set: RangeSet) !RangeSetUnhandledIterator {
        const target = sema.mod.getTarget();
        const min = try ty.minInt(sema.arena, target);
        const max = try ty.maxInt(sema.arena, target);

        return RangeSetUnhandledIterator{
            .sema = sema,
            .ty = ty,
            .cur = min,
            .max = max,
            .ranges = range_set.ranges.items,
        };
    }

    fn next(it: *RangeSetUnhandledIterator) !?Value {
        while (it.range_i < it.ranges.len) : (it.range_i += 1) {
            if (!it.first) {
                it.cur = try it.sema.intAdd(it.cur, Value.one, it.ty);
            }
            it.first = false;
            if (it.cur.compareAll(.lt, it.ranges[it.range_i].first, it.ty, it.sema.mod)) {
                return it.cur;
            }
            it.cur = it.ranges[it.range_i].last;
        }
        if (!it.first) {
            it.cur = try it.sema.intAdd(it.cur, Value.one, it.ty);
        }
        it.first = false;
        if (it.cur.compareAll(.lte, it.max, it.ty, it.sema.mod)) {
            return it.cur;
        }
        return null;
    }
};

fn resolveSwitchItemVal(
    sema: *Sema,
    block: *Block,
    item_ref: Zir.Inst.Ref,
    switch_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
    range_expand: Module.SwitchProngSrc.RangeExpand,
) CompileError!TypedValue {
    const item = try sema.resolveInst(item_ref);
    const item_ty = sema.typeOf(item);
    // Constructing a LazySrcLoc is costly because we only have the switch AST node.
    // Only if we know for sure we need to report a compile error do we resolve the
    // full source locations.
    if (sema.resolveConstValue(block, .unneeded, item, "")) |val| {
        try sema.resolveLazyValue(val);
        return TypedValue{ .ty = item_ty, .val = val };
    } else |err| switch (err) {
        error.NeededSourceLocation => {
            const src = switch_prong_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), switch_node_offset, range_expand);
            _ = try sema.resolveConstValue(block, src, item, "switch prong values must be comptime-known");
            unreachable;
        },
        else => |e| return e,
    }
}

fn validateSwitchRange(
    sema: *Sema,
    block: *Block,
    range_set: *RangeSet,
    first_ref: Zir.Inst.Ref,
    last_ref: Zir.Inst.Ref,
    operand_ty: Type,
    src_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
) CompileError!void {
    const first_val = (try sema.resolveSwitchItemVal(block, first_ref, src_node_offset, switch_prong_src, .first)).val;
    const last_val = (try sema.resolveSwitchItemVal(block, last_ref, src_node_offset, switch_prong_src, .last)).val;
    if (first_val.compareAll(.gt, last_val, operand_ty, sema.mod)) {
        const src = switch_prong_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), src_node_offset, .first);
        return sema.fail(block, src, "range start value is greater than the end value", .{});
    }
    const maybe_prev_src = try range_set.add(first_val, last_val, operand_ty, switch_prong_src);
    return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}

fn validateSwitchItem(
    sema: *Sema,
    block: *Block,
    range_set: *RangeSet,
    item_ref: Zir.Inst.Ref,
    operand_ty: Type,
    src_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
) CompileError!void {
    const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
    const maybe_prev_src = try range_set.add(item_val, item_val, operand_ty, switch_prong_src);
    return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}

fn validateSwitchItemEnum(
    sema: *Sema,
    block: *Block,
    seen_fields: []?Module.SwitchProngSrc,
    range_set: *RangeSet,
    item_ref: Zir.Inst.Ref,
    src_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
) CompileError!void {
    const item_tv = try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none);
    const field_index = item_tv.ty.enumTagFieldIndex(item_tv.val, sema.mod) orelse {
        const maybe_prev_src = try range_set.add(item_tv.val, item_tv.val, item_tv.ty, switch_prong_src);
        return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
    };
    const maybe_prev_src = seen_fields[field_index];
    seen_fields[field_index] = switch_prong_src;
    return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}

fn validateSwitchItemError(
    sema: *Sema,
    block: *Block,
    seen_errors: *SwitchErrorSet,
    item_ref: Zir.Inst.Ref,
    src_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
) CompileError!void {
    const item_tv = try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none);
    // TODO: Do i need to typecheck here?
    const error_name = item_tv.val.castTag(.@"error").?.data.name;
    const maybe_prev_src = if (try seen_errors.fetchPut(error_name, switch_prong_src)) |prev|
        prev.value
    else
        null;
    return sema.validateSwitchDupe(block, maybe_prev_src, switch_prong_src, src_node_offset);
}

fn validateSwitchDupe(
    sema: *Sema,
    block: *Block,
    maybe_prev_src: ?Module.SwitchProngSrc,
    switch_prong_src: Module.SwitchProngSrc,
    src_node_offset: i32,
) CompileError!void {
    const prev_prong_src = maybe_prev_src orelse return;
    const gpa = sema.gpa;
    const block_src_decl = sema.mod.declPtr(block.src_decl);
    const src = switch_prong_src.resolve(gpa, block_src_decl, src_node_offset, .none);
    const prev_src = prev_prong_src.resolve(gpa, block_src_decl, src_node_offset, .none);
    const msg = msg: {
        const msg = try sema.errMsg(
            block,
            src,
            "duplicate switch value",
            .{},
        );
        errdefer msg.destroy(sema.gpa);
        try sema.errNote(
            block,
            prev_src,
            msg,
            "previous value here",
            .{},
        );
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn validateSwitchItemBool(
    sema: *Sema,
    block: *Block,
    true_count: *u8,
    false_count: *u8,
    item_ref: Zir.Inst.Ref,
    src_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
) CompileError!void {
    const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
    if (item_val.toBool()) {
        true_count.* += 1;
    } else {
        false_count.* += 1;
    }
    if (true_count.* + false_count.* > 2) {
        const block_src_decl = sema.mod.declPtr(block.src_decl);
        const src = switch_prong_src.resolve(sema.gpa, block_src_decl, src_node_offset, .none);
        return sema.fail(block, src, "duplicate switch value", .{});
    }
}

const ValueSrcMap = std.HashMap(Value, Module.SwitchProngSrc, Value.HashContext, std.hash_map.default_max_load_percentage);

fn validateSwitchItemSparse(
    sema: *Sema,
    block: *Block,
    seen_values: *ValueSrcMap,
    item_ref: Zir.Inst.Ref,
    src_node_offset: i32,
    switch_prong_src: Module.SwitchProngSrc,
) CompileError!void {
    const item_val = (try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none)).val;
    const kv = (try seen_values.fetchPut(item_val, switch_prong_src)) orelse return;
    return sema.validateSwitchDupe(block, kv.value, switch_prong_src, src_node_offset);
}

fn validateSwitchNoRange(
    sema: *Sema,
    block: *Block,
    ranges_len: u32,
    operand_ty: Type,
    src_node_offset: i32,
) CompileError!void {
    if (ranges_len == 0)
        return;

    const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = src_node_offset };
    const range_src: LazySrcLoc = .{ .node_offset_switch_range = src_node_offset };

    const msg = msg: {
        const msg = try sema.errMsg(
            block,
            operand_src,
            "ranges not allowed when switching on type '{}'",
            .{operand_ty.fmt(sema.mod)},
        );
        errdefer msg.destroy(sema.gpa);
        try sema.errNote(
            block,
            range_src,
            msg,
            "range here",
            .{},
        );
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn maybeErrorUnwrap(sema: *Sema, block: *Block, body: []const Zir.Inst.Index, operand: Air.Inst.Ref) !bool {
    if (!sema.mod.backendSupportsFeature(.panic_unwrap_error)) return false;

    const tags = sema.code.instructions.items(.tag);
    for (body) |inst| {
        switch (tags[inst]) {
            .save_err_ret_index,
            .dbg_block_begin,
            .dbg_block_end,
            .dbg_stmt,
            .@"unreachable",
            .str,
            .as_node,
            .panic,
            .field_val,
            => {},
            else => return false,
        }
    }

    for (body) |inst| {
        const air_inst = switch (tags[inst]) {
            .dbg_block_begin,
            .dbg_block_end,
            => continue,
            .dbg_stmt => {
                try sema.zirDbgStmt(block, inst);
                continue;
            },
            .save_err_ret_index => {
                try sema.zirSaveErrRetIndex(block, inst);
                continue;
            },
            .str => try sema.zirStr(block, inst),
            .as_node => try sema.zirAsNode(block, inst),
            .field_val => try sema.zirFieldVal(block, inst),
            .@"unreachable" => {
                const inst_data = sema.code.instructions.items(.data)[inst].@"unreachable";
                const src = inst_data.src();

                if (!sema.mod.comp.formatted_panics) {
                    try sema.safetyPanic(block, .unwrap_error);
                    return true;
                }

                const panic_fn = try sema.getBuiltin("panicUnwrapError");
                const err_return_trace = try sema.getErrorReturnTrace(block);
                const args: [2]Air.Inst.Ref = .{ err_return_trace, operand };
                _ = try sema.analyzeCall(block, panic_fn, src, src, .auto, false, &args, null);
                return true;
            },
            .panic => {
                const inst_data = sema.code.instructions.items(.data)[inst].un_node;
                const src = inst_data.src();
                const msg_inst = try sema.resolveInst(inst_data.operand);

                const panic_fn = try sema.getBuiltin("panic");
                const err_return_trace = try sema.getErrorReturnTrace(block);
                const args: [3]Air.Inst.Ref = .{ msg_inst, err_return_trace, .null_value };
                _ = try sema.analyzeCall(block, panic_fn, src, src, .auto, false, &args, null);
                return true;
            },
            else => unreachable,
        };
        if (sema.typeOf(air_inst).isNoReturn())
            return true;
        sema.inst_map.putAssumeCapacity(inst, air_inst);
    }
    unreachable;
}

fn maybeErrorUnwrapCondbr(sema: *Sema, block: *Block, body: []const Zir.Inst.Index, cond: Zir.Inst.Ref, cond_src: LazySrcLoc) !void {
    const index = Zir.refToIndex(cond) orelse return;
    if (sema.code.instructions.items(.tag)[index] != .is_non_err) return;

    const err_inst_data = sema.code.instructions.items(.data)[index].un_node;
    const err_operand = try sema.resolveInst(err_inst_data.operand);
    const operand_ty = sema.typeOf(err_operand);
    if (operand_ty.zigTypeTag() == .ErrorSet) {
        try sema.maybeErrorUnwrapComptime(block, body, err_operand);
        return;
    }
    if (try sema.resolveDefinedValue(block, cond_src, err_operand)) |val| {
        if (!operand_ty.isError()) return;
        if (val.getError() == null) return;
        try sema.maybeErrorUnwrapComptime(block, body, err_operand);
    }
}

fn maybeErrorUnwrapComptime(sema: *Sema, block: *Block, body: []const Zir.Inst.Index, operand: Air.Inst.Ref) !void {
    const tags = sema.code.instructions.items(.tag);
    const inst = for (body) |inst| {
        switch (tags[inst]) {
            .dbg_block_begin,
            .dbg_block_end,
            .dbg_stmt,
            .save_err_ret_index,
            => {},
            .@"unreachable" => break inst,
            else => return,
        }
    } else return;
    const inst_data = sema.code.instructions.items(.data)[inst].@"unreachable";
    const src = inst_data.src();

    if (try sema.resolveDefinedValue(block, src, operand)) |val| {
        if (val.getError()) |name| {
            return sema.fail(block, src, "caught unexpected error '{s}'", .{name});
        }
    }
}

fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const unresolved_ty = try sema.resolveType(block, ty_src, extra.lhs);
    const field_name = try sema.resolveConstString(block, name_src, extra.rhs, "field name must be comptime-known");
    const ty = try sema.resolveTypeFields(unresolved_ty);

    const has_field = hf: {
        if (ty.isSlice()) {
            if (mem.eql(u8, field_name, "ptr")) break :hf true;
            if (mem.eql(u8, field_name, "len")) break :hf true;
            break :hf false;
        }
        if (ty.castTag(.anon_struct)) |pl| {
            break :hf for (pl.data.names) |name| {
                if (mem.eql(u8, name, field_name)) break true;
            } else false;
        }
        if (ty.isTuple()) {
            const field_index = std.fmt.parseUnsigned(u32, field_name, 10) catch break :hf false;
            break :hf field_index < ty.structFieldCount();
        }
        break :hf switch (ty.zigTypeTag()) {
            .Struct => ty.structFields().contains(field_name),
            .Union => ty.unionFields().contains(field_name),
            .Enum => ty.enumFields().contains(field_name),
            .Array => mem.eql(u8, field_name, "len"),
            else => return sema.fail(block, ty_src, "type '{}' does not support '@hasField'", .{
                ty.fmt(sema.mod),
            }),
        };
    };
    if (has_field) {
        return Air.Inst.Ref.bool_true;
    } else {
        return Air.Inst.Ref.bool_false;
    }
}

fn zirHasDecl(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const src = inst_data.src();
    const lhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const container_type = try sema.resolveType(block, lhs_src, extra.lhs);
    const decl_name = try sema.resolveConstString(block, rhs_src, extra.rhs, "decl name must be comptime-known");

    try sema.checkNamespaceType(block, lhs_src, container_type);

    const namespace = container_type.getNamespace() orelse return Air.Inst.Ref.bool_false;
    if (try sema.lookupInNamespace(block, src, namespace, decl_name, true)) |decl_index| {
        const decl = sema.mod.declPtr(decl_index);
        if (decl.is_pub or decl.getFileScope() == block.getFileScope()) {
            return Air.Inst.Ref.bool_true;
        }
    }
    return Air.Inst.Ref.bool_false;
}

fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const mod = sema.mod;
    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const operand_src = inst_data.src();
    const operand = inst_data.get(sema.code);

    const result = mod.importFile(block.getFileScope(), operand) catch |err| switch (err) {
        error.ImportOutsidePkgPath => {
            return sema.fail(block, operand_src, "import of file outside package path: '{s}'", .{operand});
        },
        error.PackageNotFound => {
            const name = try block.getFileScope().pkg.getName(sema.gpa, mod.*);
            defer sema.gpa.free(name);
            return sema.fail(block, operand_src, "no package named '{s}' available within package '{s}'", .{ operand, name });
        },
        else => {
            // TODO: these errors are file system errors; make sure an update() will
            // retry this and not cache the file system error, which may be transient.
            return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
        },
    };
    try mod.semaFile(result.file);
    const file_root_decl_index = result.file.root_decl.unwrap().?;
    const file_root_decl = mod.declPtr(file_root_decl_index);
    try mod.declareDeclDependency(sema.owner_decl_index, file_root_decl_index);
    return sema.addConstant(file_root_decl.ty, file_root_decl.val);
}

fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const mod = sema.mod;
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const name = try sema.resolveConstString(block, operand_src, inst_data.operand, "file path name must be comptime-known");

    const embed_file = mod.embedFile(block.getFileScope(), name) catch |err| switch (err) {
        error.ImportOutsidePkgPath => {
            return sema.fail(block, operand_src, "embed of file outside package path: '{s}'", .{name});
        },
        else => {
            // TODO: these errors are file system errors; make sure an update() will
            // retry this and not cache the file system error, which may be transient.
            return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ name, @errorName(err) });
        },
    };

    var anon_decl = try block.startAnonDecl();
    defer anon_decl.deinit();

    const bytes_including_null = embed_file.bytes[0 .. embed_file.bytes.len + 1];

    // TODO instead of using `Value.Tag.bytes`, create a new value tag for pointing at
    // a `*Module.EmbedFile`. The purpose of this would be:
    // - If only the length is read and the bytes are not inspected by comptime code,
    //   there can be an optimization where the codegen backend does a copy_file_range
    //   into the final binary, and never loads the data into memory.
    // - When a Decl is destroyed, it can free the `*Module.EmbedFile`.
    embed_file.owner_decl = try anon_decl.finish(
        try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), embed_file.bytes.len),
        try Value.Tag.bytes.create(anon_decl.arena(), bytes_including_null),
        0, // default alignment
    );

    return sema.analyzeDeclRef(embed_file.owner_decl);
}

fn zirRetErrValueCode(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const err_name = inst_data.get(sema.code);

    // Return the error code from the function.
    const kv = try sema.mod.getErrorValue(err_name);
    const result_inst = try sema.addConstant(
        try Type.Tag.error_set_single.create(sema.arena, kv.key),
        try Value.Tag.@"error".create(sema.arena, .{ .name = kv.key }),
    );
    return result_inst;
}

fn zirShl(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    air_tag: Air.Inst.Tag,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const target = sema.mod.getTarget();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);

    const scalar_ty = lhs_ty.scalarType();
    const scalar_rhs_ty = rhs_ty.scalarType();

    // TODO coerce rhs if air_tag is not shl_sat
    const rhs_is_comptime_int = try sema.checkIntType(block, rhs_src, scalar_rhs_ty);

    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(rhs);

    if (maybe_rhs_val) |rhs_val| {
        if (rhs_val.isUndef()) {
            return sema.addConstUndef(sema.typeOf(lhs));
        }
        // If rhs is 0, return lhs without doing any calculations.
        if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
            return lhs;
        }
        if (scalar_ty.zigTypeTag() != .ComptimeInt and air_tag != .shl_sat) {
            var bits_payload = Value.Payload.U64{
                .base = .{ .tag = .int_u64 },
                .data = scalar_ty.intInfo(target).bits,
            };
            const bit_value = Value.initPayload(&bits_payload.base);
            if (rhs_ty.zigTypeTag() == .Vector) {
                var i: usize = 0;
                while (i < rhs_ty.vectorLen()) : (i += 1) {
                    var elem_value_buf: Value.ElemValueBuffer = undefined;
                    const rhs_elem = rhs_val.elemValueBuffer(sema.mod, i, &elem_value_buf);
                    if (rhs_elem.compareHetero(.gte, bit_value, target)) {
                        return sema.fail(block, rhs_src, "shift amount '{}' at index '{d}' is too large for operand type '{}'", .{
                            rhs_elem.fmtValue(scalar_ty, sema.mod),
                            i,
                            scalar_ty.fmt(sema.mod),
                        });
                    }
                }
            } else if (rhs_val.compareHetero(.gte, bit_value, target)) {
                return sema.fail(block, rhs_src, "shift amount '{}' is too large for operand type '{}'", .{
                    rhs_val.fmtValue(scalar_ty, sema.mod),
                    scalar_ty.fmt(sema.mod),
                });
            }
        }
        if (rhs_ty.zigTypeTag() == .Vector) {
            var i: usize = 0;
            while (i < rhs_ty.vectorLen()) : (i += 1) {
                var elem_value_buf: Value.ElemValueBuffer = undefined;
                const rhs_elem = rhs_val.elemValueBuffer(sema.mod, i, &elem_value_buf);
                if (rhs_elem.compareHetero(.lt, Value.zero, target)) {
                    return sema.fail(block, rhs_src, "shift by negative amount '{}' at index '{d}'", .{
                        rhs_elem.fmtValue(scalar_ty, sema.mod),
                        i,
                    });
                }
            }
        } else if (rhs_val.compareHetero(.lt, Value.zero, target)) {
            return sema.fail(block, rhs_src, "shift by negative amount '{}'", .{
                rhs_val.fmtValue(scalar_ty, sema.mod),
            });
        }
    }

    const runtime_src = if (maybe_lhs_val) |lhs_val| rs: {
        if (lhs_val.isUndef()) return sema.addConstUndef(lhs_ty);
        const rhs_val = maybe_rhs_val orelse {
            if (scalar_ty.zigTypeTag() == .ComptimeInt) {
                return sema.fail(block, src, "LHS of shift must be a fixed-width integer type, or RHS must be comptime-known", .{});
            }
            break :rs rhs_src;
        };

        const val = switch (air_tag) {
            .shl_exact => val: {
                const shifted = try lhs_val.shlWithOverflow(rhs_val, lhs_ty, sema.arena, sema.mod);
                if (scalar_ty.zigTypeTag() == .ComptimeInt) {
                    break :val shifted.wrapped_result;
                }
                if (shifted.overflow_bit.compareAllWithZero(.eq, sema.mod)) {
                    break :val shifted.wrapped_result;
                }
                return sema.fail(block, src, "operation caused overflow", .{});
            },

            .shl_sat => if (scalar_ty.zigTypeTag() == .ComptimeInt)
                try lhs_val.shl(rhs_val, lhs_ty, sema.arena, sema.mod)
            else
                try lhs_val.shlSat(rhs_val, lhs_ty, sema.arena, sema.mod),

            .shl => if (scalar_ty.zigTypeTag() == .ComptimeInt)
                try lhs_val.shl(rhs_val, lhs_ty, sema.arena, sema.mod)
            else
                try lhs_val.shlTrunc(rhs_val, lhs_ty, sema.arena, sema.mod),

            else => unreachable,
        };

        return sema.addConstant(lhs_ty, val);
    } else lhs_src;

    const new_rhs = if (air_tag == .shl_sat) rhs: {
        // Limit the RHS type for saturating shl to be an integer as small as the LHS.
        if (rhs_is_comptime_int or
            scalar_rhs_ty.intInfo(target).bits > scalar_ty.intInfo(target).bits)
        {
            const max_int = try sema.addConstant(
                lhs_ty,
                try lhs_ty.maxInt(sema.arena, target),
            );
            const rhs_limited = try sema.analyzeMinMax(block, rhs_src, rhs, max_int, .min, rhs_src, rhs_src);
            break :rhs try sema.intCast(block, src, lhs_ty, rhs_src, rhs_limited, rhs_src, false);
        } else {
            break :rhs rhs;
        }
    } else rhs;

    try sema.requireRuntimeBlock(block, src, runtime_src);
    if (block.wantSafety()) {
        const bit_count = scalar_ty.intInfo(target).bits;
        if (!std.math.isPowerOfTwo(bit_count)) {
            const bit_count_val = try Value.Tag.int_u64.create(sema.arena, bit_count);

            const ok = if (rhs_ty.zigTypeTag() == .Vector) ok: {
                const bit_count_inst = try sema.addConstant(rhs_ty, try Value.Tag.repeated.create(sema.arena, bit_count_val));
                const lt = try block.addCmpVector(rhs, bit_count_inst, .lt);
                break :ok try block.addInst(.{
                    .tag = .reduce,
                    .data = .{ .reduce = .{
                        .operand = lt,
                        .operation = .And,
                    } },
                });
            } else ok: {
                const bit_count_inst = try sema.addConstant(rhs_ty, bit_count_val);
                break :ok try block.addBinOp(.cmp_lt, rhs, bit_count_inst);
            };
            try sema.addSafetyCheck(block, ok, .shift_rhs_too_big);
        }

        if (air_tag == .shl_exact) {
            const op_ov_tuple_ty = try sema.overflowArithmeticTupleType(lhs_ty);
            const op_ov = try block.addInst(.{
                .tag = .shl_with_overflow,
                .data = .{ .ty_pl = .{
                    .ty = try sema.addType(op_ov_tuple_ty),
                    .payload = try sema.addExtra(Air.Bin{
                        .lhs = lhs,
                        .rhs = rhs,
                    }),
                } },
            });
            const ov_bit = try sema.tupleFieldValByIndex(block, src, op_ov, 1, op_ov_tuple_ty);
            const any_ov_bit = if (lhs_ty.zigTypeTag() == .Vector)
                try block.addInst(.{
                    .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
                    .data = .{ .reduce = .{
                        .operand = ov_bit,
                        .operation = .Or,
                    } },
                })
            else
                ov_bit;
            const zero_ov = try sema.addConstant(Type.u1, Value.zero);
            const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);

            try sema.addSafetyCheck(block, no_ov, .shl_overflow);
            return sema.tupleFieldValByIndex(block, src, op_ov, 0, op_ov_tuple_ty);
        }
    }
    return block.addBinOp(air_tag, lhs, new_rhs);
}

fn zirShr(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    air_tag: Air.Inst.Tag,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    const target = sema.mod.getTarget();
    const scalar_ty = lhs_ty.scalarType();

    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(rhs);

    const runtime_src = if (maybe_rhs_val) |rhs_val| rs: {
        if (rhs_val.isUndef()) {
            return sema.addConstUndef(lhs_ty);
        }
        // If rhs is 0, return lhs without doing any calculations.
        if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
            return lhs;
        }
        if (scalar_ty.zigTypeTag() != .ComptimeInt) {
            var bits_payload = Value.Payload.U64{
                .base = .{ .tag = .int_u64 },
                .data = scalar_ty.intInfo(target).bits,
            };
            const bit_value = Value.initPayload(&bits_payload.base);
            if (rhs_ty.zigTypeTag() == .Vector) {
                var i: usize = 0;
                while (i < rhs_ty.vectorLen()) : (i += 1) {
                    var elem_value_buf: Value.ElemValueBuffer = undefined;
                    const rhs_elem = rhs_val.elemValueBuffer(sema.mod, i, &elem_value_buf);
                    if (rhs_elem.compareHetero(.gte, bit_value, target)) {
                        return sema.fail(block, rhs_src, "shift amount '{}' at index '{d}' is too large for operand type '{}'", .{
                            rhs_elem.fmtValue(scalar_ty, sema.mod),
                            i,
                            scalar_ty.fmt(sema.mod),
                        });
                    }
                }
            } else if (rhs_val.compareHetero(.gte, bit_value, target)) {
                return sema.fail(block, rhs_src, "shift amount '{}' is too large for operand type '{}'", .{
                    rhs_val.fmtValue(scalar_ty, sema.mod),
                    scalar_ty.fmt(sema.mod),
                });
            }
        }
        if (rhs_ty.zigTypeTag() == .Vector) {
            var i: usize = 0;
            while (i < rhs_ty.vectorLen()) : (i += 1) {
                var elem_value_buf: Value.ElemValueBuffer = undefined;
                const rhs_elem = rhs_val.elemValueBuffer(sema.mod, i, &elem_value_buf);
                if (rhs_elem.compareHetero(.lt, Value.zero, target)) {
                    return sema.fail(block, rhs_src, "shift by negative amount '{}' at index '{d}'", .{
                        rhs_elem.fmtValue(scalar_ty, sema.mod),
                        i,
                    });
                }
            }
        } else if (rhs_val.compareHetero(.lt, Value.zero, target)) {
            return sema.fail(block, rhs_src, "shift by negative amount '{}'", .{
                rhs_val.fmtValue(scalar_ty, sema.mod),
            });
        }
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                return sema.addConstUndef(lhs_ty);
            }
            if (air_tag == .shr_exact) {
                // Detect if any ones would be shifted out.
                const truncated = try lhs_val.intTruncBitsAsValue(lhs_ty, sema.arena, .unsigned, rhs_val, sema.mod);
                if (!(try truncated.compareAllWithZeroAdvanced(.eq, sema))) {
                    return sema.fail(block, src, "exact shift shifted out 1 bits", .{});
                }
            }
            const val = try lhs_val.shr(rhs_val, lhs_ty, sema.arena, sema.mod);
            return sema.addConstant(lhs_ty, val);
        } else {
            break :rs lhs_src;
        }
    } else rhs_src;

    if (maybe_rhs_val == null and scalar_ty.zigTypeTag() == .ComptimeInt) {
        return sema.fail(block, src, "LHS of shift must be a fixed-width integer type, or RHS must be comptime-known", .{});
    }

    try sema.requireRuntimeBlock(block, src, runtime_src);
    const result = try block.addBinOp(air_tag, lhs, rhs);
    if (block.wantSafety()) {
        const bit_count = scalar_ty.intInfo(target).bits;
        if (!std.math.isPowerOfTwo(bit_count)) {
            const bit_count_val = try Value.Tag.int_u64.create(sema.arena, bit_count);

            const ok = if (rhs_ty.zigTypeTag() == .Vector) ok: {
                const bit_count_inst = try sema.addConstant(rhs_ty, try Value.Tag.repeated.create(sema.arena, bit_count_val));
                const lt = try block.addCmpVector(rhs, bit_count_inst, .lt);
                break :ok try block.addInst(.{
                    .tag = .reduce,
                    .data = .{ .reduce = .{
                        .operand = lt,
                        .operation = .And,
                    } },
                });
            } else ok: {
                const bit_count_inst = try sema.addConstant(rhs_ty, bit_count_val);
                break :ok try block.addBinOp(.cmp_lt, rhs, bit_count_inst);
            };
            try sema.addSafetyCheck(block, ok, .shift_rhs_too_big);
        }

        if (air_tag == .shr_exact) {
            const back = try block.addBinOp(.shl, result, rhs);

            const ok = if (rhs_ty.zigTypeTag() == .Vector) ok: {
                const eql = try block.addCmpVector(lhs, back, .eq);
                break :ok try block.addInst(.{
                    .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
                    .data = .{ .reduce = .{
                        .operand = eql,
                        .operation = .And,
                    } },
                });
            } else try block.addBinOp(.cmp_eq, lhs, back);
            try sema.addSafetyCheck(block, ok, .shr_overflow);
        }
    }
    return result;
}

fn zirBitwise(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    air_tag: Air.Inst.Tag,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{ .override = &[_]LazySrcLoc{ lhs_src, rhs_src } });
    const scalar_type = resolved_type.scalarType();
    const scalar_tag = scalar_type.zigTypeTag();

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    if (!is_int) {
        return sema.fail(block, src, "invalid operands to binary bitwise expression: '{s}' and '{s}'", .{ @tagName(lhs_ty.zigTypeTag()), @tagName(rhs_ty.zigTypeTag()) });
    }

    const runtime_src = runtime: {
        // TODO: ask the linker what kind of relocations are available, and
        // in some cases emit a Value that means "this decl's address AND'd with this operand".
        if (try sema.resolveMaybeUndefValIntable(casted_lhs)) |lhs_val| {
            if (try sema.resolveMaybeUndefValIntable(casted_rhs)) |rhs_val| {
                const result_val = switch (air_tag) {
                    .bit_and => try lhs_val.bitwiseAnd(rhs_val, resolved_type, sema.arena, sema.mod),
                    .bit_or => try lhs_val.bitwiseOr(rhs_val, resolved_type, sema.arena, sema.mod),
                    .xor => try lhs_val.bitwiseXor(rhs_val, resolved_type, sema.arena, sema.mod),
                    else => unreachable,
                };
                return sema.addConstant(resolved_type, result_val);
            } else {
                break :runtime rhs_src;
            }
        } else {
            break :runtime lhs_src;
        }
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addBinOp(air_tag, casted_lhs, casted_rhs);
}

fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_un_op = inst_data.src_node };

    const operand = try sema.resolveInst(inst_data.operand);
    const operand_type = sema.typeOf(operand);
    const scalar_type = operand_type.scalarType();

    if (scalar_type.zigTypeTag() != .Int) {
        return sema.fail(block, src, "unable to perform binary not operation on type '{}'", .{
            operand_type.fmt(sema.mod),
        });
    }

    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        if (val.isUndef()) {
            return sema.addConstUndef(operand_type);
        } else if (operand_type.zigTypeTag() == .Vector) {
            const vec_len = try sema.usizeCast(block, operand_src, operand_type.vectorLen());
            var elem_val_buf: Value.ElemValueBuffer = undefined;
            const elems = try sema.arena.alloc(Value, vec_len);
            for (elems, 0..) |*elem, i| {
                const elem_val = val.elemValueBuffer(sema.mod, i, &elem_val_buf);
                elem.* = try elem_val.bitwiseNot(scalar_type, sema.arena, sema.mod);
            }
            return sema.addConstant(
                operand_type,
                try Value.Tag.aggregate.create(sema.arena, elems),
            );
        } else {
            const result_val = try val.bitwiseNot(operand_type, sema.arena, sema.mod);
            return sema.addConstant(operand_type, result_val);
        }
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.not, operand_type, operand);
}

fn analyzeTupleCat(
    sema: *Sema,
    block: *Block,
    src_node: i32,
    lhs: Air.Inst.Ref,
    rhs: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const src = LazySrcLoc.nodeOffset(src_node);
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = src_node };

    const lhs_len = lhs_ty.structFieldCount();
    const rhs_len = rhs_ty.structFieldCount();
    const dest_fields = lhs_len + rhs_len;

    if (dest_fields == 0) {
        return sema.addConstant(Type.initTag(.empty_struct_literal), Value.initTag(.empty_struct_value));
    }
    if (lhs_len == 0) {
        return rhs;
    }
    if (rhs_len == 0) {
        return lhs;
    }
    const final_len = try sema.usizeCast(block, rhs_src, dest_fields);

    const types = try sema.arena.alloc(Type, final_len);
    const values = try sema.arena.alloc(Value, final_len);

    const opt_runtime_src = rs: {
        var runtime_src: ?LazySrcLoc = null;
        var i: u32 = 0;
        while (i < lhs_len) : (i += 1) {
            types[i] = lhs_ty.structFieldType(i);
            const default_val = lhs_ty.structFieldDefaultValue(i);
            values[i] = default_val;
            const operand_src = lhs_src; // TODO better source location
            if (default_val.tag() == .unreachable_value) {
                runtime_src = operand_src;
            }
        }
        i = 0;
        while (i < rhs_len) : (i += 1) {
            types[i + lhs_len] = rhs_ty.structFieldType(i);
            const default_val = rhs_ty.structFieldDefaultValue(i);
            values[i + lhs_len] = default_val;
            const operand_src = rhs_src; // TODO better source location
            if (default_val.tag() == .unreachable_value) {
                runtime_src = operand_src;
            }
        }
        break :rs runtime_src;
    };

    const tuple_ty = try Type.Tag.tuple.create(sema.arena, .{
        .types = types,
        .values = values,
    });

    const runtime_src = opt_runtime_src orelse {
        const tuple_val = try Value.Tag.aggregate.create(sema.arena, values);
        return sema.addConstant(tuple_ty, tuple_val);
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, final_len);
    var i: u32 = 0;
    while (i < lhs_len) : (i += 1) {
        const operand_src = lhs_src; // TODO better source location
        element_refs[i] = try sema.tupleFieldValByIndex(block, operand_src, lhs, i, lhs_ty);
    }
    i = 0;
    while (i < rhs_len) : (i += 1) {
        const operand_src = rhs_src; // TODO better source location
        element_refs[i + lhs_len] =
            try sema.tupleFieldValByIndex(block, operand_src, rhs, i, rhs_ty);
    }

    return block.addAggregateInit(tuple_ty, element_refs);
}

fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const src = inst_data.src();

    const lhs_is_tuple = lhs_ty.isTuple();
    const rhs_is_tuple = rhs_ty.isTuple();
    if (lhs_is_tuple and rhs_is_tuple) {
        return sema.analyzeTupleCat(block, inst_data.src_node, lhs, rhs);
    }

    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };

    const lhs_info = try sema.getArrayCatInfo(block, lhs_src, lhs, rhs_ty) orelse lhs_info: {
        if (lhs_is_tuple) break :lhs_info @as(Type.ArrayInfo, undefined);
        return sema.fail(block, lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(sema.mod)});
    };
    const rhs_info = try sema.getArrayCatInfo(block, rhs_src, rhs, lhs_ty) orelse {
        assert(!rhs_is_tuple);
        return sema.fail(block, rhs_src, "expected indexable; found '{}'", .{rhs_ty.fmt(sema.mod)});
    };

    const resolved_elem_ty = t: {
        var trash_block = block.makeSubBlock();
        trash_block.is_comptime = false;
        defer trash_block.instructions.deinit(sema.gpa);

        const instructions = [_]Air.Inst.Ref{
            try trash_block.addBitCast(lhs_info.elem_type, .void_value),
            try trash_block.addBitCast(rhs_info.elem_type, .void_value),
        };
        break :t try sema.resolvePeerTypes(block, src, &instructions, .{
            .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
        });
    };

    // When there is a sentinel mismatch, no sentinel on the result.
    // Otherwise, use the sentinel value provided by either operand,
    // coercing it to the peer-resolved element type.
    const res_sent_val: ?Value = s: {
        if (lhs_info.sentinel) |lhs_sent_val| {
            const lhs_sent = try sema.addConstant(lhs_info.elem_type, lhs_sent_val);
            if (rhs_info.sentinel) |rhs_sent_val| {
                const rhs_sent = try sema.addConstant(rhs_info.elem_type, rhs_sent_val);
                const lhs_sent_casted = try sema.coerce(block, resolved_elem_ty, lhs_sent, lhs_src);
                const rhs_sent_casted = try sema.coerce(block, resolved_elem_ty, rhs_sent, rhs_src);
                const lhs_sent_casted_val = try sema.resolveConstValue(block, lhs_src, lhs_sent_casted, "array sentinel value must be comptime-known");
                const rhs_sent_casted_val = try sema.resolveConstValue(block, rhs_src, rhs_sent_casted, "array sentinel value must be comptime-known");
                if (try sema.valuesEqual(lhs_sent_casted_val, rhs_sent_casted_val, resolved_elem_ty)) {
                    break :s lhs_sent_casted_val;
                } else {
                    break :s null;
                }
            } else {
                const lhs_sent_casted = try sema.coerce(block, resolved_elem_ty, lhs_sent, lhs_src);
                const lhs_sent_casted_val = try sema.resolveConstValue(block, lhs_src, lhs_sent_casted, "array sentinel value must be comptime-known");
                break :s lhs_sent_casted_val;
            }
        } else {
            if (rhs_info.sentinel) |rhs_sent_val| {
                const rhs_sent = try sema.addConstant(rhs_info.elem_type, rhs_sent_val);
                const rhs_sent_casted = try sema.coerce(block, resolved_elem_ty, rhs_sent, rhs_src);
                const rhs_sent_casted_val = try sema.resolveConstValue(block, rhs_src, rhs_sent_casted, "array sentinel value must be comptime-known");
                break :s rhs_sent_casted_val;
            } else {
                break :s null;
            }
        }
    };

    const lhs_len = try sema.usizeCast(block, lhs_src, lhs_info.len);
    const rhs_len = try sema.usizeCast(block, lhs_src, rhs_info.len);
    const result_len = std.math.add(usize, lhs_len, rhs_len) catch |err| switch (err) {
        error.Overflow => return sema.fail(
            block,
            src,
            "concatenating arrays of length {d} and {d} produces an array too large for this compiler implementation to handle",
            .{ lhs_len, rhs_len },
        ),
    };

    const result_ty = try Type.array(sema.arena, result_len, res_sent_val, resolved_elem_ty, sema.mod);
    const ptr_addrspace = p: {
        if (lhs_ty.zigTypeTag() == .Pointer) break :p lhs_ty.ptrAddressSpace();
        if (rhs_ty.zigTypeTag() == .Pointer) break :p rhs_ty.ptrAddressSpace();
        break :p null;
    };

    const runtime_src = if (switch (lhs_ty.zigTypeTag()) {
        .Array, .Struct => try sema.resolveMaybeUndefVal(lhs),
        .Pointer => try sema.resolveDefinedValue(block, lhs_src, lhs),
        else => unreachable,
    }) |lhs_val| rs: {
        if (switch (rhs_ty.zigTypeTag()) {
            .Array, .Struct => try sema.resolveMaybeUndefVal(rhs),
            .Pointer => try sema.resolveDefinedValue(block, rhs_src, rhs),
            else => unreachable,
        }) |rhs_val| {
            const lhs_sub_val = if (lhs_ty.isSinglePointer())
                (try sema.pointerDeref(block, lhs_src, lhs_val, lhs_ty)).?
            else
                lhs_val;

            const rhs_sub_val = if (rhs_ty.isSinglePointer())
                (try sema.pointerDeref(block, rhs_src, rhs_val, rhs_ty)).?
            else
                rhs_val;

            const final_len_including_sent = result_len + @boolToInt(res_sent_val != null);
            const element_vals = try sema.arena.alloc(Value, final_len_including_sent);
            var elem_i: usize = 0;
            while (elem_i < lhs_len) : (elem_i += 1) {
                const lhs_elem_i = elem_i;
                const elem_ty = if (lhs_is_tuple) lhs_ty.structFieldType(lhs_elem_i) else lhs_info.elem_type;
                const elem_default_val = if (lhs_is_tuple) lhs_ty.structFieldDefaultValue(lhs_elem_i) else Value.initTag(.unreachable_value);
                const elem_val = if (elem_default_val.tag() == .unreachable_value) try lhs_sub_val.elemValue(sema.mod, sema.arena, lhs_elem_i) else elem_default_val;
                const elem_val_inst = try sema.addConstant(elem_ty, elem_val);
                const coerced_elem_val_inst = try sema.coerce(block, resolved_elem_ty, elem_val_inst, .unneeded);
                const coerced_elem_val = try sema.resolveConstMaybeUndefVal(block, .unneeded, coerced_elem_val_inst, "");
                element_vals[elem_i] = coerced_elem_val;
            }
            while (elem_i < result_len) : (elem_i += 1) {
                const rhs_elem_i = elem_i - lhs_len;
                const elem_ty = if (rhs_is_tuple) rhs_ty.structFieldType(rhs_elem_i) else rhs_info.elem_type;
                const elem_default_val = if (rhs_is_tuple) rhs_ty.structFieldDefaultValue(rhs_elem_i) else Value.initTag(.unreachable_value);
                const elem_val = if (elem_default_val.tag() == .unreachable_value) try rhs_sub_val.elemValue(sema.mod, sema.arena, rhs_elem_i) else elem_default_val;
                const elem_val_inst = try sema.addConstant(elem_ty, elem_val);
                const coerced_elem_val_inst = try sema.coerce(block, resolved_elem_ty, elem_val_inst, .unneeded);
                const coerced_elem_val = try sema.resolveConstMaybeUndefVal(block, .unneeded, coerced_elem_val_inst, "");
                element_vals[elem_i] = coerced_elem_val;
            }
            if (res_sent_val) |sent_val| {
                element_vals[result_len] = sent_val;
            }
            const val = try Value.Tag.aggregate.create(sema.arena, element_vals);
            return sema.addConstantMaybeRef(block, result_ty, val, ptr_addrspace != null);
        } else break :rs rhs_src;
    } else lhs_src;

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (ptr_addrspace) |ptr_as| {
        const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = result_ty,
            .@"addrspace" = ptr_as,
        });
        const alloc = try block.addTy(.alloc, alloc_ty);
        const elem_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = resolved_elem_ty,
            .@"addrspace" = ptr_as,
        });

        var elem_i: usize = 0;
        while (elem_i < lhs_len) : (elem_i += 1) {
            const elem_index = try sema.addIntUnsigned(Type.usize, elem_i);
            const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
            const init = try sema.elemVal(block, lhs_src, lhs, elem_index, src, true);
            try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
        }
        while (elem_i < result_len) : (elem_i += 1) {
            const elem_index = try sema.addIntUnsigned(Type.usize, elem_i);
            const rhs_index = try sema.addIntUnsigned(Type.usize, elem_i - lhs_len);
            const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
            const init = try sema.elemVal(block, rhs_src, rhs, rhs_index, src, true);
            try sema.storePtr2(block, src, elem_ptr, src, init, rhs_src, .store);
        }
        if (res_sent_val) |sent_val| {
            const elem_index = try sema.addIntUnsigned(Type.usize, result_len);
            const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
            const init = try sema.addConstant(lhs_info.elem_type, sent_val);
            try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
        }

        return alloc;
    }

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, result_len);
    {
        var elem_i: usize = 0;
        while (elem_i < lhs_len) : (elem_i += 1) {
            const index = try sema.addIntUnsigned(Type.usize, elem_i);
            const init = try sema.elemVal(block, lhs_src, lhs, index, src, true);
            element_refs[elem_i] = try sema.coerce(block, resolved_elem_ty, init, lhs_src);
        }
        while (elem_i < result_len) : (elem_i += 1) {
            const index = try sema.addIntUnsigned(Type.usize, elem_i - lhs_len);
            const init = try sema.elemVal(block, rhs_src, rhs, index, src, true);
            element_refs[elem_i] = try sema.coerce(block, resolved_elem_ty, init, rhs_src);
        }
    }

    return block.addAggregateInit(result_ty, element_refs);
}

fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref, peer_ty: Type) !?Type.ArrayInfo {
    const operand_ty = sema.typeOf(operand);
    switch (operand_ty.zigTypeTag()) {
        .Array => return operand_ty.arrayInfo(),
        .Pointer => {
            const ptr_info = operand_ty.ptrInfo().data;
            switch (ptr_info.size) {
                // TODO: in the Many case here this should only work if the type
                // has a sentinel, and this code should compute the length based
                // on the sentinel value.
                .Slice, .Many => {
                    const val = try sema.resolveConstValue(block, src, operand, "slice value being concatenated must be comptime-known");
                    return Type.ArrayInfo{
                        .elem_type = ptr_info.pointee_type,
                        .sentinel = ptr_info.sentinel,
                        .len = val.sliceLen(sema.mod),
                    };
                },
                .One => {
                    if (ptr_info.pointee_type.zigTypeTag() == .Array) {
                        return ptr_info.pointee_type.arrayInfo();
                    }
                },
                .C => {},
            }
        },
        .Struct => {
            if (operand_ty.isTuple() and peer_ty.isIndexable()) {
                assert(!peer_ty.isTuple());
                return .{
                    .elem_type = peer_ty.elemType2(),
                    .sentinel = null,
                    .len = operand_ty.arrayLen(),
                };
            }
        },
        else => {},
    }
    return null;
}

fn analyzeTupleMul(
    sema: *Sema,
    block: *Block,
    src_node: i32,
    operand: Air.Inst.Ref,
    factor: u64,
) CompileError!Air.Inst.Ref {
    const operand_ty = sema.typeOf(operand);
    const src = LazySrcLoc.nodeOffset(src_node);
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = src_node };

    const tuple_len = operand_ty.structFieldCount();
    const final_len_u64 = std.math.mul(u64, tuple_len, factor) catch
        return sema.fail(block, rhs_src, "operation results in overflow", .{});

    if (final_len_u64 == 0) {
        return sema.addConstant(Type.initTag(.empty_struct_literal), Value.initTag(.empty_struct_value));
    }
    const final_len = try sema.usizeCast(block, rhs_src, final_len_u64);

    const types = try sema.arena.alloc(Type, final_len);
    const values = try sema.arena.alloc(Value, final_len);

    const opt_runtime_src = rs: {
        var runtime_src: ?LazySrcLoc = null;
        var i: u32 = 0;
        while (i < tuple_len) : (i += 1) {
            types[i] = operand_ty.structFieldType(i);
            values[i] = operand_ty.structFieldDefaultValue(i);
            const operand_src = lhs_src; // TODO better source location
            if (values[i].tag() == .unreachable_value) {
                runtime_src = operand_src;
            }
        }
        i = 0;
        while (i < factor) : (i += 1) {
            mem.copy(Type, types[tuple_len * i ..], types[0..tuple_len]);
            mem.copy(Value, values[tuple_len * i ..], values[0..tuple_len]);
        }
        break :rs runtime_src;
    };

    const tuple_ty = try Type.Tag.tuple.create(sema.arena, .{
        .types = types,
        .values = values,
    });

    const runtime_src = opt_runtime_src orelse {
        const tuple_val = try Value.Tag.aggregate.create(sema.arena, values);
        return sema.addConstant(tuple_ty, tuple_val);
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, final_len);
    var i: u32 = 0;
    while (i < tuple_len) : (i += 1) {
        const operand_src = lhs_src; // TODO better source location
        element_refs[i] = try sema.tupleFieldValByIndex(block, operand_src, operand, @intCast(u32, i), operand_ty);
    }
    i = 1;
    while (i < factor) : (i += 1) {
        mem.copy(Air.Inst.Ref, element_refs[tuple_len * i ..], element_refs[0..tuple_len]);
    }

    return block.addAggregateInit(tuple_ty, element_refs);
}

fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const lhs_ty = sema.typeOf(lhs);
    const src: LazySrcLoc = inst_data.src();
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const operator_src: LazySrcLoc = .{ .node_offset_main_token = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };

    if (lhs_ty.isTuple()) {
        // In `**` rhs must be comptime-known, but lhs can be runtime-known
        const factor = try sema.resolveInt(block, rhs_src, extra.rhs, Type.usize, "array multiplication factor must be comptime-known");
        return sema.analyzeTupleMul(block, inst_data.src_node, lhs, factor);
    }

    // Analyze the lhs first, to catch the case that someone tried to do exponentiation
    const lhs_info = try sema.getArrayCatInfo(block, lhs_src, lhs, lhs_ty) orelse {
        const msg = msg: {
            const msg = try sema.errMsg(block, lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(sema.mod)});
            errdefer msg.destroy(sema.gpa);
            switch (lhs_ty.zigTypeTag()) {
                .Int, .Float, .ComptimeFloat, .ComptimeInt, .Vector => {
                    try sema.errNote(block, operator_src, msg, "this operator multiplies arrays; use std.math.pow for exponentiation", .{});
                },
                else => {},
            }
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    };

    // In `**` rhs must be comptime-known, but lhs can be runtime-known
    const factor = try sema.resolveInt(block, rhs_src, extra.rhs, Type.usize, "array multiplication factor must be comptime-known");

    const result_len_u64 = std.math.mul(u64, lhs_info.len, factor) catch
        return sema.fail(block, rhs_src, "operation results in overflow", .{});
    const result_len = try sema.usizeCast(block, src, result_len_u64);

    const result_ty = try Type.array(sema.arena, result_len, lhs_info.sentinel, lhs_info.elem_type, sema.mod);

    const ptr_addrspace = if (lhs_ty.zigTypeTag() == .Pointer) lhs_ty.ptrAddressSpace() else null;
    const lhs_len = try sema.usizeCast(block, lhs_src, lhs_info.len);

    if (try sema.resolveDefinedValue(block, lhs_src, lhs)) |lhs_val| {
        const final_len_including_sent = result_len + @boolToInt(lhs_info.sentinel != null);

        const lhs_sub_val = if (lhs_ty.isSinglePointer())
            (try sema.pointerDeref(block, lhs_src, lhs_val, lhs_ty)).?
        else
            lhs_val;

        const val = v: {
            // Optimization for the common pattern of a single element repeated N times, such
            // as zero-filling a byte array.
            if (lhs_len == 1) {
                const elem_val = try lhs_sub_val.elemValue(sema.mod, sema.arena, 0);
                break :v try Value.Tag.repeated.create(sema.arena, elem_val);
            }

            const element_vals = try sema.arena.alloc(Value, final_len_including_sent);
            var elem_i: usize = 0;
            while (elem_i < result_len) {
                var lhs_i: usize = 0;
                while (lhs_i < lhs_len) : (lhs_i += 1) {
                    const elem_val = try lhs_sub_val.elemValue(sema.mod, sema.arena, lhs_i);
                    element_vals[elem_i] = elem_val;
                    elem_i += 1;
                }
            }
            if (lhs_info.sentinel) |sent_val| {
                element_vals[result_len] = sent_val;
            }
            break :v try Value.Tag.aggregate.create(sema.arena, element_vals);
        };
        return sema.addConstantMaybeRef(block, result_ty, val, ptr_addrspace != null);
    }

    try sema.requireRuntimeBlock(block, src, lhs_src);

    if (ptr_addrspace) |ptr_as| {
        const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = result_ty,
            .@"addrspace" = ptr_as,
        });
        const alloc = try block.addTy(.alloc, alloc_ty);
        const elem_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = lhs_info.elem_type,
            .@"addrspace" = ptr_as,
        });

        var elem_i: usize = 0;
        while (elem_i < result_len) {
            var lhs_i: usize = 0;
            while (lhs_i < lhs_len) : (lhs_i += 1) {
                const elem_index = try sema.addIntUnsigned(Type.usize, elem_i);
                elem_i += 1;
                const lhs_index = try sema.addIntUnsigned(Type.usize, lhs_i);
                const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
                const init = try sema.elemVal(block, lhs_src, lhs, lhs_index, src, true);
                try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
            }
        }
        if (lhs_info.sentinel) |sent_val| {
            const elem_index = try sema.addIntUnsigned(Type.usize, result_len);
            const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
            const init = try sema.addConstant(lhs_info.elem_type, sent_val);
            try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
        }

        return alloc;
    }

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, result_len);
    var elem_i: usize = 0;
    while (elem_i < result_len) {
        var lhs_i: usize = 0;
        while (lhs_i < lhs_len) : (lhs_i += 1) {
            const lhs_index = try sema.addIntUnsigned(Type.usize, lhs_i);
            const init = try sema.elemVal(block, lhs_src, lhs, lhs_index, src, true);
            element_refs[elem_i] = init;
            elem_i += 1;
        }
    }

    return block.addAggregateInit(result_ty, element_refs);
}

fn zirNegate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const lhs_src = src;
    const rhs_src: LazySrcLoc = .{ .node_offset_un_op = inst_data.src_node };

    const rhs = try sema.resolveInst(inst_data.operand);
    const rhs_ty = sema.typeOf(rhs);
    const rhs_scalar_ty = rhs_ty.scalarType();

    if (rhs_scalar_ty.isUnsignedInt() or switch (rhs_scalar_ty.zigTypeTag()) {
        .Int, .ComptimeInt, .Float, .ComptimeFloat => false,
        else => true,
    }) {
        return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(sema.mod)});
    }

    if (rhs_scalar_ty.isAnyFloat()) {
        // We handle float negation here to ensure negative zero is represented in the bits.
        if (try sema.resolveMaybeUndefVal(rhs)) |rhs_val| {
            if (rhs_val.isUndef()) return sema.addConstUndef(rhs_ty);
            return sema.addConstant(rhs_ty, try rhs_val.floatNeg(rhs_ty, sema.arena, sema.mod));
        }
        try sema.requireRuntimeBlock(block, src, null);
        return block.addUnOp(if (block.float_mode == .Optimized) .neg_optimized else .neg, rhs);
    }

    const lhs = if (rhs_ty.zigTypeTag() == .Vector)
        try sema.addConstant(rhs_ty, try Value.Tag.repeated.create(sema.arena, Value.zero))
    else
        try sema.resolveInst(.zero);

    return sema.analyzeArithmetic(block, .sub, lhs, rhs, src, lhs_src, rhs_src, true);
}

fn zirNegateWrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const lhs_src = src;
    const rhs_src: LazySrcLoc = .{ .node_offset_un_op = inst_data.src_node };

    const rhs = try sema.resolveInst(inst_data.operand);
    const rhs_ty = sema.typeOf(rhs);
    const rhs_scalar_ty = rhs_ty.scalarType();

    switch (rhs_scalar_ty.zigTypeTag()) {
        .Int, .ComptimeInt, .Float, .ComptimeFloat => {},
        else => return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(sema.mod)}),
    }

    const lhs = if (rhs_ty.zigTypeTag() == .Vector)
        try sema.addConstant(rhs_ty, try Value.Tag.repeated.create(sema.arena, Value.zero))
    else
        try sema.resolveInst(.zero);

    return sema.analyzeArithmetic(block, .subwrap, lhs, rhs, src, lhs_src, rhs_src, true);
}

fn zirArithmetic(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    zir_tag: Zir.Inst.Tag,
    safety: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    sema.src = .{ .node_offset_bin_op = inst_data.src_node };
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);

    return sema.analyzeArithmetic(block, zir_tag, lhs, rhs, sema.src, lhs_src, rhs_src, safety);
}

fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const is_vector = resolved_type.zigTypeTag() == .Vector;

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const lhs_scalar_ty = lhs_ty.scalarType();
    const rhs_scalar_ty = rhs_ty.scalarType();
    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .div);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    if ((lhs_ty.zigTypeTag() == .ComptimeFloat and rhs_ty.zigTypeTag() == .ComptimeInt) or
        (lhs_ty.zigTypeTag() == .ComptimeInt and rhs_ty.zigTypeTag() == .ComptimeFloat))
    {
        // If it makes a difference whether we coerce to ints or floats before doing the division, error.
        // If lhs % rhs is 0, it doesn't matter.
        const lhs_val = maybe_lhs_val orelse unreachable;
        const rhs_val = maybe_rhs_val orelse unreachable;
        const rem = lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod) catch unreachable;
        if (!rem.compareAllWithZero(.eq, mod)) {
            return sema.fail(block, src, "ambiguous coercion of division operands '{s}' and '{s}'; non-zero remainder '{}'", .{
                @tagName(lhs_ty.tag()), @tagName(rhs_ty.tag()), rem.fmtValue(resolved_type, sema.mod),
            });
        }
    }

    // TODO: emit compile error when .div is used on integers and there would be an
    // ambiguous result between div_floor and div_trunc.

    // For integers:
    // If the lhs is zero, then zero is returned regardless of rhs.
    // If the rhs is zero, compile error for division by zero.
    // If the rhs is undefined, compile error because there is a possible
    // value (zero) for which the division would be illegal behavior.
    // If the lhs is undefined:
    //   * if lhs type is signed:
    //     * if rhs is comptime-known and not -1, result is undefined
    //     * if rhs is -1 or runtime-known, compile error because there is a
    //        possible value (-min_int / -1)  for which division would be
    //        illegal behavior.
    //   * if lhs type is unsigned, undef is returned regardless of rhs.
    //
    // For floats:
    // If the rhs is zero:
    //  * comptime_float: compile error for division by zero.
    //  * other float type:
    //    * if the lhs is zero: QNaN
    //    * otherwise: +Inf or -Inf depending on lhs sign
    // If the rhs is undefined:
    //  * comptime_float: compile error because there is a possible
    //    value (zero) for which the division would be illegal behavior.
    //  * other float type: result is undefined
    // If the lhs is undefined, result is undefined.
    switch (scalar_tag) {
        .Int, .ComptimeInt, .ComptimeFloat => {
            if (maybe_lhs_val) |lhs_val| {
                if (!lhs_val.isUndef()) {
                    if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        const zero_val = if (is_vector) b: {
                            break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                        } else Value.zero;
                        return sema.addConstant(resolved_type, zero_val);
                    }
                }
            }
            if (maybe_rhs_val) |rhs_val| {
                if (rhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                    return sema.failWithDivideByZero(block, rhs_src);
                }
                // TODO: if the RHS is one, return the LHS directly
            }
        },
        else => {},
    }

    const runtime_src = rs: {
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                if (lhs_scalar_ty.isSignedInt() and rhs_scalar_ty.isSignedInt()) {
                    if (maybe_rhs_val) |rhs_val| {
                        if (try sema.compareAll(rhs_val, .neq, Value.negative_one, resolved_type)) {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                return sema.addConstUndef(resolved_type);
            }

            if (maybe_rhs_val) |rhs_val| {
                if (is_int) {
                    const res = try lhs_val.intDiv(rhs_val, resolved_type, sema.arena, mod);
                    var vector_index: usize = undefined;
                    if (!(try sema.intFitsInType(res, resolved_type, &vector_index))) {
                        return sema.failWithIntegerOverflow(block, src, resolved_type, res, vector_index);
                    }
                    return sema.addConstant(resolved_type, res);
                } else {
                    return sema.addConstant(
                        resolved_type,
                        try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, mod),
                    );
                }
            } else {
                break :rs rhs_src;
            }
        } else {
            break :rs lhs_src;
        }
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (block.wantSafety()) {
        try sema.addDivIntOverflowSafety(block, resolved_type, lhs_scalar_ty, maybe_lhs_val, maybe_rhs_val, casted_lhs, casted_rhs, is_int);
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
    }

    const air_tag = if (is_int) blk: {
        if (lhs_ty.isSignedInt() or rhs_ty.isSignedInt()) {
            return sema.fail(block, src, "division with '{s}' and '{s}': signed integers must use @divTrunc, @divFloor, or @divExact", .{ @tagName(lhs_ty.tag()), @tagName(rhs_ty.tag()) });
        }
        break :blk Air.Inst.Tag.div_trunc;
    } else switch (block.float_mode) {
        .Optimized => Air.Inst.Tag.div_float_optimized,
        .Strict => Air.Inst.Tag.div_float,
    };
    return block.addBinOp(air_tag, casted_lhs, casted_rhs);
}

fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const is_vector = resolved_type.zigTypeTag() == .Vector;

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const lhs_scalar_ty = lhs_ty.scalarType();
    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .div_exact);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    const runtime_src = rs: {
        // For integers:
        // If the lhs is zero, then zero is returned regardless of rhs.
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, compile error because there is a possible
        // value for which the division would result in a remainder.
        // TODO: emit runtime safety for if there is a remainder
        // TODO: emit runtime safety for division by zero
        //
        // For floats:
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, compile error because there is a possible
        // value for which the division would result in a remainder.
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            } else {
                if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                    const zero_val = if (is_vector) b: {
                        break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                    } else Value.zero;
                    return sema.addConstant(resolved_type, zero_val);
                }
            }
        }
        if (maybe_rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                return sema.failWithDivideByZero(block, rhs_src);
            }
            // TODO: if the RHS is one, return the LHS directly
        }
        if (maybe_lhs_val) |lhs_val| {
            if (maybe_rhs_val) |rhs_val| {
                if (is_int) {
                    const modulus_val = try lhs_val.intMod(rhs_val, resolved_type, sema.arena, mod);
                    if (!(modulus_val.compareAllWithZero(.eq, mod))) {
                        return sema.fail(block, src, "exact division produced remainder", .{});
                    }
                    const res = try lhs_val.intDiv(rhs_val, resolved_type, sema.arena, mod);
                    var vector_index: usize = undefined;
                    if (!(try sema.intFitsInType(res, resolved_type, &vector_index))) {
                        return sema.failWithIntegerOverflow(block, src, resolved_type, res, vector_index);
                    }
                    return sema.addConstant(resolved_type, res);
                } else {
                    const modulus_val = try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, mod);
                    if (!(modulus_val.compareAllWithZero(.eq, mod))) {
                        return sema.fail(block, src, "exact division produced remainder", .{});
                    }
                    return sema.addConstant(
                        resolved_type,
                        try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, mod),
                    );
                }
            } else break :rs rhs_src;
        } else break :rs lhs_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    // Depending on whether safety is enabled, we will have a slightly different strategy
    // here. The `div_exact` AIR instruction causes undefined behavior if a remainder
    // is produced, so in the safety check case, it cannot be used. Instead we do a
    // div_trunc and check for remainder.

    if (block.wantSafety()) {
        try sema.addDivIntOverflowSafety(block, resolved_type, lhs_scalar_ty, maybe_lhs_val, maybe_rhs_val, casted_lhs, casted_rhs, is_int);
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);

        const result = try block.addBinOp(.div_trunc, casted_lhs, casted_rhs);
        const ok = if (!is_int) ok: {
            const floored = try block.addUnOp(.floor, result);

            if (resolved_type.zigTypeTag() == .Vector) {
                const eql = try block.addCmpVector(result, floored, .eq);
                break :ok try block.addInst(.{
                    .tag = switch (block.float_mode) {
                        .Strict => .reduce,
                        .Optimized => .reduce_optimized,
                    },
                    .data = .{ .reduce = .{
                        .operand = eql,
                        .operation = .And,
                    } },
                });
            } else {
                const is_in_range = try block.addBinOp(switch (block.float_mode) {
                    .Strict => .cmp_eq,
                    .Optimized => .cmp_eq_optimized,
                }, result, floored);
                break :ok is_in_range;
            }
        } else ok: {
            const remainder = try block.addBinOp(.rem, casted_lhs, casted_rhs);

            if (resolved_type.zigTypeTag() == .Vector) {
                const zero_val = try Value.Tag.repeated.create(sema.arena, Value.zero);
                const zero = try sema.addConstant(resolved_type, zero_val);
                const eql = try block.addCmpVector(remainder, zero, .eq);
                break :ok try block.addInst(.{
                    .tag = .reduce,
                    .data = .{ .reduce = .{
                        .operand = eql,
                        .operation = .And,
                    } },
                });
            } else {
                const zero = try sema.addConstant(resolved_type, Value.zero);
                const is_in_range = try block.addBinOp(.cmp_eq, remainder, zero);
                break :ok is_in_range;
            }
        };
        try sema.addSafetyCheck(block, ok, .exact_division_remainder);
        return result;
    }

    return block.addBinOp(airTag(block, is_int, .div_exact, .div_exact_optimized), casted_lhs, casted_rhs);
}

fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const is_vector = resolved_type.zigTypeTag() == .Vector;

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const lhs_scalar_ty = lhs_ty.scalarType();
    const rhs_scalar_ty = rhs_ty.scalarType();
    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .div_floor);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    const runtime_src = rs: {
        // For integers:
        // If the lhs is zero, then zero is returned regardless of rhs.
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined:
        //   * if lhs type is signed:
        //     * if rhs is comptime-known and not -1, result is undefined
        //     * if rhs is -1 or runtime-known, compile error because there is a
        //        possible value (-min_int / -1)  for which division would be
        //        illegal behavior.
        //   * if lhs type is unsigned, undef is returned regardless of rhs.
        // TODO: emit runtime safety for division by zero
        //
        // For floats:
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, result is undefined.
        if (maybe_lhs_val) |lhs_val| {
            if (!lhs_val.isUndef()) {
                if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                    const zero_val = if (is_vector) b: {
                        break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                    } else Value.zero;
                    return sema.addConstant(resolved_type, zero_val);
                }
            }
        }
        if (maybe_rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                return sema.failWithDivideByZero(block, rhs_src);
            }
            // TODO: if the RHS is one, return the LHS directly
        }
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                if (lhs_scalar_ty.isSignedInt() and rhs_scalar_ty.isSignedInt()) {
                    if (maybe_rhs_val) |rhs_val| {
                        if (try sema.compareAll(rhs_val, .neq, Value.negative_one, resolved_type)) {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                return sema.addConstUndef(resolved_type);
            }

            if (maybe_rhs_val) |rhs_val| {
                if (is_int) {
                    return sema.addConstant(
                        resolved_type,
                        try lhs_val.intDivFloor(rhs_val, resolved_type, sema.arena, mod),
                    );
                } else {
                    return sema.addConstant(
                        resolved_type,
                        try lhs_val.floatDivFloor(rhs_val, resolved_type, sema.arena, mod),
                    );
                }
            } else break :rs rhs_src;
        } else break :rs lhs_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (block.wantSafety()) {
        try sema.addDivIntOverflowSafety(block, resolved_type, lhs_scalar_ty, maybe_lhs_val, maybe_rhs_val, casted_lhs, casted_rhs, is_int);
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
    }

    return block.addBinOp(airTag(block, is_int, .div_floor, .div_floor_optimized), casted_lhs, casted_rhs);
}

fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const is_vector = resolved_type.zigTypeTag() == .Vector;

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const lhs_scalar_ty = lhs_ty.scalarType();
    const rhs_scalar_ty = rhs_ty.scalarType();
    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .div_trunc);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    const runtime_src = rs: {
        // For integers:
        // If the lhs is zero, then zero is returned regardless of rhs.
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined:
        //   * if lhs type is signed:
        //     * if rhs is comptime-known and not -1, result is undefined
        //     * if rhs is -1 or runtime-known, compile error because there is a
        //        possible value (-min_int / -1)  for which division would be
        //        illegal behavior.
        //   * if lhs type is unsigned, undef is returned regardless of rhs.
        // TODO: emit runtime safety for division by zero
        //
        // For floats:
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, result is undefined.
        if (maybe_lhs_val) |lhs_val| {
            if (!lhs_val.isUndef()) {
                if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                    const zero_val = if (is_vector) b: {
                        break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                    } else Value.zero;
                    return sema.addConstant(resolved_type, zero_val);
                }
            }
        }
        if (maybe_rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                return sema.failWithDivideByZero(block, rhs_src);
            }
        }
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                if (lhs_scalar_ty.isSignedInt() and rhs_scalar_ty.isSignedInt()) {
                    if (maybe_rhs_val) |rhs_val| {
                        if (try sema.compareAll(rhs_val, .neq, Value.negative_one, resolved_type)) {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                return sema.addConstUndef(resolved_type);
            }

            if (maybe_rhs_val) |rhs_val| {
                if (is_int) {
                    const res = try lhs_val.intDiv(rhs_val, resolved_type, sema.arena, mod);
                    var vector_index: usize = undefined;
                    if (!(try sema.intFitsInType(res, resolved_type, &vector_index))) {
                        return sema.failWithIntegerOverflow(block, src, resolved_type, res, vector_index);
                    }
                    return sema.addConstant(resolved_type, res);
                } else {
                    return sema.addConstant(
                        resolved_type,
                        try lhs_val.floatDivTrunc(rhs_val, resolved_type, sema.arena, mod),
                    );
                }
            } else break :rs rhs_src;
        } else break :rs lhs_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (block.wantSafety()) {
        try sema.addDivIntOverflowSafety(block, resolved_type, lhs_scalar_ty, maybe_lhs_val, maybe_rhs_val, casted_lhs, casted_rhs, is_int);
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
    }

    return block.addBinOp(airTag(block, is_int, .div_trunc, .div_trunc_optimized), casted_lhs, casted_rhs);
}

fn addDivIntOverflowSafety(
    sema: *Sema,
    block: *Block,
    resolved_type: Type,
    lhs_scalar_ty: Type,
    maybe_lhs_val: ?Value,
    maybe_rhs_val: ?Value,
    casted_lhs: Air.Inst.Ref,
    casted_rhs: Air.Inst.Ref,
    is_int: bool,
) CompileError!void {
    if (!is_int) return;

    // If the LHS is unsigned, it cannot cause overflow.
    if (!lhs_scalar_ty.isSignedInt()) return;

    const mod = sema.mod;
    const target = mod.getTarget();

    // If the LHS is widened to a larger integer type, no overflow is possible.
    if (lhs_scalar_ty.intInfo(target).bits < resolved_type.intInfo(target).bits) {
        return;
    }

    const min_int = try resolved_type.minInt(sema.arena, target);
    const neg_one_scalar = try Value.Tag.int_i64.create(sema.arena, -1);
    const neg_one = if (resolved_type.zigTypeTag() == .Vector)
        try Value.Tag.repeated.create(sema.arena, neg_one_scalar)
    else
        neg_one_scalar;

    // If the LHS is comptime-known to be not equal to the min int,
    // no overflow is possible.
    if (maybe_lhs_val) |lhs_val| {
        if (lhs_val.compareAll(.neq, min_int, resolved_type, mod)) return;
    }

    // If the RHS is comptime-known to not be equal to -1, no overflow is possible.
    if (maybe_rhs_val) |rhs_val| {
        if (rhs_val.compareAll(.neq, neg_one, resolved_type, mod)) return;
    }

    var ok: Air.Inst.Ref = .none;
    if (resolved_type.zigTypeTag() == .Vector) {
        if (maybe_lhs_val == null) {
            const min_int_ref = try sema.addConstant(resolved_type, min_int);
            ok = try block.addCmpVector(casted_lhs, min_int_ref, .neq);
        }
        if (maybe_rhs_val == null) {
            const neg_one_ref = try sema.addConstant(resolved_type, neg_one);
            const rhs_ok = try block.addCmpVector(casted_rhs, neg_one_ref, .neq);
            if (ok == .none) {
                ok = rhs_ok;
            } else {
                ok = try block.addBinOp(.bool_or, ok, rhs_ok);
            }
        }
        assert(ok != .none);
        ok = try block.addInst(.{
            .tag = .reduce,
            .data = .{ .reduce = .{
                .operand = ok,
                .operation = .And,
            } },
        });
    } else {
        if (maybe_lhs_val == null) {
            const min_int_ref = try sema.addConstant(resolved_type, min_int);
            ok = try block.addBinOp(.cmp_neq, casted_lhs, min_int_ref);
        }
        if (maybe_rhs_val == null) {
            const neg_one_ref = try sema.addConstant(resolved_type, neg_one);
            const rhs_ok = try block.addBinOp(.cmp_neq, casted_rhs, neg_one_ref);
            if (ok == .none) {
                ok = rhs_ok;
            } else {
                ok = try block.addBinOp(.bool_or, ok, rhs_ok);
            }
        }
        assert(ok != .none);
    }
    try sema.addSafetyCheck(block, ok, .integer_overflow);
}

fn addDivByZeroSafety(
    sema: *Sema,
    block: *Block,
    resolved_type: Type,
    maybe_rhs_val: ?Value,
    casted_rhs: Air.Inst.Ref,
    is_int: bool,
) CompileError!void {
    // Strict IEEE floats have well-defined division by zero.
    if (!is_int and block.float_mode == .Strict) return;

    // If rhs was comptime-known to be zero a compile error would have been
    // emitted above.
    if (maybe_rhs_val != null) return;

    const ok = if (resolved_type.zigTypeTag() == .Vector) ok: {
        const zero_val = try Value.Tag.repeated.create(sema.arena, Value.zero);
        const zero = try sema.addConstant(resolved_type, zero_val);
        const ok = try block.addCmpVector(casted_rhs, zero, .neq);
        break :ok try block.addInst(.{
            .tag = if (is_int) .reduce else .reduce_optimized,
            .data = .{ .reduce = .{
                .operand = ok,
                .operation = .And,
            } },
        });
    } else ok: {
        const zero = try sema.addConstant(resolved_type, Value.zero);
        break :ok try block.addBinOp(if (is_int) .cmp_neq else .cmp_neq_optimized, casted_rhs, zero);
    };
    try sema.addSafetyCheck(block, ok, .divide_by_zero);
}

fn airTag(block: *Block, is_int: bool, normal: Air.Inst.Tag, optimized: Air.Inst.Tag) Air.Inst.Tag {
    if (is_int) return normal;
    return switch (block.float_mode) {
        .Strict => normal,
        .Optimized => optimized,
    };
}

fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const is_vector = resolved_type.zigTypeTag() == .Vector;

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const lhs_scalar_ty = lhs_ty.scalarType();
    const rhs_scalar_ty = rhs_ty.scalarType();
    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .mod_rem);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    const runtime_src = rs: {
        // For integers:
        // Either operand being undef is a compile error because there exists
        // a possible value (TODO what is it?) that would invoke illegal behavior.
        // TODO: can lhs undef be handled better?
        //
        // For floats:
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, result is undefined.
        //
        // For either one: if the result would be different between @mod and @rem,
        // then emit a compile error saying you have to pick one.
        if (is_int) {
            if (maybe_lhs_val) |lhs_val| {
                if (lhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, lhs_src);
                }
                if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                    const zero_val = if (is_vector) b: {
                        break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                    } else Value.zero;
                    return sema.addConstant(resolved_type, zero_val);
                }
            } else if (lhs_scalar_ty.isSignedInt()) {
                return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
            }
            if (maybe_rhs_val) |rhs_val| {
                if (rhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                    return sema.failWithDivideByZero(block, rhs_src);
                }
                if (!(try rhs_val.compareAllWithZeroAdvanced(.gte, sema))) {
                    return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
                }
                if (maybe_lhs_val) |lhs_val| {
                    const rem_result = try sema.intRem(resolved_type, lhs_val, rhs_val);
                    // If this answer could possibly be different by doing `intMod`,
                    // we must emit a compile error. Otherwise, it's OK.
                    if (!(try lhs_val.compareAllWithZeroAdvanced(.gte, sema)) and
                        !(try rem_result.compareAllWithZeroAdvanced(.eq, sema)))
                    {
                        return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
                    }
                    return sema.addConstant(resolved_type, rem_result);
                }
                break :rs lhs_src;
            } else if (rhs_scalar_ty.isSignedInt()) {
                return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
            } else {
                break :rs rhs_src;
            }
        }
        // float operands
        if (maybe_rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                return sema.failWithDivideByZero(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.gte, sema))) {
                return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
            }
            if (maybe_lhs_val) |lhs_val| {
                if (lhs_val.isUndef() or !(try lhs_val.compareAllWithZeroAdvanced(.gte, sema))) {
                    return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
                }
                return sema.addConstant(
                    resolved_type,
                    try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod),
                );
            } else {
                return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
            }
        } else {
            return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
        }
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (block.wantSafety()) {
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
    }

    const air_tag = airTag(block, is_int, .rem, .rem_optimized);
    return block.addBinOp(air_tag, casted_lhs, casted_rhs);
}

fn intRem(
    sema: *Sema,
    ty: Type,
    lhs: Value,
    rhs: Value,
) CompileError!Value {
    if (ty.zigTypeTag() == .Vector) {
        const result_data = try sema.arena.alloc(Value, ty.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            scalar.* = try sema.intRemScalar(lhs_elem, rhs_elem);
        }
        return Value.Tag.aggregate.create(sema.arena, result_data);
    }
    return sema.intRemScalar(lhs, rhs);
}

fn intRemScalar(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
) CompileError!Value {
    const target = sema.mod.getTarget();
    // 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 = try lhs.toBigIntAdvanced(&lhs_space, target, sema);
    const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, target, sema);
    const limbs_q = try sema.arena.alloc(
        math.big.Limb,
        lhs_bigint.limbs.len,
    );
    const limbs_r = try sema.arena.alloc(
        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 sema.arena.alloc(
        math.big.Limb,
        math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
    );
    var result_q = math.big.int.Mutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
    var result_r = math.big.int.Mutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
    result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
    return Value.fromBigInt(sema.arena, result_r.toConst());
}

fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .mod);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    const runtime_src = rs: {
        // For integers:
        // Either operand being undef is a compile error because there exists
        // a possible value (TODO what is it?) that would invoke illegal behavior.
        // TODO: can lhs zero be handled better?
        // TODO: can lhs undef be handled better?
        //
        // For floats:
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, result is undefined.
        if (is_int) {
            if (maybe_lhs_val) |lhs_val| {
                if (lhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, lhs_src);
                }
            }
            if (maybe_rhs_val) |rhs_val| {
                if (rhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                    return sema.failWithDivideByZero(block, rhs_src);
                }
                if (maybe_lhs_val) |lhs_val| {
                    return sema.addConstant(
                        resolved_type,
                        try lhs_val.intMod(rhs_val, resolved_type, sema.arena, mod),
                    );
                }
                break :rs lhs_src;
            } else {
                break :rs rhs_src;
            }
        }
        // float operands
        if (maybe_rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                return sema.failWithDivideByZero(block, rhs_src);
            }
        }
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                return sema.addConstUndef(resolved_type);
            }
            if (maybe_rhs_val) |rhs_val| {
                return sema.addConstant(
                    resolved_type,
                    try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, mod),
                );
            } else break :rs rhs_src;
        } else break :rs lhs_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (block.wantSafety()) {
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
    }

    const air_tag = airTag(block, is_int, .mod, .mod_optimized);
    return block.addBinOp(air_tag, casted_lhs, casted_rhs);
}

fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    try sema.checkInvalidPtrArithmetic(block, src, lhs_ty);

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, .rem);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);

    const runtime_src = rs: {
        // For integers:
        // Either operand being undef is a compile error because there exists
        // a possible value (TODO what is it?) that would invoke illegal behavior.
        // TODO: can lhs zero be handled better?
        // TODO: can lhs undef be handled better?
        //
        // For floats:
        // If the rhs is zero, compile error for division by zero.
        // If the rhs is undefined, compile error because there is a possible
        // value (zero) for which the division would be illegal behavior.
        // If the lhs is undefined, result is undefined.
        if (is_int) {
            if (maybe_lhs_val) |lhs_val| {
                if (lhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, lhs_src);
                }
            }
            if (maybe_rhs_val) |rhs_val| {
                if (rhs_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, rhs_src);
                }
                if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                    return sema.failWithDivideByZero(block, rhs_src);
                }
                if (maybe_lhs_val) |lhs_val| {
                    return sema.addConstant(
                        resolved_type,
                        try sema.intRem(resolved_type, lhs_val, rhs_val),
                    );
                }
                break :rs lhs_src;
            } else {
                break :rs rhs_src;
            }
        }
        // float operands
        if (maybe_rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) {
                return sema.failWithUseOfUndef(block, rhs_src);
            }
            if (!(try rhs_val.compareAllWithZeroAdvanced(.neq, sema))) {
                return sema.failWithDivideByZero(block, rhs_src);
            }
        }
        if (maybe_lhs_val) |lhs_val| {
            if (lhs_val.isUndef()) {
                return sema.addConstUndef(resolved_type);
            }
            if (maybe_rhs_val) |rhs_val| {
                return sema.addConstant(
                    resolved_type,
                    try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod),
                );
            } else break :rs rhs_src;
        } else break :rs lhs_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (block.wantSafety()) {
        try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
    }

    const air_tag = airTag(block, is_int, .rem, .rem_optimized);
    return block.addBinOp(air_tag, casted_lhs, casted_rhs);
}

fn zirOverflowArithmetic(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
    zir_tag: Zir.Inst.Extended,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);

    const lhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const rhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };

    const uncasted_lhs = try sema.resolveInst(extra.lhs);
    const uncasted_rhs = try sema.resolveInst(extra.rhs);

    const lhs_ty = sema.typeOf(uncasted_lhs);
    const rhs_ty = sema.typeOf(uncasted_rhs);
    const mod = sema.mod;

    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);

    const instructions = &[_]Air.Inst.Ref{ uncasted_lhs, uncasted_rhs };
    const dest_ty = if (zir_tag == .shl_with_overflow)
        lhs_ty
    else
        try sema.resolvePeerTypes(block, src, instructions, .{
            .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
        });

    const rhs_dest_ty = if (zir_tag == .shl_with_overflow)
        try sema.log2IntType(block, lhs_ty, src)
    else
        dest_ty;

    const lhs = try sema.coerce(block, dest_ty, uncasted_lhs, lhs_src);
    const rhs = try sema.coerce(block, rhs_dest_ty, uncasted_rhs, rhs_src);

    if (dest_ty.scalarType().zigTypeTag() != .Int) {
        return sema.fail(block, src, "expected vector of integers or integer tag type, found '{}'", .{dest_ty.fmt(mod)});
    }

    const maybe_lhs_val = try sema.resolveMaybeUndefVal(lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefVal(rhs);

    const tuple_ty = try sema.overflowArithmeticTupleType(dest_ty);

    var result: struct {
        inst: Air.Inst.Ref = .none,
        wrapped: Value = Value.initTag(.unreachable_value),
        overflow_bit: Value,
    } = result: {
        switch (zir_tag) {
            .add_with_overflow => {
                // If either of the arguments is zero, `false` is returned and the other is stored
                // to the result, even if it is undefined..
                // Otherwise, if either of the argument is undefined, undefined is returned.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef() and (try lhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = rhs };
                    }
                }
                if (maybe_rhs_val) |rhs_val| {
                    if (!rhs_val.isUndef() and (try rhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = lhs };
                    }
                }
                if (maybe_lhs_val) |lhs_val| {
                    if (maybe_rhs_val) |rhs_val| {
                        if (lhs_val.isUndef() or rhs_val.isUndef()) {
                            break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
                        }

                        const result = try sema.intAddWithOverflow(lhs_val, rhs_val, dest_ty);
                        break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
                    }
                }
            },
            .sub_with_overflow => {
                // If the rhs is zero, then the result is lhs and no overflow occured.
                // Otherwise, if either result is undefined, both results are undefined.
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
                    } else if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = lhs };
                    } else if (maybe_lhs_val) |lhs_val| {
                        if (lhs_val.isUndef()) {
                            break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
                        }

                        const result = try sema.intSubWithOverflow(lhs_val, rhs_val, dest_ty);
                        break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
                    }
                }
            },
            .mul_with_overflow => {
                // If either of the arguments is zero, the result is zero and no overflow occured.
                // If either of the arguments is one, the result is the other and no overflow occured.
                // Otherwise, if either of the arguments is undefined, both results are undefined.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef()) {
                        if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                            break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = lhs };
                        } else if (try sema.compareAll(lhs_val, .eq, try maybeRepeated(sema, dest_ty, Value.one), dest_ty)) {
                            break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = rhs };
                        }
                    }
                }

                if (maybe_rhs_val) |rhs_val| {
                    if (!rhs_val.isUndef()) {
                        if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                            break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = rhs };
                        } else if (try sema.compareAll(rhs_val, .eq, try maybeRepeated(sema, dest_ty, Value.one), dest_ty)) {
                            break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = lhs };
                        }
                    }
                }

                if (maybe_lhs_val) |lhs_val| {
                    if (maybe_rhs_val) |rhs_val| {
                        if (lhs_val.isUndef() or rhs_val.isUndef()) {
                            break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
                        }

                        const result = try lhs_val.intMulWithOverflow(rhs_val, dest_ty, sema.arena, mod);
                        break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
                    }
                }
            },
            .shl_with_overflow => {
                // If lhs is zero, the result is zero and no overflow occurred.
                // If rhs is zero, the result is lhs (even if undefined) and no overflow occurred.
                // Oterhwise if either of the arguments is undefined, both results are undefined.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef() and (try lhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = lhs };
                    }
                }
                if (maybe_rhs_val) |rhs_val| {
                    if (!rhs_val.isUndef() and (try rhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        break :result .{ .overflow_bit = try maybeRepeated(sema, dest_ty, Value.zero), .inst = lhs };
                    }
                }
                if (maybe_lhs_val) |lhs_val| {
                    if (maybe_rhs_val) |rhs_val| {
                        if (lhs_val.isUndef() or rhs_val.isUndef()) {
                            break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
                        }

                        const result = try lhs_val.shlWithOverflow(rhs_val, dest_ty, sema.arena, sema.mod);
                        break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
                    }
                }
            },
            else => unreachable,
        }

        const air_tag: Air.Inst.Tag = switch (zir_tag) {
            .add_with_overflow => .add_with_overflow,
            .mul_with_overflow => .mul_with_overflow,
            .sub_with_overflow => .sub_with_overflow,
            .shl_with_overflow => .shl_with_overflow,
            else => unreachable,
        };

        const runtime_src = if (maybe_lhs_val == null) lhs_src else rhs_src;
        try sema.requireRuntimeBlock(block, src, runtime_src);

        return block.addInst(.{
            .tag = air_tag,
            .data = .{ .ty_pl = .{
                .ty = try block.sema.addType(tuple_ty),
                .payload = try block.sema.addExtra(Air.Bin{
                    .lhs = lhs,
                    .rhs = rhs,
                }),
            } },
        });
    };

    if (result.inst != .none) {
        if (try sema.resolveMaybeUndefVal(result.inst)) |some| {
            result.wrapped = some;
            result.inst = .none;
        }
    }

    if (result.inst == .none) {
        const values = try sema.arena.alloc(Value, 2);
        values[0] = result.wrapped;
        values[1] = result.overflow_bit;
        const tuple_val = try Value.Tag.aggregate.create(sema.arena, values);
        return sema.addConstant(tuple_ty, tuple_val);
    }

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, 2);
    element_refs[0] = result.inst;
    element_refs[1] = try sema.addConstant(tuple_ty.structFieldType(1), result.overflow_bit);
    return block.addAggregateInit(tuple_ty, element_refs);
}

fn maybeRepeated(sema: *Sema, ty: Type, val: Value) !Value {
    if (ty.zigTypeTag() != .Vector) return val;
    return Value.Tag.repeated.create(sema.arena, val);
}

fn overflowArithmeticTupleType(sema: *Sema, ty: Type) !Type {
    const ov_ty = if (ty.zigTypeTag() == .Vector) try Type.vector(sema.arena, ty.vectorLen(), Type.u1) else Type.u1;

    const types = try sema.arena.alloc(Type, 2);
    const values = try sema.arena.alloc(Value, 2);
    const tuple_ty = try Type.Tag.tuple.create(sema.arena, .{
        .types = types,
        .values = values,
    });

    types[0] = ty;
    types[1] = ov_ty;
    values[0] = Value.initTag(.unreachable_value);
    values[1] = Value.initTag(.unreachable_value);

    return tuple_ty;
}

fn analyzeArithmetic(
    sema: *Sema,
    block: *Block,
    /// TODO performance investigation: make this comptime?
    zir_tag: Zir.Inst.Tag,
    lhs: Air.Inst.Ref,
    rhs: Air.Inst.Ref,
    src: LazySrcLoc,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
    want_safety: bool,
) CompileError!Air.Inst.Ref {
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);

    if (lhs_zig_ty_tag == .Pointer) switch (lhs_ty.ptrSize()) {
        .One, .Slice => {},
        .Many, .C => {
            const air_tag: Air.Inst.Tag = switch (zir_tag) {
                .add => .ptr_add,
                .sub => .ptr_sub,
                else => return sema.fail(block, src, "invalid pointer arithmetic operator", .{}),
            };
            return sema.analyzePtrArithmetic(block, src, lhs, rhs, air_tag, lhs_src, rhs_src);
        },
    };

    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });

    const is_vector = resolved_type.zigTypeTag() == .Vector;

    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);

    const scalar_tag = resolved_type.scalarType().zigTypeTag();

    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;

    try sema.checkArithmeticOp(block, src, scalar_tag, lhs_zig_ty_tag, rhs_zig_ty_tag, zir_tag);

    const mod = sema.mod;
    const maybe_lhs_val = try sema.resolveMaybeUndefValIntable(casted_lhs);
    const maybe_rhs_val = try sema.resolveMaybeUndefValIntable(casted_rhs);
    const rs: struct { src: LazySrcLoc, air_tag: Air.Inst.Tag } = rs: {
        switch (zir_tag) {
            .add, .add_unsafe => {
                // For integers:intAddSat
                // If either of the operands are zero, then the other operand is
                // returned, even if it is undefined.
                // If either of the operands are undefined, it's a compile error
                // because there is a possible value for which the addition would
                // overflow (max_int), causing illegal behavior.
                // For floats: either operand being undef makes the result undef.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef() and (try lhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        return casted_rhs;
                    }
                }
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        if (is_int) {
                            return sema.failWithUseOfUndef(block, rhs_src);
                        } else {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        return casted_lhs;
                    }
                }
                const air_tag: Air.Inst.Tag = if (block.float_mode == .Optimized) .add_optimized else .add;
                if (maybe_lhs_val) |lhs_val| {
                    if (lhs_val.isUndef()) {
                        if (is_int) {
                            return sema.failWithUseOfUndef(block, lhs_src);
                        } else {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    if (maybe_rhs_val) |rhs_val| {
                        if (is_int) {
                            const sum = try sema.intAdd(lhs_val, rhs_val, resolved_type);
                            var vector_index: usize = undefined;
                            if (!(try sema.intFitsInType(sum, resolved_type, &vector_index))) {
                                return sema.failWithIntegerOverflow(block, src, resolved_type, sum, vector_index);
                            }
                            return sema.addConstant(resolved_type, sum);
                        } else {
                            return sema.addConstant(
                                resolved_type,
                                try sema.floatAdd(lhs_val, rhs_val, resolved_type),
                            );
                        }
                    } else break :rs .{ .src = rhs_src, .air_tag = air_tag };
                } else break :rs .{ .src = lhs_src, .air_tag = air_tag };
            },
            .addwrap => {
                // Integers only; floats are checked above.
                // If either of the operands are zero, the other operand is returned.
                // If either of the operands are undefined, the result is undefined.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef() and (try lhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        return casted_rhs;
                    }
                }
                const air_tag: Air.Inst.Tag = if (block.float_mode == .Optimized) .addwrap_optimized else .addwrap;
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        return casted_lhs;
                    }
                    if (maybe_lhs_val) |lhs_val| {
                        return sema.addConstant(
                            resolved_type,
                            try sema.numberAddWrapScalar(lhs_val, rhs_val, resolved_type),
                        );
                    } else break :rs .{ .src = lhs_src, .air_tag = air_tag };
                } else break :rs .{ .src = rhs_src, .air_tag = air_tag };
            },
            .add_sat => {
                // Integers only; floats are checked above.
                // If either of the operands are zero, then the other operand is returned.
                // If either of the operands are undefined, the result is undefined.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef() and (try lhs_val.compareAllWithZeroAdvanced(.eq, sema))) {
                        return casted_rhs;
                    }
                }
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        return casted_lhs;
                    }
                    if (maybe_lhs_val) |lhs_val| {
                        const val = if (scalar_tag == .ComptimeInt)
                            try sema.intAdd(lhs_val, rhs_val, resolved_type)
                        else
                            try lhs_val.intAddSat(rhs_val, resolved_type, sema.arena, mod);

                        return sema.addConstant(resolved_type, val);
                    } else break :rs .{ .src = lhs_src, .air_tag = .add_sat };
                } else break :rs .{ .src = rhs_src, .air_tag = .add_sat };
            },
            .sub => {
                // For integers:
                // If the rhs is zero, then the other operand is
                // returned, even if it is undefined.
                // If either of the operands are undefined, it's a compile error
                // because there is a possible value for which the subtraction would
                // overflow, causing illegal behavior.
                // For floats: either operand being undef makes the result undef.
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        if (is_int) {
                            return sema.failWithUseOfUndef(block, rhs_src);
                        } else {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        return casted_lhs;
                    }
                }
                const air_tag: Air.Inst.Tag = if (block.float_mode == .Optimized) .sub_optimized else .sub;
                if (maybe_lhs_val) |lhs_val| {
                    if (lhs_val.isUndef()) {
                        if (is_int) {
                            return sema.failWithUseOfUndef(block, lhs_src);
                        } else {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    if (maybe_rhs_val) |rhs_val| {
                        if (is_int) {
                            const diff = try sema.intSub(lhs_val, rhs_val, resolved_type);
                            var vector_index: usize = undefined;
                            if (!(try sema.intFitsInType(diff, resolved_type, &vector_index))) {
                                return sema.failWithIntegerOverflow(block, src, resolved_type, diff, vector_index);
                            }
                            return sema.addConstant(resolved_type, diff);
                        } else {
                            return sema.addConstant(
                                resolved_type,
                                try sema.floatSub(lhs_val, rhs_val, resolved_type),
                            );
                        }
                    } else break :rs .{ .src = rhs_src, .air_tag = air_tag };
                } else break :rs .{ .src = lhs_src, .air_tag = air_tag };
            },
            .subwrap => {
                // Integers only; floats are checked above.
                // If the RHS is zero, then the other operand is returned, even if it is undefined.
                // If either of the operands are undefined, the result is undefined.
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        return casted_lhs;
                    }
                }
                const air_tag: Air.Inst.Tag = if (block.float_mode == .Optimized) .subwrap_optimized else .subwrap;
                if (maybe_lhs_val) |lhs_val| {
                    if (lhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (maybe_rhs_val) |rhs_val| {
                        return sema.addConstant(
                            resolved_type,
                            try sema.numberSubWrapScalar(lhs_val, rhs_val, resolved_type),
                        );
                    } else break :rs .{ .src = rhs_src, .air_tag = air_tag };
                } else break :rs .{ .src = lhs_src, .air_tag = air_tag };
            },
            .sub_sat => {
                // Integers only; floats are checked above.
                // If the RHS is zero, result is LHS.
                // If either of the operands are undefined, result is undefined.
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        return casted_lhs;
                    }
                }
                if (maybe_lhs_val) |lhs_val| {
                    if (lhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (maybe_rhs_val) |rhs_val| {
                        const val = if (scalar_tag == .ComptimeInt)
                            try sema.intSub(lhs_val, rhs_val, resolved_type)
                        else
                            try lhs_val.intSubSat(rhs_val, resolved_type, sema.arena, mod);

                        return sema.addConstant(resolved_type, val);
                    } else break :rs .{ .src = rhs_src, .air_tag = .sub_sat };
                } else break :rs .{ .src = lhs_src, .air_tag = .sub_sat };
            },
            .mul => {
                // For integers:
                // If either of the operands are zero, the result is zero.
                // If either of the operands are one, the result is the other
                // operand, even if it is undefined.
                // If either of the operands are undefined, it's a compile error
                // because there is a possible value for which the addition would
                // overflow (max_int), causing illegal behavior.
                // For floats: either operand being undef makes the result undef.
                // If either of the operands are inf, and the other operand is zero,
                // the result is nan.
                // If either of the operands are nan, the result is nan.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef()) {
                        if (lhs_val.isNan()) {
                            return sema.addConstant(resolved_type, lhs_val);
                        }
                        if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) lz: {
                            if (maybe_rhs_val) |rhs_val| {
                                if (rhs_val.isNan()) {
                                    return sema.addConstant(resolved_type, rhs_val);
                                }
                                if (rhs_val.isInf()) {
                                    return sema.addConstant(resolved_type, try Value.Tag.float_32.create(sema.arena, std.math.nan_f32));
                                }
                            } else if (resolved_type.isAnyFloat()) {
                                break :lz;
                            }
                            const zero_val = if (is_vector) b: {
                                break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                            } else Value.zero;
                            return sema.addConstant(resolved_type, zero_val);
                        }
                        if (try sema.compareAll(lhs_val, .eq, Value.one, resolved_type)) {
                            return casted_rhs;
                        }
                    }
                }
                const air_tag: Air.Inst.Tag = if (block.float_mode == .Optimized) .mul_optimized else .mul;
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        if (is_int) {
                            return sema.failWithUseOfUndef(block, rhs_src);
                        } else {
                            return sema.addConstUndef(resolved_type);
                        }
                    }
                    if (rhs_val.isNan()) {
                        return sema.addConstant(resolved_type, rhs_val);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) rz: {
                        if (maybe_lhs_val) |lhs_val| {
                            if (lhs_val.isInf()) {
                                return sema.addConstant(resolved_type, try Value.Tag.float_32.create(sema.arena, std.math.nan_f32));
                            }
                        } else if (resolved_type.isAnyFloat()) {
                            break :rz;
                        }
                        const zero_val = if (is_vector) b: {
                            break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                        } else Value.zero;
                        return sema.addConstant(resolved_type, zero_val);
                    }
                    if (try sema.compareAll(rhs_val, .eq, Value.one, resolved_type)) {
                        return casted_lhs;
                    }
                    if (maybe_lhs_val) |lhs_val| {
                        if (lhs_val.isUndef()) {
                            if (is_int) {
                                return sema.failWithUseOfUndef(block, lhs_src);
                            } else {
                                return sema.addConstUndef(resolved_type);
                            }
                        }
                        if (is_int) {
                            const product = try lhs_val.intMul(rhs_val, resolved_type, sema.arena, sema.mod);
                            var vector_index: usize = undefined;
                            if (!(try sema.intFitsInType(product, resolved_type, &vector_index))) {
                                return sema.failWithIntegerOverflow(block, src, resolved_type, product, vector_index);
                            }
                            return sema.addConstant(resolved_type, product);
                        } else {
                            return sema.addConstant(
                                resolved_type,
                                try lhs_val.floatMul(rhs_val, resolved_type, sema.arena, sema.mod),
                            );
                        }
                    } else break :rs .{ .src = lhs_src, .air_tag = air_tag };
                } else break :rs .{ .src = rhs_src, .air_tag = air_tag };
            },
            .mulwrap => {
                // Integers only; floats are handled above.
                // If either of the operands are zero, result is zero.
                // If either of the operands are one, result is the other operand.
                // If either of the operands are undefined, result is undefined.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef()) {
                        if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                            const zero_val = if (is_vector) b: {
                                break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                            } else Value.zero;
                            return sema.addConstant(resolved_type, zero_val);
                        }
                        if (try sema.compareAll(lhs_val, .eq, Value.one, resolved_type)) {
                            return casted_rhs;
                        }
                    }
                }
                const air_tag: Air.Inst.Tag = if (block.float_mode == .Optimized) .mulwrap_optimized else .mulwrap;
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        const zero_val = if (is_vector) b: {
                            break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                        } else Value.zero;
                        return sema.addConstant(resolved_type, zero_val);
                    }
                    if (try sema.compareAll(rhs_val, .eq, Value.one, resolved_type)) {
                        return casted_lhs;
                    }
                    if (maybe_lhs_val) |lhs_val| {
                        if (lhs_val.isUndef()) {
                            return sema.addConstUndef(resolved_type);
                        }
                        return sema.addConstant(
                            resolved_type,
                            try lhs_val.numberMulWrap(rhs_val, resolved_type, sema.arena, sema.mod),
                        );
                    } else break :rs .{ .src = lhs_src, .air_tag = air_tag };
                } else break :rs .{ .src = rhs_src, .air_tag = air_tag };
            },
            .mul_sat => {
                // Integers only; floats are checked above.
                // If either of the operands are zero, result is zero.
                // If either of the operands are one, result is the other operand.
                // If either of the operands are undefined, result is undefined.
                if (maybe_lhs_val) |lhs_val| {
                    if (!lhs_val.isUndef()) {
                        if (try lhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                            const zero_val = if (is_vector) b: {
                                break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                            } else Value.zero;
                            return sema.addConstant(resolved_type, zero_val);
                        }
                        if (try sema.compareAll(lhs_val, .eq, Value.one, resolved_type)) {
                            return casted_rhs;
                        }
                    }
                }
                if (maybe_rhs_val) |rhs_val| {
                    if (rhs_val.isUndef()) {
                        return sema.addConstUndef(resolved_type);
                    }
                    if (try rhs_val.compareAllWithZeroAdvanced(.eq, sema)) {
                        const zero_val = if (is_vector) b: {
                            break :b try Value.Tag.repeated.create(sema.arena, Value.zero);
                        } else Value.zero;
                        return sema.addConstant(resolved_type, zero_val);
                    }
                    if (try sema.compareAll(rhs_val, .eq, Value.one, resolved_type)) {
                        return casted_lhs;
                    }
                    if (maybe_lhs_val) |lhs_val| {
                        if (lhs_val.isUndef()) {
                            return sema.addConstUndef(resolved_type);
                        }

                        const val = if (scalar_tag == .ComptimeInt)
                            try lhs_val.intMul(rhs_val, resolved_type, sema.arena, sema.mod)
                        else
                            try lhs_val.intMulSat(rhs_val, resolved_type, sema.arena, sema.mod);

                        return sema.addConstant(resolved_type, val);
                    } else break :rs .{ .src = lhs_src, .air_tag = .mul_sat };
                } else break :rs .{ .src = rhs_src, .air_tag = .mul_sat };
            },
            else => unreachable,
        }
    };

    try sema.requireRuntimeBlock(block, src, rs.src);
    if (block.wantSafety() and want_safety) {
        if (scalar_tag == .Int) {
            const maybe_op_ov: ?Air.Inst.Tag = switch (rs.air_tag) {
                .add => .add_with_overflow,
                .sub => .sub_with_overflow,
                .mul => .mul_with_overflow,
                else => null,
            };
            if (maybe_op_ov) |op_ov_tag| {
                const op_ov_tuple_ty = try sema.overflowArithmeticTupleType(resolved_type);
                const op_ov = try block.addInst(.{
                    .tag = op_ov_tag,
                    .data = .{ .ty_pl = .{
                        .ty = try sema.addType(op_ov_tuple_ty),
                        .payload = try sema.addExtra(Air.Bin{
                            .lhs = casted_lhs,
                            .rhs = casted_rhs,
                        }),
                    } },
                });
                const ov_bit = try sema.tupleFieldValByIndex(block, src, op_ov, 1, op_ov_tuple_ty);
                const any_ov_bit = if (resolved_type.zigTypeTag() == .Vector)
                    try block.addInst(.{
                        .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
                        .data = .{ .reduce = .{
                            .operand = ov_bit,
                            .operation = .Or,
                        } },
                    })
                else
                    ov_bit;
                const zero_ov = try sema.addConstant(Type.u1, Value.zero);
                const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);

                try sema.addSafetyCheck(block, no_ov, .integer_overflow);
                return sema.tupleFieldValByIndex(block, src, op_ov, 0, op_ov_tuple_ty);
            }
        }
    }
    return block.addBinOp(rs.air_tag, casted_lhs, casted_rhs);
}

fn analyzePtrArithmetic(
    sema: *Sema,
    block: *Block,
    op_src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    uncasted_offset: Air.Inst.Ref,
    air_tag: Air.Inst.Tag,
    ptr_src: LazySrcLoc,
    offset_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    // TODO if the operand is comptime-known to be negative, or is a negative int,
    // coerce to isize instead of usize.
    const offset = try sema.coerce(block, Type.usize, uncasted_offset, offset_src);
    const target = sema.mod.getTarget();
    const opt_ptr_val = try sema.resolveMaybeUndefVal(ptr);
    const opt_off_val = try sema.resolveDefinedValue(block, offset_src, offset);
    const ptr_ty = sema.typeOf(ptr);
    const ptr_info = ptr_ty.ptrInfo().data;
    const elem_ty = if (ptr_info.size == .One and ptr_info.pointee_type.zigTypeTag() == .Array)
        ptr_info.pointee_type.childType()
    else
        ptr_info.pointee_type;

    const new_ptr_ty = t: {
        // Calculate the new pointer alignment.
        // This code is duplicated in `elemPtrType`.
        if (ptr_info.@"align" == 0) {
            // ABI-aligned pointer. Any pointer arithmetic maintains the same ABI-alignedness.
            break :t ptr_ty;
        }
        // If the addend is not a comptime-known value we can still count on
        // it being a multiple of the type size.
        const elem_size = elem_ty.abiSize(target);
        const addend = if (opt_off_val) |off_val| a: {
            const off_int = try sema.usizeCast(block, offset_src, off_val.toUnsignedInt(target));
            break :a elem_size * off_int;
        } else elem_size;

        // The resulting pointer is aligned to the lcd between the offset (an
        // arbitrary number) and the alignment factor (always a power of two,
        // non zero).
        const new_align = @as(u32, 1) << @intCast(u5, @ctz(addend | ptr_info.@"align"));

        break :t try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = ptr_info.pointee_type,
            .sentinel = ptr_info.sentinel,
            .@"align" = new_align,
            .@"addrspace" = ptr_info.@"addrspace",
            .mutable = ptr_info.mutable,
            .@"allowzero" = ptr_info.@"allowzero",
            .@"volatile" = ptr_info.@"volatile",
            .size = ptr_info.size,
        });
    };

    const runtime_src = rs: {
        if (opt_ptr_val) |ptr_val| {
            if (opt_off_val) |offset_val| {
                if (ptr_val.isUndef()) return sema.addConstUndef(new_ptr_ty);

                const offset_int = try sema.usizeCast(block, offset_src, offset_val.toUnsignedInt(target));
                if (offset_int == 0) return ptr;
                if (try ptr_val.getUnsignedIntAdvanced(target, sema)) |addr| {
                    const elem_size = elem_ty.abiSize(target);
                    const new_addr = switch (air_tag) {
                        .ptr_add => addr + elem_size * offset_int,
                        .ptr_sub => addr - elem_size * offset_int,
                        else => unreachable,
                    };
                    const new_ptr_val = try Value.Tag.int_u64.create(sema.arena, new_addr);
                    return sema.addConstant(new_ptr_ty, new_ptr_val);
                }
                if (air_tag == .ptr_sub) {
                    return sema.fail(block, op_src, "TODO implement Sema comptime pointer subtraction", .{});
                }
                const new_ptr_val = try ptr_val.elemPtr(ptr_ty, sema.arena, offset_int, sema.mod);
                return sema.addConstant(new_ptr_ty, new_ptr_val);
            } else break :rs offset_src;
        } else break :rs ptr_src;
    };

    try sema.requireRuntimeBlock(block, op_src, runtime_src);
    return block.addInst(.{
        .tag = air_tag,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(new_ptr_ty),
            .payload = try sema.addExtra(Air.Bin{
                .lhs = ptr,
                .rhs = offset,
            }),
        } },
    });
}

fn zirLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ptr_src = src; // TODO better source location
    const ptr = try sema.resolveInst(inst_data.operand);
    return sema.analyzeLoad(block, src, ptr, ptr_src);
}

fn zirAsm(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
    tmpl_is_expr: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.Asm, extended.operand);
    const src = LazySrcLoc.nodeOffset(extra.data.src_node);
    const ret_ty_src: LazySrcLoc = .{ .node_offset_asm_ret_ty = extra.data.src_node };
    const outputs_len = @truncate(u5, extended.small);
    const inputs_len = @truncate(u5, extended.small >> 5);
    const clobbers_len = @truncate(u5, extended.small >> 10);
    const is_volatile = @truncate(u1, extended.small >> 15) != 0;
    const is_global_assembly = sema.func == null;

    const asm_source: []const u8 = if (tmpl_is_expr) blk: {
        const tmpl = @intToEnum(Zir.Inst.Ref, extra.data.asm_source);
        const s: []const u8 = try sema.resolveConstString(block, src, tmpl, "assembly code must be comptime-known");
        break :blk s;
    } else sema.code.nullTerminatedString(extra.data.asm_source);

    if (is_global_assembly) {
        if (outputs_len != 0) {
            return sema.fail(block, src, "module-level assembly does not support outputs", .{});
        }
        if (inputs_len != 0) {
            return sema.fail(block, src, "module-level assembly does not support inputs", .{});
        }
        if (clobbers_len != 0) {
            return sema.fail(block, src, "module-level assembly does not support clobbers", .{});
        }
        if (is_volatile) {
            return sema.fail(block, src, "volatile keyword is redundant on module-level assembly", .{});
        }
        try sema.mod.addGlobalAssembly(sema.owner_decl_index, asm_source);
        return Air.Inst.Ref.void_value;
    }

    if (block.is_comptime) {
        try sema.requireRuntimeBlock(block, src, null);
    }

    var extra_i = extra.end;
    var output_type_bits = extra.data.output_type_bits;
    var needed_capacity: usize = @typeInfo(Air.Asm).Struct.fields.len + outputs_len + inputs_len;

    const ConstraintName = struct { c: []const u8, n: []const u8 };
    const out_args = try sema.arena.alloc(Air.Inst.Ref, outputs_len);
    const outputs = try sema.arena.alloc(ConstraintName, outputs_len);
    var expr_ty = Air.Inst.Ref.void_type;

    for (out_args, 0..) |*arg, out_i| {
        const output = sema.code.extraData(Zir.Inst.Asm.Output, extra_i);
        extra_i = output.end;

        const is_type = @truncate(u1, output_type_bits) != 0;
        output_type_bits >>= 1;

        if (is_type) {
            // Indicate the output is the asm instruction return value.
            arg.* = .none;
            const out_ty = try sema.resolveType(block, ret_ty_src, output.data.operand);
            try sema.queueFullTypeResolution(out_ty);
            expr_ty = try sema.addType(out_ty);
        } else {
            arg.* = try sema.resolveInst(output.data.operand);
        }

        const constraint = sema.code.nullTerminatedString(output.data.constraint);
        const name = sema.code.nullTerminatedString(output.data.name);
        needed_capacity += (constraint.len + name.len + (2 + 3)) / 4;

        outputs[out_i] = .{ .c = constraint, .n = name };
    }

    const args = try sema.arena.alloc(Air.Inst.Ref, inputs_len);
    const inputs = try sema.arena.alloc(ConstraintName, inputs_len);

    for (args, 0..) |*arg, arg_i| {
        const input = sema.code.extraData(Zir.Inst.Asm.Input, extra_i);
        extra_i = input.end;

        const uncasted_arg = try sema.resolveInst(input.data.operand);
        const uncasted_arg_ty = sema.typeOf(uncasted_arg);
        switch (uncasted_arg_ty.zigTypeTag()) {
            .ComptimeInt => arg.* = try sema.coerce(block, Type.initTag(.usize), uncasted_arg, src),
            .ComptimeFloat => arg.* = try sema.coerce(block, Type.initTag(.f64), uncasted_arg, src),
            else => {
                arg.* = uncasted_arg;
                try sema.queueFullTypeResolution(uncasted_arg_ty);
            },
        }

        const constraint = sema.code.nullTerminatedString(input.data.constraint);
        const name = sema.code.nullTerminatedString(input.data.name);
        needed_capacity += (constraint.len + name.len + (2 + 3)) / 4;
        inputs[arg_i] = .{ .c = constraint, .n = name };
    }

    const clobbers = try sema.arena.alloc([]const u8, clobbers_len);
    for (clobbers) |*name| {
        name.* = sema.code.nullTerminatedString(sema.code.extra[extra_i]);
        extra_i += 1;

        needed_capacity += name.*.len / 4 + 1;
    }

    needed_capacity += (asm_source.len + 3) / 4;

    const gpa = sema.gpa;
    try sema.air_extra.ensureUnusedCapacity(gpa, needed_capacity);
    const asm_air = try block.addInst(.{
        .tag = .assembly,
        .data = .{ .ty_pl = .{
            .ty = expr_ty,
            .payload = sema.addExtraAssumeCapacity(Air.Asm{
                .source_len = @intCast(u32, asm_source.len),
                .outputs_len = outputs_len,
                .inputs_len = @intCast(u32, args.len),
                .flags = (@as(u32, @boolToInt(is_volatile)) << 31) | @intCast(u32, clobbers.len),
            }),
        } },
    });
    sema.appendRefsAssumeCapacity(out_args);
    sema.appendRefsAssumeCapacity(args);
    for (outputs) |o| {
        const buffer = mem.sliceAsBytes(sema.air_extra.unusedCapacitySlice());
        mem.copy(u8, buffer, o.c);
        buffer[o.c.len] = 0;
        mem.copy(u8, buffer[o.c.len + 1 ..], o.n);
        buffer[o.c.len + 1 + o.n.len] = 0;
        sema.air_extra.items.len += (o.c.len + o.n.len + (2 + 3)) / 4;
    }
    for (inputs) |input| {
        const buffer = mem.sliceAsBytes(sema.air_extra.unusedCapacitySlice());
        mem.copy(u8, buffer, input.c);
        buffer[input.c.len] = 0;
        mem.copy(u8, buffer[input.c.len + 1 ..], input.n);
        buffer[input.c.len + 1 + input.n.len] = 0;
        sema.air_extra.items.len += (input.c.len + input.n.len + (2 + 3)) / 4;
    }
    for (clobbers) |clobber| {
        const buffer = mem.sliceAsBytes(sema.air_extra.unusedCapacitySlice());
        mem.copy(u8, buffer, clobber);
        buffer[clobber.len] = 0;
        sema.air_extra.items.len += clobber.len / 4 + 1;
    }
    {
        const buffer = mem.sliceAsBytes(sema.air_extra.unusedCapacitySlice());
        mem.copy(u8, buffer, asm_source);
        sema.air_extra.items.len += (asm_source.len + 3) / 4;
    }
    return asm_air;
}

/// Only called for equality operators. See also `zirCmp`.
fn zirCmpEq(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    op: std.math.CompareOperator,
    air_tag: Air.Inst.Tag,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const src: LazySrcLoc = inst_data.src();
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);

    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    const lhs_ty_tag = lhs_ty.zigTypeTag();
    const rhs_ty_tag = rhs_ty.zigTypeTag();
    if (lhs_ty_tag == .Null and rhs_ty_tag == .Null) {
        // null == null, null != null
        if (op == .eq) {
            return Air.Inst.Ref.bool_true;
        } else {
            return Air.Inst.Ref.bool_false;
        }
    }

    // comparing null with optionals
    if (lhs_ty_tag == .Null and (rhs_ty_tag == .Optional or rhs_ty.isCPtr())) {
        return sema.analyzeIsNull(block, src, rhs, op == .neq);
    }
    if (rhs_ty_tag == .Null and (lhs_ty_tag == .Optional or lhs_ty.isCPtr())) {
        return sema.analyzeIsNull(block, src, lhs, op == .neq);
    }

    if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) {
        const non_null_type = if (lhs_ty_tag == .Null) rhs_ty else lhs_ty;
        return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(sema.mod)});
    }

    if (lhs_ty_tag == .Union and (rhs_ty_tag == .EnumLiteral or rhs_ty_tag == .Enum)) {
        return sema.analyzeCmpUnionTag(block, src, lhs, lhs_src, rhs, rhs_src, op);
    }
    if (rhs_ty_tag == .Union and (lhs_ty_tag == .EnumLiteral or lhs_ty_tag == .Enum)) {
        return sema.analyzeCmpUnionTag(block, src, rhs, rhs_src, lhs, lhs_src, op);
    }

    if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) {
        const runtime_src: LazySrcLoc = src: {
            if (try sema.resolveMaybeUndefVal(lhs)) |lval| {
                if (try sema.resolveMaybeUndefVal(rhs)) |rval| {
                    if (lval.isUndef() or rval.isUndef()) {
                        return sema.addConstUndef(Type.bool);
                    }
                    // TODO optimisation opportunity: evaluate if mem.eql is faster with the names,
                    // or calling to Module.getErrorValue to get the values and then compare them is
                    // faster.
                    const lhs_name = lval.castTag(.@"error").?.data.name;
                    const rhs_name = rval.castTag(.@"error").?.data.name;
                    if (mem.eql(u8, lhs_name, rhs_name) == (op == .eq)) {
                        return Air.Inst.Ref.bool_true;
                    } else {
                        return Air.Inst.Ref.bool_false;
                    }
                } else {
                    break :src rhs_src;
                }
            } else {
                break :src lhs_src;
            }
        };
        try sema.requireRuntimeBlock(block, src, runtime_src);
        return block.addBinOp(air_tag, lhs, rhs);
    }
    if (lhs_ty_tag == .Type and rhs_ty_tag == .Type) {
        const lhs_as_type = try sema.analyzeAsType(block, lhs_src, lhs);
        const rhs_as_type = try sema.analyzeAsType(block, rhs_src, rhs);
        if (lhs_as_type.eql(rhs_as_type, sema.mod) == (op == .eq)) {
            return Air.Inst.Ref.bool_true;
        } else {
            return Air.Inst.Ref.bool_false;
        }
    }
    return sema.analyzeCmp(block, src, lhs, rhs, op, lhs_src, rhs_src, true);
}

fn analyzeCmpUnionTag(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    un: Air.Inst.Ref,
    un_src: LazySrcLoc,
    tag: Air.Inst.Ref,
    tag_src: LazySrcLoc,
    op: std.math.CompareOperator,
) CompileError!Air.Inst.Ref {
    const union_ty = try sema.resolveTypeFields(sema.typeOf(un));
    const union_tag_ty = union_ty.unionTagType() orelse {
        const msg = msg: {
            const msg = try sema.errMsg(block, un_src, "comparison of union and enum literal is only valid for tagged union types", .{});
            errdefer msg.destroy(sema.gpa);
            try sema.mod.errNoteNonLazy(union_ty.declSrcLoc(sema.mod), msg, "union '{}' is not a tagged union", .{union_ty.fmt(sema.mod)});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    };
    // Coerce both the union and the tag to the union's tag type, and then execute the
    // enum comparison codepath.
    const coerced_tag = try sema.coerce(block, union_tag_ty, tag, tag_src);
    const coerced_union = try sema.coerce(block, union_tag_ty, un, un_src);

    if (try sema.resolveMaybeUndefVal(coerced_tag)) |enum_val| {
        if (enum_val.isUndef()) return sema.addConstUndef(Type.bool);
        const field_ty = union_ty.unionFieldType(enum_val, sema.mod);
        if (field_ty.zigTypeTag() == .NoReturn) {
            return Air.Inst.Ref.bool_false;
        }
    }

    return sema.cmpSelf(block, src, coerced_union, coerced_tag, op, un_src, tag_src);
}

/// Only called for non-equality operators. See also `zirCmpEq`.
fn zirCmp(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    op: std.math.CompareOperator,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const src: LazySrcLoc = inst_data.src();
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    return sema.analyzeCmp(block, src, lhs, rhs, op, lhs_src, rhs_src, false);
}

fn analyzeCmp(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    lhs: Air.Inst.Ref,
    rhs: Air.Inst.Ref,
    op: std.math.CompareOperator,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
    is_equality_cmp: bool,
) CompileError!Air.Inst.Ref {
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    if (lhs_ty.zigTypeTag() != .Optional and rhs_ty.zigTypeTag() != .Optional) {
        try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    }

    if (lhs_ty.zigTypeTag() == .Vector and rhs_ty.zigTypeTag() == .Vector) {
        return sema.cmpVector(block, src, lhs, rhs, op, lhs_src, rhs_src);
    }
    if (lhs_ty.isNumeric() and rhs_ty.isNumeric()) {
        // This operation allows any combination of integer and float types, regardless of the
        // signed-ness, comptime-ness, and bit-width. So peer type resolution is incorrect for
        // numeric types.
        return sema.cmpNumeric(block, src, lhs, rhs, op, lhs_src, rhs_src);
    }
    if (is_equality_cmp and lhs_ty.zigTypeTag() == .ErrorUnion and rhs_ty.zigTypeTag() == .ErrorSet) {
        const casted_lhs = try sema.analyzeErrUnionCode(block, lhs_src, lhs);
        return sema.cmpSelf(block, src, casted_lhs, rhs, op, lhs_src, rhs_src);
    }
    if (is_equality_cmp and lhs_ty.zigTypeTag() == .ErrorSet and rhs_ty.zigTypeTag() == .ErrorUnion) {
        const casted_rhs = try sema.analyzeErrUnionCode(block, rhs_src, rhs);
        return sema.cmpSelf(block, src, lhs, casted_rhs, op, lhs_src, rhs_src);
    }
    const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
    const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{ .override = &[_]LazySrcLoc{ lhs_src, rhs_src } });
    if (!resolved_type.isSelfComparable(is_equality_cmp)) {
        return sema.fail(block, src, "operator {s} not allowed for type '{}'", .{
            compareOperatorName(op), resolved_type.fmt(sema.mod),
        });
    }
    const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, resolved_type, rhs, rhs_src);
    return sema.cmpSelf(block, src, casted_lhs, casted_rhs, op, lhs_src, rhs_src);
}

fn compareOperatorName(comp: std.math.CompareOperator) []const u8 {
    return switch (comp) {
        .lt => "<",
        .lte => "<=",
        .eq => "==",
        .gte => ">=",
        .gt => ">",
        .neq => "!=",
    };
}

fn cmpSelf(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    casted_lhs: Air.Inst.Ref,
    casted_rhs: Air.Inst.Ref,
    op: std.math.CompareOperator,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const resolved_type = sema.typeOf(casted_lhs);
    const runtime_src: LazySrcLoc = src: {
        if (try sema.resolveMaybeUndefVal(casted_lhs)) |lhs_val| {
            if (lhs_val.isUndef()) return sema.addConstUndef(Type.bool);
            if (try sema.resolveMaybeUndefVal(casted_rhs)) |rhs_val| {
                if (rhs_val.isUndef()) return sema.addConstUndef(Type.bool);

                if (resolved_type.zigTypeTag() == .Vector) {
                    const result_ty = try Type.vector(sema.arena, resolved_type.vectorLen(), Type.bool);
                    const cmp_val = try sema.compareVector(lhs_val, op, rhs_val, resolved_type);
                    return sema.addConstant(result_ty, cmp_val);
                }

                if (try sema.compareAll(lhs_val, op, rhs_val, resolved_type)) {
                    return Air.Inst.Ref.bool_true;
                } else {
                    return Air.Inst.Ref.bool_false;
                }
            } else {
                if (resolved_type.zigTypeTag() == .Bool) {
                    // We can lower bool eq/neq more efficiently.
                    return sema.runtimeBoolCmp(block, src, op, casted_rhs, lhs_val.toBool(), rhs_src);
                }
                break :src rhs_src;
            }
        } else {
            // For bools, we still check the other operand, because we can lower
            // bool eq/neq more efficiently.
            if (resolved_type.zigTypeTag() == .Bool) {
                if (try sema.resolveMaybeUndefVal(casted_rhs)) |rhs_val| {
                    if (rhs_val.isUndef()) return sema.addConstUndef(Type.bool);
                    return sema.runtimeBoolCmp(block, src, op, casted_lhs, rhs_val.toBool(), lhs_src);
                }
            }
            break :src lhs_src;
        }
    };
    try sema.requireRuntimeBlock(block, src, runtime_src);
    if (resolved_type.zigTypeTag() == .Vector) {
        return block.addCmpVector(casted_lhs, casted_rhs, op);
    }
    const tag = Air.Inst.Tag.fromCmpOp(op, block.float_mode == .Optimized);
    return block.addBinOp(tag, casted_lhs, casted_rhs);
}

/// cmp_eq (x, false) => not(x)
/// cmp_eq (x, true ) => x
/// cmp_neq(x, false) => x
/// cmp_neq(x, true ) => not(x)
fn runtimeBoolCmp(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    op: std.math.CompareOperator,
    lhs: Air.Inst.Ref,
    rhs: bool,
    runtime_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    if ((op == .neq) == rhs) {
        try sema.requireRuntimeBlock(block, src, runtime_src);
        return block.addTyOp(.not, Type.bool, lhs);
    } else {
        return lhs;
    }
}

fn zirSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ty = try sema.resolveType(block, operand_src, inst_data.operand);
    switch (ty.zigTypeTag()) {
        .Fn,
        .NoReturn,
        .Undefined,
        .Null,
        .Opaque,
        => return sema.fail(block, operand_src, "no size available for type '{}'", .{ty.fmt(sema.mod)}),

        .Type,
        .EnumLiteral,
        .ComptimeFloat,
        .ComptimeInt,
        .Void,
        => return sema.addIntUnsigned(Type.comptime_int, 0),

        .Bool,
        .Int,
        .Float,
        .Pointer,
        .Array,
        .Struct,
        .Optional,
        .ErrorUnion,
        .ErrorSet,
        .Enum,
        .Union,
        .Vector,
        .Frame,
        .AnyFrame,
        => {},
    }
    const target = sema.mod.getTarget();
    const val = try ty.lazyAbiSize(target, sema.arena);
    if (val.tag() == .lazy_size) {
        try sema.queueFullTypeResolution(ty);
    }
    return sema.addConstant(Type.comptime_int, val);
}

fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_ty = try sema.resolveType(block, operand_src, inst_data.operand);
    switch (operand_ty.zigTypeTag()) {
        .Fn,
        .NoReturn,
        .Undefined,
        .Null,
        .Opaque,
        => return sema.fail(block, operand_src, "no size available for type '{}'", .{operand_ty.fmt(sema.mod)}),

        .Type,
        .EnumLiteral,
        .ComptimeFloat,
        .ComptimeInt,
        .Void,
        => return sema.addIntUnsigned(Type.comptime_int, 0),

        .Bool,
        .Int,
        .Float,
        .Pointer,
        .Array,
        .Struct,
        .Optional,
        .ErrorUnion,
        .ErrorSet,
        .Enum,
        .Union,
        .Vector,
        .Frame,
        .AnyFrame,
        => {},
    }
    const target = sema.mod.getTarget();
    const bit_size = try operand_ty.bitSizeAdvanced(target, sema);
    return sema.addIntUnsigned(Type.comptime_int, bit_size);
}

fn zirThis(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const this_decl_index = block.namespace.getDeclIndex();
    const src = LazySrcLoc.nodeOffset(@bitCast(i32, extended.operand));
    return sema.analyzeDeclVal(block, src, this_decl_index);
}

fn zirClosureCapture(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!void {
    // TODO: Compile error when closed over values are modified
    const inst_data = sema.code.instructions.items(.data)[inst].un_tok;
    // Closures are not necessarily constant values. For example, the
    // code might do something like this:
    // fn foo(x: anytype) void { const S = struct {field: @TypeOf(x)}; }
    // ...in which case the closure_capture instruction has access to a runtime
    // value only. In such case we preserve the type and use a dummy runtime value.
    const operand = try sema.resolveInst(inst_data.operand);
    const val = (try sema.resolveMaybeUndefValAllowVariables(operand)) orelse
        Value.initTag(.unreachable_value);

    try block.wip_capture_scope.captures.putNoClobber(sema.gpa, inst, .{
        .ty = try sema.typeOf(operand).copy(sema.perm_arena),
        .val = try val.copy(sema.perm_arena),
    });
}

fn zirClosureGet(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    // TODO CLOSURE: Test this with inline functions
    const inst_data = sema.code.instructions.items(.data)[inst].inst_node;
    var scope: *CaptureScope = sema.mod.declPtr(block.src_decl).src_scope.?;
    // Note: The target closure must be in this scope list.
    // If it's not here, the zir is invalid, or the list is broken.
    const tv = while (true) {
        // Note: We don't need to add a dependency here, because
        // decls always depend on their lexical parents.

        // Fail this decl if a scope it depended on failed.
        if (scope.failed()) {
            if (sema.owner_func) |owner_func| {
                owner_func.state = .dependency_failure;
            } else {
                sema.owner_decl.analysis = .dependency_failure;
            }
            return error.AnalysisFail;
        }
        if (scope.captures.getPtr(inst_data.inst)) |tv| {
            break tv;
        }
        scope = scope.parent.?;
    };

    if (tv.val.tag() == .unreachable_value and !block.is_typeof and sema.func == null) {
        const msg = msg: {
            const name = name: {
                const file = sema.owner_decl.getFileScope();
                const tree = file.getTree(sema.mod.gpa) catch |err| {
                    // In this case we emit a warning + a less precise source location.
                    log.warn("unable to load {s}: {s}", .{
                        file.sub_file_path, @errorName(err),
                    });
                    break :name null;
                };
                const node = sema.owner_decl.relativeToNodeIndex(inst_data.src_node);
                const token = tree.nodes.items(.main_token)[node];
                break :name tree.tokenSlice(token);
            };

            const msg = if (name) |some|
                try sema.errMsg(block, inst_data.src(), "'{s}' not accessible outside function scope", .{some})
            else
                try sema.errMsg(block, inst_data.src(), "variable not accessible outside function scope", .{});
            errdefer msg.destroy(sema.gpa);

            // TODO add "declared here" note
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (tv.val.tag() == .unreachable_value and !block.is_typeof and !block.is_comptime and sema.func != null) {
        const msg = msg: {
            const name = name: {
                const file = sema.owner_decl.getFileScope();
                const tree = file.getTree(sema.mod.gpa) catch |err| {
                    // In this case we emit a warning + a less precise source location.
                    log.warn("unable to load {s}: {s}", .{
                        file.sub_file_path, @errorName(err),
                    });
                    break :name null;
                };
                const node = sema.owner_decl.relativeToNodeIndex(inst_data.src_node);
                const token = tree.nodes.items(.main_token)[node];
                break :name tree.tokenSlice(token);
            };

            const msg = if (name) |some|
                try sema.errMsg(block, inst_data.src(), "'{s}' not accessible from inner function", .{some})
            else
                try sema.errMsg(block, inst_data.src(), "variable not accessible from inner function", .{});
            errdefer msg.destroy(sema.gpa);

            try sema.errNote(block, LazySrcLoc.nodeOffset(0), msg, "crossed function definition here", .{});

            // TODO add "declared here" note
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (tv.val.tag() == .unreachable_value) {
        assert(block.is_typeof);
        // We need a dummy runtime instruction with the correct type.
        return block.addTy(.alloc, tv.ty);
    }

    return sema.addConstant(tv.ty, tv.val);
}

fn zirRetAddr(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const src = LazySrcLoc.nodeOffset(@bitCast(i32, extended.operand));
    try sema.requireRuntimeBlock(block, src, null);
    return try block.addNoOp(.ret_addr);
}

fn zirFrameAddress(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const src = LazySrcLoc.nodeOffset(@bitCast(i32, extended.operand));
    try sema.requireRuntimeBlock(block, src, null);
    return try block.addNoOp(.frame_addr);
}

fn zirBuiltinSrc(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.Src, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const func = sema.func orelse return sema.fail(block, src, "@src outside function", .{});
    const fn_owner_decl = sema.mod.declPtr(func.owner_decl);

    const func_name_val = blk: {
        var anon_decl = try block.startAnonDecl();
        defer anon_decl.deinit();
        const name = std.mem.span(fn_owner_decl.name);
        const bytes = try anon_decl.arena().dupe(u8, name[0 .. name.len + 1]);
        const new_decl = try anon_decl.finish(
            try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len - 1),
            try Value.Tag.bytes.create(anon_decl.arena(), bytes),
            0, // default alignment
        );
        break :blk try Value.Tag.decl_ref.create(sema.arena, new_decl);
    };

    const file_name_val = blk: {
        var anon_decl = try block.startAnonDecl();
        defer anon_decl.deinit();
        // The compiler must not call realpath anywhere.
        const name = try fn_owner_decl.getFileScope().fullPathZ(anon_decl.arena());
        const new_decl = try anon_decl.finish(
            try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), name.len),
            try Value.Tag.bytes.create(anon_decl.arena(), name[0 .. name.len + 1]),
            0, // default alignment
        );
        break :blk try Value.Tag.decl_ref.create(sema.arena, new_decl);
    };

    const field_values = try sema.arena.alloc(Value, 4);
    // file: [:0]const u8,
    field_values[0] = file_name_val;
    // fn_name: [:0]const u8,
    field_values[1] = func_name_val;
    // line: u32
    field_values[2] = try Value.Tag.runtime_value.create(sema.arena, try Value.Tag.int_u64.create(sema.arena, extra.line + 1));
    // column: u32,
    field_values[3] = try Value.Tag.int_u64.create(sema.arena, extra.column + 1);

    return sema.addConstant(
        try sema.getBuiltinType("SourceLocation"),
        try Value.Tag.aggregate.create(sema.arena, field_values),
    );
}

fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ty = try sema.resolveType(block, src, inst_data.operand);
    const type_info_ty = try sema.getBuiltinType("Type");
    const target = sema.mod.getTarget();

    switch (ty.zigTypeTag()) {
        .Type => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Type)),
                .val = Value.void,
            }),
        ),
        .Void => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Void)),
                .val = Value.void,
            }),
        ),
        .Bool => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Bool)),
                .val = Value.void,
            }),
        ),
        .NoReturn => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.NoReturn)),
                .val = Value.void,
            }),
        ),
        .ComptimeFloat => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.ComptimeFloat)),
                .val = Value.void,
            }),
        ),
        .ComptimeInt => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.ComptimeInt)),
                .val = Value.void,
            }),
        ),
        .Undefined => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Undefined)),
                .val = Value.void,
            }),
        ),
        .Null => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Null)),
                .val = Value.void,
            }),
        ),
        .EnumLiteral => return sema.addConstant(
            type_info_ty,
            try Value.Tag.@"union".create(sema.arena, .{
                .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.EnumLiteral)),
                .val = Value.void,
            }),
        ),
        .Fn => {
            // TODO: look into memoizing this result.
            const info = ty.fnInfo();

            var params_anon_decl = try block.startAnonDecl();
            defer params_anon_decl.deinit();

            const param_vals = try params_anon_decl.arena().alloc(Value, info.param_types.len);
            for (param_vals, 0..) |*param_val, i| {
                const param_ty = info.param_types[i];
                const is_generic = param_ty.tag() == .generic_poison;
                const param_ty_val = if (is_generic)
                    Value.null
                else
                    try Value.Tag.opt_payload.create(
                        params_anon_decl.arena(),
                        try Value.Tag.ty.create(params_anon_decl.arena(), try param_ty.copy(params_anon_decl.arena())),
                    );

                const is_noalias = blk: {
                    const index = std.math.cast(u5, i) orelse break :blk false;
                    break :blk @truncate(u1, info.noalias_bits >> index) != 0;
                };

                const param_fields = try params_anon_decl.arena().create([3]Value);
                param_fields.* = .{
                    // is_generic: bool,
                    Value.makeBool(is_generic),
                    // is_noalias: bool,
                    Value.makeBool(is_noalias),
                    // type: ?type,
                    param_ty_val,
                };
                param_val.* = try Value.Tag.aggregate.create(params_anon_decl.arena(), param_fields);
            }

            const args_val = v: {
                const fn_info_decl_index = (try sema.namespaceLookup(
                    block,
                    src,
                    type_info_ty.getNamespace().?,
                    "Fn",
                )).?;
                try sema.mod.declareDeclDependency(sema.owner_decl_index, fn_info_decl_index);
                try sema.ensureDeclAnalyzed(fn_info_decl_index);
                const fn_info_decl = sema.mod.declPtr(fn_info_decl_index);
                var fn_ty_buffer: Value.ToTypeBuffer = undefined;
                const fn_ty = fn_info_decl.val.toType(&fn_ty_buffer);
                const param_info_decl_index = (try sema.namespaceLookup(
                    block,
                    src,
                    fn_ty.getNamespace().?,
                    "Param",
                )).?;
                try sema.mod.declareDeclDependency(sema.owner_decl_index, param_info_decl_index);
                try sema.ensureDeclAnalyzed(param_info_decl_index);
                const param_info_decl = sema.mod.declPtr(param_info_decl_index);
                var param_buffer: Value.ToTypeBuffer = undefined;
                const param_ty = param_info_decl.val.toType(&param_buffer);
                const new_decl = try params_anon_decl.finish(
                    try Type.Tag.array.create(params_anon_decl.arena(), .{
                        .len = param_vals.len,
                        .elem_type = try param_ty.copy(params_anon_decl.arena()),
                    }),
                    try Value.Tag.aggregate.create(
                        params_anon_decl.arena(),
                        param_vals,
                    ),
                    0, // default alignment
                );
                break :v try Value.Tag.slice.create(sema.arena, .{
                    .ptr = try Value.Tag.decl_ref.create(sema.arena, new_decl),
                    .len = try Value.Tag.int_u64.create(sema.arena, param_vals.len),
                });
            };

            const ret_ty_opt = if (info.return_type.tag() != .generic_poison)
                try Value.Tag.opt_payload.create(
                    sema.arena,
                    try Value.Tag.ty.create(sema.arena, info.return_type),
                )
            else
                Value.null;

            const field_values = try sema.arena.create([6]Value);
            field_values.* = .{
                // calling_convention: CallingConvention,
                try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(info.cc)),
                // alignment: comptime_int,
                try Value.Tag.int_u64.create(sema.arena, ty.abiAlignment(target)),
                // is_generic: bool,
                Value.makeBool(info.is_generic),
                // is_var_args: bool,
                Value.makeBool(info.is_var_args),
                // return_type: ?type,
                ret_ty_opt,
                // args: []const Fn.Param,
                args_val,
            };

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Fn)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Int => {
            const info = ty.intInfo(target);
            const field_values = try sema.arena.alloc(Value, 2);
            // signedness: Signedness,
            field_values[0] = try Value.Tag.enum_field_index.create(
                sema.arena,
                @enumToInt(info.signedness),
            );
            // bits: comptime_int,
            field_values[1] = try Value.Tag.int_u64.create(sema.arena, info.bits);

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Int)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Float => {
            const field_values = try sema.arena.alloc(Value, 1);
            // bits: comptime_int,
            field_values[0] = try Value.Tag.int_u64.create(sema.arena, ty.bitSize(target));

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Float)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Pointer => {
            const info = ty.ptrInfo().data;
            const alignment = if (info.@"align" != 0)
                try Value.Tag.int_u64.create(sema.arena, info.@"align")
            else
                try info.pointee_type.lazyAbiAlignment(target, sema.arena);

            const field_values = try sema.arena.create([8]Value);
            field_values.* = .{
                // size: Size,
                try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(info.size)),
                // is_const: bool,
                Value.makeBool(!info.mutable),
                // is_volatile: bool,
                Value.makeBool(info.@"volatile"),
                // alignment: comptime_int,
                alignment,
                // address_space: AddressSpace
                try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(info.@"addrspace")),
                // child: type,
                try Value.Tag.ty.create(sema.arena, info.pointee_type),
                // is_allowzero: bool,
                Value.makeBool(info.@"allowzero"),
                // sentinel: ?*const anyopaque,
                try sema.optRefValue(block, info.pointee_type, info.sentinel),
            };

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Pointer)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Array => {
            const info = ty.arrayInfo();
            const field_values = try sema.arena.alloc(Value, 3);
            // len: comptime_int,
            field_values[0] = try Value.Tag.int_u64.create(sema.arena, info.len);
            // child: type,
            field_values[1] = try Value.Tag.ty.create(sema.arena, info.elem_type);
            // sentinel: ?*const anyopaque,
            field_values[2] = try sema.optRefValue(block, info.elem_type, info.sentinel);

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Array)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Vector => {
            const info = ty.arrayInfo();
            const field_values = try sema.arena.alloc(Value, 2);
            // len: comptime_int,
            field_values[0] = try Value.Tag.int_u64.create(sema.arena, info.len);
            // child: type,
            field_values[1] = try Value.Tag.ty.create(sema.arena, info.elem_type);

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Vector)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Optional => {
            const field_values = try sema.arena.alloc(Value, 1);
            // child: type,
            field_values[0] = try Value.Tag.ty.create(sema.arena, try ty.optionalChildAlloc(sema.arena));

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Optional)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .ErrorSet => {
            var fields_anon_decl = try block.startAnonDecl();
            defer fields_anon_decl.deinit();

            // Get the Error type
            const error_field_ty = t: {
                const set_field_ty_decl_index = (try sema.namespaceLookup(
                    block,
                    src,
                    type_info_ty.getNamespace().?,
                    "Error",
                )).?;
                try sema.mod.declareDeclDependency(sema.owner_decl_index, set_field_ty_decl_index);
                try sema.ensureDeclAnalyzed(set_field_ty_decl_index);
                const set_field_ty_decl = sema.mod.declPtr(set_field_ty_decl_index);
                var buffer: Value.ToTypeBuffer = undefined;
                break :t try set_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
            };

            try sema.queueFullTypeResolution(try error_field_ty.copy(sema.arena));

            // If the error set is inferred it must be resolved at this point
            try sema.resolveInferredErrorSetTy(block, src, ty);

            // Build our list of Error values
            // Optional value is only null if anyerror
            // Value can be zero-length slice otherwise
            const error_field_vals: ?[]Value = if (ty.isAnyError()) null else blk: {
                const names = ty.errorSetNames();
                const vals = try fields_anon_decl.arena().alloc(Value, names.len);
                for (vals, 0..) |*field_val, i| {
                    const name = names[i];
                    const name_val = v: {
                        var anon_decl = try block.startAnonDecl();
                        defer anon_decl.deinit();
                        const bytes = try anon_decl.arena().dupeZ(u8, name);
                        const new_decl = try anon_decl.finish(
                            try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
                            try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
                            0, // default alignment
                        );
                        break :v try Value.Tag.decl_ref.create(fields_anon_decl.arena(), new_decl);
                    };

                    const error_field_fields = try fields_anon_decl.arena().create([1]Value);
                    error_field_fields.* = .{
                        // name: []const u8,
                        name_val,
                    };

                    field_val.* = try Value.Tag.aggregate.create(
                        fields_anon_decl.arena(),
                        error_field_fields,
                    );
                }

                break :blk vals;
            };

            // Build our ?[]const Error value
            const errors_val = if (error_field_vals) |vals| v: {
                const new_decl = try fields_anon_decl.finish(
                    try Type.Tag.array.create(fields_anon_decl.arena(), .{
                        .len = vals.len,
                        .elem_type = error_field_ty,
                    }),
                    try Value.Tag.aggregate.create(
                        fields_anon_decl.arena(),
                        vals,
                    ),
                    0, // default alignment
                );

                const new_decl_val = try Value.Tag.decl_ref.create(sema.arena, new_decl);
                const slice_val = try Value.Tag.slice.create(sema.arena, .{
                    .ptr = new_decl_val,
                    .len = try Value.Tag.int_u64.create(sema.arena, vals.len),
                });
                break :v try Value.Tag.opt_payload.create(sema.arena, slice_val);
            } else Value.null;

            // Construct Type{ .ErrorSet = errors_val }
            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.ErrorSet)),
                    .val = errors_val,
                }),
            );
        },
        .ErrorUnion => {
            const field_values = try sema.arena.alloc(Value, 2);
            // error_set: type,
            field_values[0] = try Value.Tag.ty.create(sema.arena, ty.errorUnionSet());
            // payload: type,
            field_values[1] = try Value.Tag.ty.create(sema.arena, ty.errorUnionPayload());

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.ErrorUnion)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Enum => {
            // TODO: look into memoizing this result.
            var int_tag_type_buffer: Type.Payload.Bits = undefined;
            const int_tag_ty = try ty.intTagType(&int_tag_type_buffer).copy(sema.arena);

            const is_exhaustive = Value.makeBool(!ty.isNonexhaustiveEnum());

            var fields_anon_decl = try block.startAnonDecl();
            defer fields_anon_decl.deinit();

            const enum_field_ty = t: {
                const enum_field_ty_decl_index = (try sema.namespaceLookup(
                    block,
                    src,
                    type_info_ty.getNamespace().?,
                    "EnumField",
                )).?;
                try sema.mod.declareDeclDependency(sema.owner_decl_index, enum_field_ty_decl_index);
                try sema.ensureDeclAnalyzed(enum_field_ty_decl_index);
                const enum_field_ty_decl = sema.mod.declPtr(enum_field_ty_decl_index);
                var buffer: Value.ToTypeBuffer = undefined;
                break :t try enum_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
            };

            const enum_fields = ty.enumFields();
            const enum_field_vals = try fields_anon_decl.arena().alloc(Value, enum_fields.count());

            for (enum_field_vals, 0..) |*field_val, i| {
                var tag_val_payload: Value.Payload.U32 = .{
                    .base = .{ .tag = .enum_field_index },
                    .data = @intCast(u32, i),
                };
                const tag_val = Value.initPayload(&tag_val_payload.base);

                var buffer: Value.Payload.U64 = undefined;
                const int_val = try tag_val.enumToInt(ty, &buffer).copy(fields_anon_decl.arena());

                const name = enum_fields.keys()[i];
                const name_val = v: {
                    var anon_decl = try block.startAnonDecl();
                    defer anon_decl.deinit();
                    const bytes = try anon_decl.arena().dupeZ(u8, name);
                    const new_decl = try anon_decl.finish(
                        try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
                        try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
                        0, // default alignment
                    );
                    break :v try Value.Tag.decl_ref.create(fields_anon_decl.arena(), new_decl);
                };

                const enum_field_fields = try fields_anon_decl.arena().create([2]Value);
                enum_field_fields.* = .{
                    // name: []const u8,
                    name_val,
                    // value: comptime_int,
                    int_val,
                };
                field_val.* = try Value.Tag.aggregate.create(fields_anon_decl.arena(), enum_field_fields);
            }

            const fields_val = v: {
                const new_decl = try fields_anon_decl.finish(
                    try Type.Tag.array.create(fields_anon_decl.arena(), .{
                        .len = enum_field_vals.len,
                        .elem_type = enum_field_ty,
                    }),
                    try Value.Tag.aggregate.create(
                        fields_anon_decl.arena(),
                        enum_field_vals,
                    ),
                    0, // default alignment
                );
                break :v try Value.Tag.decl_ref.create(sema.arena, new_decl);
            };

            const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespace());

            const field_values = try sema.arena.create([4]Value);
            field_values.* = .{
                // tag_type: type,
                try Value.Tag.ty.create(sema.arena, int_tag_ty),
                // fields: []const EnumField,
                fields_val,
                // decls: []const Declaration,
                decls_val,
                // is_exhaustive: bool,
                is_exhaustive,
            };

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Enum)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Union => {
            // TODO: look into memoizing this result.

            var fields_anon_decl = try block.startAnonDecl();
            defer fields_anon_decl.deinit();

            const union_field_ty = t: {
                const union_field_ty_decl_index = (try sema.namespaceLookup(
                    block,
                    src,
                    type_info_ty.getNamespace().?,
                    "UnionField",
                )).?;
                try sema.mod.declareDeclDependency(sema.owner_decl_index, union_field_ty_decl_index);
                try sema.ensureDeclAnalyzed(union_field_ty_decl_index);
                const union_field_ty_decl = sema.mod.declPtr(union_field_ty_decl_index);
                var buffer: Value.ToTypeBuffer = undefined;
                break :t try union_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
            };

            const union_ty = try sema.resolveTypeFields(ty);
            try sema.resolveTypeLayout(ty); // Getting alignment requires type layout
            const layout = union_ty.containerLayout();

            const union_fields = union_ty.unionFields();
            const union_field_vals = try fields_anon_decl.arena().alloc(Value, union_fields.count());

            for (union_field_vals, 0..) |*field_val, i| {
                const field = union_fields.values()[i];
                const name = union_fields.keys()[i];
                const name_val = v: {
                    var anon_decl = try block.startAnonDecl();
                    defer anon_decl.deinit();
                    const bytes = try anon_decl.arena().dupeZ(u8, name);
                    const new_decl = try anon_decl.finish(
                        try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
                        try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
                        0, // default alignment
                    );
                    break :v try Value.Tag.decl_ref.create(fields_anon_decl.arena(), new_decl);
                };

                const union_field_fields = try fields_anon_decl.arena().create([3]Value);
                const alignment = switch (layout) {
                    .Auto, .Extern => try sema.unionFieldAlignment(field),
                    .Packed => 0,
                };

                union_field_fields.* = .{
                    // name: []const u8,
                    name_val,
                    // type: type,
                    try Value.Tag.ty.create(fields_anon_decl.arena(), field.ty),
                    // alignment: comptime_int,
                    try Value.Tag.int_u64.create(fields_anon_decl.arena(), alignment),
                };
                field_val.* = try Value.Tag.aggregate.create(fields_anon_decl.arena(), union_field_fields);
            }

            const fields_val = v: {
                const new_decl = try fields_anon_decl.finish(
                    try Type.Tag.array.create(fields_anon_decl.arena(), .{
                        .len = union_field_vals.len,
                        .elem_type = union_field_ty,
                    }),
                    try Value.Tag.aggregate.create(
                        fields_anon_decl.arena(),
                        try fields_anon_decl.arena().dupe(Value, union_field_vals),
                    ),
                    0, // default alignment
                );
                break :v try Value.Tag.slice.create(sema.arena, .{
                    .ptr = try Value.Tag.decl_ref.create(sema.arena, new_decl),
                    .len = try Value.Tag.int_u64.create(sema.arena, union_field_vals.len),
                });
            };

            const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, union_ty.getNamespace());

            const enum_tag_ty_val = if (union_ty.unionTagType()) |tag_ty| v: {
                const ty_val = try Value.Tag.ty.create(sema.arena, tag_ty);
                break :v try Value.Tag.opt_payload.create(sema.arena, ty_val);
            } else Value.null;

            const field_values = try sema.arena.create([4]Value);
            field_values.* = .{
                // layout: ContainerLayout,
                try Value.Tag.enum_field_index.create(
                    sema.arena,
                    @enumToInt(layout),
                ),

                // tag_type: ?type,
                enum_tag_ty_val,
                // fields: []const UnionField,
                fields_val,
                // decls: []const Declaration,
                decls_val,
            };

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Union)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Struct => {
            // TODO: look into memoizing this result.

            var fields_anon_decl = try block.startAnonDecl();
            defer fields_anon_decl.deinit();

            const struct_field_ty = t: {
                const struct_field_ty_decl_index = (try sema.namespaceLookup(
                    block,
                    src,
                    type_info_ty.getNamespace().?,
                    "StructField",
                )).?;
                try sema.mod.declareDeclDependency(sema.owner_decl_index, struct_field_ty_decl_index);
                try sema.ensureDeclAnalyzed(struct_field_ty_decl_index);
                const struct_field_ty_decl = sema.mod.declPtr(struct_field_ty_decl_index);
                var buffer: Value.ToTypeBuffer = undefined;
                break :t try struct_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
            };
            const struct_ty = try sema.resolveTypeFields(ty);
            try sema.resolveTypeLayout(ty); // Getting alignment requires type layout
            const layout = struct_ty.containerLayout();

            const struct_field_vals = fv: {
                if (struct_ty.isSimpleTupleOrAnonStruct()) {
                    const tuple = struct_ty.tupleFields();
                    const field_types = tuple.types;
                    const struct_field_vals = try fields_anon_decl.arena().alloc(Value, field_types.len);
                    for (struct_field_vals, 0..) |*struct_field_val, i| {
                        const field_ty = field_types[i];
                        const name_val = v: {
                            var anon_decl = try block.startAnonDecl();
                            defer anon_decl.deinit();
                            const bytes = if (struct_ty.castTag(.anon_struct)) |payload|
                                try anon_decl.arena().dupeZ(u8, payload.data.names[i])
                            else
                                try std.fmt.allocPrintZ(anon_decl.arena(), "{d}", .{i});
                            const new_decl = try anon_decl.finish(
                                try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
                                try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
                                0, // default alignment
                            );
                            break :v try Value.Tag.slice.create(fields_anon_decl.arena(), .{
                                .ptr = try Value.Tag.decl_ref.create(fields_anon_decl.arena(), new_decl),
                                .len = try Value.Tag.int_u64.create(fields_anon_decl.arena(), bytes.len),
                            });
                        };

                        const struct_field_fields = try fields_anon_decl.arena().create([5]Value);
                        const field_val = tuple.values[i];
                        const is_comptime = field_val.tag() != .unreachable_value;
                        const opt_default_val = if (is_comptime) field_val else null;
                        const default_val_ptr = try sema.optRefValue(block, field_ty, opt_default_val);
                        struct_field_fields.* = .{
                            // name: []const u8,
                            name_val,
                            // type: type,
                            try Value.Tag.ty.create(fields_anon_decl.arena(), field_ty),
                            // default_value: ?*const anyopaque,
                            try default_val_ptr.copy(fields_anon_decl.arena()),
                            // is_comptime: bool,
                            Value.makeBool(is_comptime),
                            // alignment: comptime_int,
                            try field_ty.lazyAbiAlignment(target, fields_anon_decl.arena()),
                        };
                        struct_field_val.* = try Value.Tag.aggregate.create(fields_anon_decl.arena(), struct_field_fields);
                    }
                    break :fv struct_field_vals;
                }
                const struct_fields = struct_ty.structFields();
                const struct_field_vals = try fields_anon_decl.arena().alloc(Value, struct_fields.count());

                for (struct_field_vals, 0..) |*field_val, i| {
                    const field = struct_fields.values()[i];
                    const name = struct_fields.keys()[i];
                    const name_val = v: {
                        var anon_decl = try block.startAnonDecl();
                        defer anon_decl.deinit();
                        const bytes = try anon_decl.arena().dupeZ(u8, name);
                        const new_decl = try anon_decl.finish(
                            try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
                            try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
                            0, // default alignment
                        );
                        break :v try Value.Tag.slice.create(fields_anon_decl.arena(), .{
                            .ptr = try Value.Tag.decl_ref.create(fields_anon_decl.arena(), new_decl),
                            .len = try Value.Tag.int_u64.create(fields_anon_decl.arena(), bytes.len),
                        });
                    };

                    const struct_field_fields = try fields_anon_decl.arena().create([5]Value);
                    const opt_default_val = if (field.default_val.tag() == .unreachable_value)
                        null
                    else
                        field.default_val;
                    const default_val_ptr = try sema.optRefValue(block, field.ty, opt_default_val);
                    const alignment = field.alignment(target, layout);

                    struct_field_fields.* = .{
                        // name: []const u8,
                        name_val,
                        // type: type,
                        try Value.Tag.ty.create(fields_anon_decl.arena(), field.ty),
                        // default_value: ?*const anyopaque,
                        try default_val_ptr.copy(fields_anon_decl.arena()),
                        // is_comptime: bool,
                        Value.makeBool(field.is_comptime),
                        // alignment: comptime_int,
                        try Value.Tag.int_u64.create(fields_anon_decl.arena(), alignment),
                    };
                    field_val.* = try Value.Tag.aggregate.create(fields_anon_decl.arena(), struct_field_fields);
                }
                break :fv struct_field_vals;
            };

            const fields_val = v: {
                const new_decl = try fields_anon_decl.finish(
                    try Type.Tag.array.create(fields_anon_decl.arena(), .{
                        .len = struct_field_vals.len,
                        .elem_type = struct_field_ty,
                    }),
                    try Value.Tag.aggregate.create(
                        fields_anon_decl.arena(),
                        try fields_anon_decl.arena().dupe(Value, struct_field_vals),
                    ),
                    0, // default alignment
                );
                break :v try Value.Tag.slice.create(sema.arena, .{
                    .ptr = try Value.Tag.decl_ref.create(sema.arena, new_decl),
                    .len = try Value.Tag.int_u64.create(sema.arena, struct_field_vals.len),
                });
            };

            const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, struct_ty.getNamespace());

            const backing_integer_val = blk: {
                if (layout == .Packed) {
                    const struct_obj = struct_ty.castTag(.@"struct").?.data;
                    assert(struct_obj.haveLayout());
                    assert(struct_obj.backing_int_ty.isInt());
                    const backing_int_ty_val = try Value.Tag.ty.create(sema.arena, struct_obj.backing_int_ty);
                    break :blk try Value.Tag.opt_payload.create(sema.arena, backing_int_ty_val);
                } else {
                    break :blk Value.initTag(.null_value);
                }
            };

            const field_values = try sema.arena.create([5]Value);
            field_values.* = .{
                // layout: ContainerLayout,
                try Value.Tag.enum_field_index.create(
                    sema.arena,
                    @enumToInt(layout),
                ),
                // backing_integer: ?type,
                backing_integer_val,
                // fields: []const StructField,
                fields_val,
                // decls: []const Declaration,
                decls_val,
                // is_tuple: bool,
                Value.makeBool(struct_ty.isTuple()),
            };

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Struct)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Opaque => {
            // TODO: look into memoizing this result.

            const opaque_ty = try sema.resolveTypeFields(ty);
            const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, opaque_ty.getNamespace());

            const field_values = try sema.arena.create([1]Value);
            field_values.* = .{
                // decls: []const Declaration,
                decls_val,
            };

            return sema.addConstant(
                type_info_ty,
                try Value.Tag.@"union".create(sema.arena, .{
                    .tag = try Value.Tag.enum_field_index.create(sema.arena, @enumToInt(std.builtin.TypeId.Opaque)),
                    .val = try Value.Tag.aggregate.create(sema.arena, field_values),
                }),
            );
        },
        .Frame => return sema.failWithUseOfAsync(block, src),
        .AnyFrame => return sema.failWithUseOfAsync(block, src),
    }
}

fn typeInfoDecls(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    type_info_ty: Type,
    opt_namespace: ?*Module.Namespace,
) CompileError!Value {
    var decls_anon_decl = try block.startAnonDecl();
    defer decls_anon_decl.deinit();

    const declaration_ty = t: {
        const declaration_ty_decl_index = (try sema.namespaceLookup(
            block,
            src,
            type_info_ty.getNamespace().?,
            "Declaration",
        )).?;
        try sema.mod.declareDeclDependency(sema.owner_decl_index, declaration_ty_decl_index);
        try sema.ensureDeclAnalyzed(declaration_ty_decl_index);
        const declaration_ty_decl = sema.mod.declPtr(declaration_ty_decl_index);
        var buffer: Value.ToTypeBuffer = undefined;
        break :t try declaration_ty_decl.val.toType(&buffer).copy(decls_anon_decl.arena());
    };
    try sema.queueFullTypeResolution(try declaration_ty.copy(sema.arena));

    var decl_vals = std.ArrayList(Value).init(sema.gpa);
    defer decl_vals.deinit();

    var seen_namespaces = std.AutoHashMap(*Namespace, void).init(sema.gpa);
    defer seen_namespaces.deinit();

    if (opt_namespace) |some| {
        try sema.typeInfoNamespaceDecls(block, decls_anon_decl.arena(), some, &decl_vals, &seen_namespaces);
    }

    const new_decl = try decls_anon_decl.finish(
        try Type.Tag.array.create(decls_anon_decl.arena(), .{
            .len = decl_vals.items.len,
            .elem_type = declaration_ty,
        }),
        try Value.Tag.aggregate.create(
            decls_anon_decl.arena(),
            try decls_anon_decl.arena().dupe(Value, decl_vals.items),
        ),
        0, // default alignment
    );
    return try Value.Tag.slice.create(sema.arena, .{
        .ptr = try Value.Tag.decl_ref.create(sema.arena, new_decl),
        .len = try Value.Tag.int_u64.create(sema.arena, decl_vals.items.len),
    });
}

fn typeInfoNamespaceDecls(
    sema: *Sema,
    block: *Block,
    decls_anon_decl: Allocator,
    namespace: *Namespace,
    decl_vals: *std.ArrayList(Value),
    seen_namespaces: *std.AutoHashMap(*Namespace, void),
) !void {
    const gop = try seen_namespaces.getOrPut(namespace);
    if (gop.found_existing) return;
    const decls = namespace.decls.keys();
    for (decls) |decl_index| {
        const decl = sema.mod.declPtr(decl_index);
        if (decl.kind == .@"usingnamespace") {
            if (decl.analysis == .in_progress) continue;
            try sema.mod.ensureDeclAnalyzed(decl_index);
            var buf: Value.ToTypeBuffer = undefined;
            const new_ns = decl.val.toType(&buf).getNamespace().?;
            try sema.typeInfoNamespaceDecls(block, decls_anon_decl, new_ns, decl_vals, seen_namespaces);
            continue;
        }
        if (decl.kind != .named) continue;
        const name_val = v: {
            var anon_decl = try block.startAnonDecl();
            defer anon_decl.deinit();
            const bytes = try anon_decl.arena().dupeZ(u8, mem.sliceTo(decl.name, 0));
            const new_decl = try anon_decl.finish(
                try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
                try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
                0, // default alignment
            );
            break :v try Value.Tag.slice.create(decls_anon_decl, .{
                .ptr = try Value.Tag.decl_ref.create(decls_anon_decl, new_decl),
                .len = try Value.Tag.int_u64.create(decls_anon_decl, bytes.len),
            });
        };

        const fields = try decls_anon_decl.create([2]Value);
        fields.* = .{
            //name: []const u8,
            name_val,
            //is_pub: bool,
            Value.makeBool(decl.is_pub),
        };
        try decl_vals.append(try Value.Tag.aggregate.create(decls_anon_decl, fields));
    }
}

fn zirTypeof(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    _ = block;
    const zir_datas = sema.code.instructions.items(.data);
    const inst_data = zir_datas[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    return sema.addType(operand_ty);
}

fn zirTypeofBuiltin(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const pl_node = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Block, pl_node.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];

    var child_block: Block = .{
        .parent = block,
        .sema = sema,
        .src_decl = block.src_decl,
        .namespace = block.namespace,
        .wip_capture_scope = block.wip_capture_scope,
        .instructions = .{},
        .inlining = block.inlining,
        .is_comptime = false,
        .is_typeof = true,
        .want_safety = false,
        .error_return_trace_index = block.error_return_trace_index,
    };
    defer child_block.instructions.deinit(sema.gpa);

    const operand = try sema.resolveBody(&child_block, body, inst);
    const operand_ty = sema.typeOf(operand);
    if (operand_ty.tag() == .generic_poison) return error.GenericPoison;
    return sema.addType(operand_ty);
}

fn zirTypeofLog2IntType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    const res_ty = try sema.log2IntType(block, operand_ty, src);
    return sema.addType(res_ty);
}

fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) CompileError!Type {
    switch (operand.zigTypeTag()) {
        .ComptimeInt => return Type.comptime_int,
        .Int => {
            const bits = operand.bitSize(sema.mod.getTarget());
            const count = if (bits == 0)
                0
            else blk: {
                var count: u16 = 0;
                var s = bits - 1;
                while (s != 0) : (s >>= 1) {
                    count += 1;
                }
                break :blk count;
            };
            return Module.makeIntType(sema.arena, .unsigned, count);
        },
        .Vector => {
            const elem_ty = operand.elemType2();
            const log2_elem_ty = try sema.log2IntType(block, elem_ty, src);
            return Type.Tag.vector.create(sema.arena, .{
                .len = operand.vectorLen(),
                .elem_type = log2_elem_ty,
            });
        },
        else => {},
    }
    return sema.fail(
        block,
        src,
        "bit shifting operation expected integer type, found '{}'",
        .{operand.fmt(sema.mod)},
    );
}

fn zirTypeofPeer(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const extra = sema.code.extraData(Zir.Inst.TypeOfPeer, extended.operand);
    const src = LazySrcLoc.nodeOffset(extra.data.src_node);
    const body = sema.code.extra[extra.data.body_index..][0..extra.data.body_len];

    var child_block: Block = .{
        .parent = block,
        .sema = sema,
        .src_decl = block.src_decl,
        .namespace = block.namespace,
        .wip_capture_scope = block.wip_capture_scope,
        .instructions = .{},
        .inlining = block.inlining,
        .is_comptime = false,
        .is_typeof = true,
        .runtime_cond = block.runtime_cond,
        .runtime_loop = block.runtime_loop,
        .runtime_index = block.runtime_index,
    };
    defer child_block.instructions.deinit(sema.gpa);
    // Ignore the result, we only care about the instructions in `args`.
    _ = try sema.analyzeBodyBreak(&child_block, body);

    const args = sema.code.refSlice(extra.end, extended.small);

    const inst_list = try sema.gpa.alloc(Air.Inst.Ref, args.len);
    defer sema.gpa.free(inst_list);

    for (args, 0..) |arg_ref, i| {
        inst_list[i] = try sema.resolveInst(arg_ref);
    }

    const result_type = try sema.resolvePeerTypes(block, src, inst_list, .{ .typeof_builtin_call_node_offset = extra.data.src_node });
    return sema.addType(result_type);
}

fn zirBoolNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_un_op = inst_data.src_node };
    const uncasted_operand = try sema.resolveInst(inst_data.operand);

    const operand = try sema.coerce(block, Type.bool, uncasted_operand, operand_src);
    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        return if (val.isUndef())
            sema.addConstUndef(Type.bool)
        else if (val.toBool())
            Air.Inst.Ref.bool_false
        else
            Air.Inst.Ref.bool_true;
    }
    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.not, Type.bool, operand);
}

fn zirBoolBr(
    sema: *Sema,
    parent_block: *Block,
    inst: Zir.Inst.Index,
    is_bool_or: bool,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const datas = sema.code.instructions.items(.data);
    const inst_data = datas[inst].bool_br;
    const lhs = try sema.resolveInst(inst_data.lhs);
    const lhs_src = sema.src;
    const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];
    const gpa = sema.gpa;

    if (try sema.resolveDefinedValue(parent_block, lhs_src, lhs)) |lhs_val| {
        if (is_bool_or and lhs_val.toBool()) {
            return Air.Inst.Ref.bool_true;
        } else if (!is_bool_or and !lhs_val.toBool()) {
            return Air.Inst.Ref.bool_false;
        }
        // comptime-known left-hand side. No need for a block here; the result
        // is simply the rhs expression. Here we rely on there only being 1
        // break instruction (`break_inline`).
        return sema.resolveBody(parent_block, body, inst);
    }

    const block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
    try sema.air_instructions.append(gpa, .{
        .tag = .block,
        .data = .{ .ty_pl = .{
            .ty = .bool_type,
            .payload = undefined,
        } },
    });

    var child_block = parent_block.makeSubBlock();
    child_block.runtime_loop = null;
    child_block.runtime_cond = lhs_src;
    child_block.runtime_index.increment();
    defer child_block.instructions.deinit(gpa);

    var then_block = child_block.makeSubBlock();
    defer then_block.instructions.deinit(gpa);

    var else_block = child_block.makeSubBlock();
    defer else_block.instructions.deinit(gpa);

    const lhs_block = if (is_bool_or) &then_block else &else_block;
    const rhs_block = if (is_bool_or) &else_block else &then_block;

    const lhs_result: Air.Inst.Ref = if (is_bool_or) .bool_true else .bool_false;
    _ = try lhs_block.addBr(block_inst, lhs_result);

    const rhs_result = try sema.resolveBody(rhs_block, body, inst);
    if (!sema.typeOf(rhs_result).isNoReturn()) {
        _ = try rhs_block.addBr(block_inst, rhs_result);
    }

    const result = sema.finishCondBr(parent_block, &child_block, &then_block, &else_block, lhs, block_inst);
    if (!sema.typeOf(rhs_result).isNoReturn()) {
        if (try sema.resolveDefinedValue(rhs_block, sema.src, rhs_result)) |rhs_val| {
            if (is_bool_or and rhs_val.toBool()) {
                return Air.Inst.Ref.bool_true;
            } else if (!is_bool_or and !rhs_val.toBool()) {
                return Air.Inst.Ref.bool_false;
            }
        }
    }

    return result;
}

fn finishCondBr(
    sema: *Sema,
    parent_block: *Block,
    child_block: *Block,
    then_block: *Block,
    else_block: *Block,
    cond: Air.Inst.Ref,
    block_inst: Air.Inst.Index,
) !Air.Inst.Ref {
    const gpa = sema.gpa;

    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.CondBr).Struct.fields.len +
        then_block.instructions.items.len + else_block.instructions.items.len +
        @typeInfo(Air.Block).Struct.fields.len + child_block.instructions.items.len + 1);

    const cond_br_payload = sema.addExtraAssumeCapacity(Air.CondBr{
        .then_body_len = @intCast(u32, then_block.instructions.items.len),
        .else_body_len = @intCast(u32, else_block.instructions.items.len),
    });
    sema.air_extra.appendSliceAssumeCapacity(then_block.instructions.items);
    sema.air_extra.appendSliceAssumeCapacity(else_block.instructions.items);

    _ = try child_block.addInst(.{ .tag = .cond_br, .data = .{ .pl_op = .{
        .operand = cond,
        .payload = cond_br_payload,
    } } });

    sema.air_instructions.items(.data)[block_inst].ty_pl.payload = sema.addExtraAssumeCapacity(
        Air.Block{ .body_len = @intCast(u32, child_block.instructions.items.len) },
    );
    sema.air_extra.appendSliceAssumeCapacity(child_block.instructions.items);

    try parent_block.instructions.append(gpa, block_inst);
    return Air.indexToRef(block_inst);
}

fn checkNullableType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
    switch (ty.zigTypeTag()) {
        .Optional, .Null, .Undefined => return,
        .Pointer => if (ty.isPtrLikeOptional()) return,
        else => {},
    }
    return sema.failWithExpectedOptionalType(block, src, ty);
}

fn zirIsNonNull(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    try sema.checkNullableType(block, src, sema.typeOf(operand));
    return sema.analyzeIsNull(block, src, operand, true);
}

fn zirIsNonNullPtr(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ptr = try sema.resolveInst(inst_data.operand);
    try sema.checkNullableType(block, src, sema.typeOf(ptr).elemType2());
    if ((try sema.resolveMaybeUndefVal(ptr)) == null) {
        return block.addUnOp(.is_non_null_ptr, ptr);
    }
    const loaded = try sema.analyzeLoad(block, src, ptr, src);
    return sema.analyzeIsNull(block, src, loaded, true);
}

fn checkErrorType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
    switch (ty.zigTypeTag()) {
        .ErrorSet, .ErrorUnion, .Undefined => return,
        else => return sema.fail(block, src, "expected error union type, found '{}'", .{
            ty.fmt(sema.mod),
        }),
    }
}

fn zirIsNonErr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    try sema.checkErrorType(block, src, sema.typeOf(operand));
    return sema.analyzeIsNonErr(block, src, operand);
}

fn zirIsNonErrPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ptr = try sema.resolveInst(inst_data.operand);
    try sema.checkErrorType(block, src, sema.typeOf(ptr).elemType2());
    const loaded = try sema.analyzeLoad(block, src, ptr, src);
    return sema.analyzeIsNonErr(block, src, loaded);
}

fn zirRetIsNonErr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    return sema.analyzeIsNonErr(block, src, operand);
}

fn zirCondbr(
    sema: *Sema,
    parent_block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Zir.Inst.Index {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const cond_src: LazySrcLoc = .{ .node_offset_if_cond = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);

    const then_body = sema.code.extra[extra.end..][0..extra.data.then_body_len];
    const else_body = sema.code.extra[extra.end + then_body.len ..][0..extra.data.else_body_len];

    const uncasted_cond = try sema.resolveInst(extra.data.condition);
    const cond = try sema.coerce(parent_block, Type.bool, uncasted_cond, cond_src);

    if (try sema.resolveDefinedValue(parent_block, cond_src, cond)) |cond_val| {
        const body = if (cond_val.toBool()) then_body else else_body;

        try sema.maybeErrorUnwrapCondbr(parent_block, body, extra.data.condition, cond_src);
        // We use `analyzeBodyInner` since we want to propagate any possible
        // `error.ComptimeBreak` to the caller.
        return sema.analyzeBodyInner(parent_block, body);
    }

    const gpa = sema.gpa;

    // We'll re-use the sub block to save on memory bandwidth, and yank out the
    // instructions array in between using it for the then block and else block.
    var sub_block = parent_block.makeSubBlock();
    sub_block.runtime_loop = null;
    sub_block.runtime_cond = cond_src;
    sub_block.runtime_index.increment();
    defer sub_block.instructions.deinit(gpa);

    try sema.analyzeBodyRuntimeBreak(&sub_block, then_body);
    const true_instructions = try sub_block.instructions.toOwnedSlice(gpa);
    defer gpa.free(true_instructions);

    const err_cond = blk: {
        const index = Zir.refToIndex(extra.data.condition) orelse break :blk null;
        if (sema.code.instructions.items(.tag)[index] != .is_non_err) break :blk null;

        const err_inst_data = sema.code.instructions.items(.data)[index].un_node;
        const err_operand = try sema.resolveInst(err_inst_data.operand);
        const operand_ty = sema.typeOf(err_operand);
        assert(operand_ty.zigTypeTag() == .ErrorUnion);
        const result_ty = operand_ty.errorUnionSet();
        break :blk try sub_block.addTyOp(.unwrap_errunion_err, result_ty, err_operand);
    };

    if (err_cond != null and try sema.maybeErrorUnwrap(&sub_block, else_body, err_cond.?)) {
        // nothing to do
    } else {
        try sema.analyzeBodyRuntimeBreak(&sub_block, else_body);
    }
    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.CondBr).Struct.fields.len +
        true_instructions.len + sub_block.instructions.items.len);
    _ = try parent_block.addInst(.{
        .tag = .cond_br,
        .data = .{ .pl_op = .{
            .operand = cond,
            .payload = sema.addExtraAssumeCapacity(Air.CondBr{
                .then_body_len = @intCast(u32, true_instructions.len),
                .else_body_len = @intCast(u32, sub_block.instructions.items.len),
            }),
        } },
    });
    sema.air_extra.appendSliceAssumeCapacity(true_instructions);
    sema.air_extra.appendSliceAssumeCapacity(sub_block.instructions.items);
    return always_noreturn;
}

fn zirTry(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Try, inst_data.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];
    const err_union = try sema.resolveInst(extra.data.operand);
    const err_union_ty = sema.typeOf(err_union);
    if (err_union_ty.zigTypeTag() != .ErrorUnion) {
        return sema.fail(parent_block, operand_src, "expected error union type, found '{}'", .{
            err_union_ty.fmt(sema.mod),
        });
    }
    const is_non_err = try sema.analyzeIsNonErrComptimeOnly(parent_block, operand_src, err_union);
    if (is_non_err != .none) {
        const is_non_err_val = (try sema.resolveDefinedValue(parent_block, operand_src, is_non_err)).?;
        if (is_non_err_val.toBool()) {
            return sema.analyzeErrUnionPayload(parent_block, src, err_union_ty, err_union, operand_src, false);
        }
        // We can analyze the body directly in the parent block because we know there are
        // no breaks from the body possible, and that the body is noreturn.
        return sema.resolveBody(parent_block, body, inst);
    }

    var sub_block = parent_block.makeSubBlock();
    defer sub_block.instructions.deinit(sema.gpa);

    // This body is guaranteed to end with noreturn and has no breaks.
    _ = try sema.analyzeBodyInner(&sub_block, body);

    try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.Try).Struct.fields.len +
        sub_block.instructions.items.len);
    const try_inst = try parent_block.addInst(.{
        .tag = .@"try",
        .data = .{ .pl_op = .{
            .operand = err_union,
            .payload = sema.addExtraAssumeCapacity(Air.Try{
                .body_len = @intCast(u32, sub_block.instructions.items.len),
            }),
        } },
    });
    sema.air_extra.appendSliceAssumeCapacity(sub_block.instructions.items);
    return try_inst;
}

fn zirTryPtr(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Try, inst_data.payload_index);
    const body = sema.code.extra[extra.end..][0..extra.data.body_len];
    const operand = try sema.resolveInst(extra.data.operand);
    const err_union = try sema.analyzeLoad(parent_block, src, operand, operand_src);
    const err_union_ty = sema.typeOf(err_union);
    if (err_union_ty.zigTypeTag() != .ErrorUnion) {
        return sema.fail(parent_block, operand_src, "expected error union type, found '{}'", .{
            err_union_ty.fmt(sema.mod),
        });
    }
    const is_non_err = try sema.analyzeIsNonErrComptimeOnly(parent_block, operand_src, err_union);
    if (is_non_err != .none) {
        const is_non_err_val = (try sema.resolveDefinedValue(parent_block, operand_src, is_non_err)).?;
        if (is_non_err_val.toBool()) {
            return sema.analyzeErrUnionPayloadPtr(parent_block, src, operand, false, false);
        }
        // We can analyze the body directly in the parent block because we know there are
        // no breaks from the body possible, and that the body is noreturn.
        return sema.resolveBody(parent_block, body, inst);
    }

    var sub_block = parent_block.makeSubBlock();
    defer sub_block.instructions.deinit(sema.gpa);

    // This body is guaranteed to end with noreturn and has no breaks.
    _ = try sema.analyzeBodyInner(&sub_block, body);

    const operand_ty = sema.typeOf(operand);
    const ptr_info = operand_ty.ptrInfo().data;
    const res_ty = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = err_union_ty.errorUnionPayload(),
        .@"addrspace" = ptr_info.@"addrspace",
        .mutable = ptr_info.mutable,
        .@"allowzero" = ptr_info.@"allowzero",
        .@"volatile" = ptr_info.@"volatile",
    });
    const res_ty_ref = try sema.addType(res_ty);
    try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.TryPtr).Struct.fields.len +
        sub_block.instructions.items.len);
    const try_inst = try parent_block.addInst(.{
        .tag = .try_ptr,
        .data = .{ .ty_pl = .{
            .ty = res_ty_ref,
            .payload = sema.addExtraAssumeCapacity(Air.TryPtr{
                .ptr = operand,
                .body_len = @intCast(u32, sub_block.instructions.items.len),
            }),
        } },
    });
    sema.air_extra.appendSliceAssumeCapacity(sub_block.instructions.items);
    return try_inst;
}

// A `break` statement is inside a runtime condition, but trying to
// break from an inline loop. In such case we must convert it to
// a runtime break.
fn addRuntimeBreak(sema: *Sema, child_block: *Block, break_data: BreakData) !void {
    const gop = sema.inst_map.getOrPutAssumeCapacity(break_data.block_inst);
    const labeled_block = if (!gop.found_existing) blk: {
        try sema.post_hoc_blocks.ensureUnusedCapacity(sema.gpa, 1);

        const new_block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
        gop.value_ptr.* = Air.indexToRef(new_block_inst);
        try sema.air_instructions.append(sema.gpa, .{
            .tag = .block,
            .data = undefined,
        });
        const labeled_block = try sema.gpa.create(LabeledBlock);
        labeled_block.* = .{
            .label = .{
                .zir_block = break_data.block_inst,
                .merges = .{
                    .results = .{},
                    .br_list = .{},
                    .block_inst = new_block_inst,
                },
            },
            .block = .{
                .parent = child_block,
                .sema = sema,
                .src_decl = child_block.src_decl,
                .namespace = child_block.namespace,
                .wip_capture_scope = child_block.wip_capture_scope,
                .instructions = .{},
                .label = &labeled_block.label,
                .inlining = child_block.inlining,
                .is_comptime = child_block.is_comptime,
            },
        };
        sema.post_hoc_blocks.putAssumeCapacityNoClobber(new_block_inst, labeled_block);
        break :blk labeled_block;
    } else blk: {
        const new_block_inst = Air.refToIndex(gop.value_ptr.*).?;
        const labeled_block = sema.post_hoc_blocks.get(new_block_inst).?;
        break :blk labeled_block;
    };

    const operand = try sema.resolveInst(break_data.operand);
    const br_ref = try child_block.addBr(labeled_block.label.merges.block_inst, operand);
    try labeled_block.label.merges.results.append(sema.gpa, operand);
    try labeled_block.label.merges.br_list.append(sema.gpa, Air.refToIndex(br_ref).?);
    labeled_block.block.runtime_index.increment();
    if (labeled_block.block.runtime_cond == null and labeled_block.block.runtime_loop == null) {
        labeled_block.block.runtime_cond = child_block.runtime_cond orelse child_block.runtime_loop;
        labeled_block.block.runtime_loop = child_block.runtime_loop;
    }
}

fn zirUnreachable(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Index {
    const inst_data = sema.code.instructions.items(.data)[inst].@"unreachable";
    const src = inst_data.src();

    if (block.is_comptime or inst_data.force_comptime) {
        return sema.fail(block, src, "reached unreachable code", .{});
    }
    // TODO Add compile error for @optimizeFor occurring too late in a scope.
    try block.addUnreachable(true);
    return always_noreturn;
}

fn zirRetErrValue(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Zir.Inst.Index {
    const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
    const err_name = inst_data.get(sema.code);
    const src = inst_data.src();

    // Return the error code from the function.
    const kv = try sema.mod.getErrorValue(err_name);
    const result_inst = try sema.addConstant(
        try Type.Tag.error_set_single.create(sema.arena, kv.key),
        try Value.Tag.@"error".create(sema.arena, .{ .name = kv.key }),
    );
    return sema.analyzeRet(block, result_inst, src);
}

fn zirRetImplicit(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Zir.Inst.Index {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_tok;
    const operand = try sema.resolveInst(inst_data.operand);

    const r_brace_src = inst_data.src();
    const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = 0 };
    const base_tag = sema.fn_ret_ty.baseZigTypeTag();
    if (base_tag == .NoReturn) {
        const msg = msg: {
            const msg = try sema.errMsg(block, ret_ty_src, "function declared '{}' implicitly returns", .{
                sema.fn_ret_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, r_brace_src, msg, "control flow reaches end of body here", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    } else if (base_tag != .Void) {
        const msg = msg: {
            const msg = try sema.errMsg(block, ret_ty_src, "function with non-void return type '{}' implicitly returns", .{
                sema.fn_ret_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, r_brace_src, msg, "control flow reaches end of body here", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    return sema.analyzeRet(block, operand, .unneeded);
}

fn zirRetNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Index {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const src = inst_data.src();

    return sema.analyzeRet(block, operand, src);
}

fn zirRetLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Zir.Inst.Index {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const ret_ptr = try sema.resolveInst(inst_data.operand);

    if (block.is_comptime or block.inlining != null) {
        const operand = try sema.analyzeLoad(block, src, ret_ptr, src);
        return sema.analyzeRet(block, operand, src);
    }

    if (sema.wantErrorReturnTracing(sema.fn_ret_ty)) {
        const is_non_err = try sema.analyzePtrIsNonErr(block, src, ret_ptr);
        return sema.retWithErrTracing(block, src, is_non_err, .ret_load, ret_ptr);
    }

    _ = try block.addUnOp(.ret_load, ret_ptr);
    return always_noreturn;
}

fn retWithErrTracing(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    is_non_err: Air.Inst.Ref,
    ret_tag: Air.Inst.Tag,
    operand: Air.Inst.Ref,
) CompileError!Zir.Inst.Index {
    const need_check = switch (is_non_err) {
        .bool_true => {
            _ = try block.addUnOp(ret_tag, operand);
            return always_noreturn;
        },
        .bool_false => false,
        else => true,
    };
    const gpa = sema.gpa;
    const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
    const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
    const ptr_stack_trace_ty = try Type.Tag.single_mut_pointer.create(sema.arena, stack_trace_ty);
    const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
    const return_err_fn = try sema.getBuiltin("returnError");
    const args: [1]Air.Inst.Ref = .{err_return_trace};

    if (!need_check) {
        _ = try sema.analyzeCall(block, return_err_fn, src, src, .never_inline, false, &args, null);
        _ = try block.addUnOp(ret_tag, operand);
        return always_noreturn;
    }

    var then_block = block.makeSubBlock();
    defer then_block.instructions.deinit(gpa);
    _ = try then_block.addUnOp(ret_tag, operand);

    var else_block = block.makeSubBlock();
    defer else_block.instructions.deinit(gpa);
    _ = try sema.analyzeCall(&else_block, return_err_fn, src, src, .never_inline, false, &args, null);
    _ = try else_block.addUnOp(ret_tag, operand);

    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.CondBr).Struct.fields.len +
        then_block.instructions.items.len + else_block.instructions.items.len +
        @typeInfo(Air.Block).Struct.fields.len + 1);

    const cond_br_payload = sema.addExtraAssumeCapacity(Air.CondBr{
        .then_body_len = @intCast(u32, then_block.instructions.items.len),
        .else_body_len = @intCast(u32, else_block.instructions.items.len),
    });
    sema.air_extra.appendSliceAssumeCapacity(then_block.instructions.items);
    sema.air_extra.appendSliceAssumeCapacity(else_block.instructions.items);

    _ = try block.addInst(.{ .tag = .cond_br, .data = .{ .pl_op = .{
        .operand = is_non_err,
        .payload = cond_br_payload,
    } } });

    return always_noreturn;
}

fn wantErrorReturnTracing(sema: *Sema, fn_ret_ty: Type) bool {
    if (!sema.mod.backendSupportsFeature(.error_return_trace)) return false;

    return fn_ret_ty.isError() and
        sema.mod.comp.bin_file.options.error_return_tracing;
}

fn zirSaveErrRetIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].save_err_ret_index;

    if (!sema.mod.backendSupportsFeature(.error_return_trace)) return;
    if (!sema.mod.comp.bin_file.options.error_return_tracing) return;

    // This is only relevant at runtime.
    if (block.is_comptime or block.is_typeof) return;

    const save_index = inst_data.operand == .none or b: {
        const operand = try sema.resolveInst(inst_data.operand);
        const operand_ty = sema.typeOf(operand);
        break :b operand_ty.isError();
    };

    if (save_index)
        block.error_return_trace_index = try sema.analyzeSaveErrRetIndex(block);
}

fn zirRestoreErrRetIndex(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].restore_err_ret_index;
    const src = sema.src; // TODO

    // This is only relevant at runtime.
    if (start_block.is_comptime or start_block.is_typeof) return;

    if (!sema.mod.backendSupportsFeature(.error_return_trace)) return;
    if (!sema.owner_func.?.calls_or_awaits_errorable_fn) return;
    if (!sema.mod.comp.bin_file.options.error_return_tracing) return;

    const tracy = trace(@src());
    defer tracy.end();

    const saved_index = if (Zir.refToIndex(inst_data.block)) |zir_block| b: {
        var block = start_block;
        while (true) {
            if (block.label) |label| {
                if (label.zir_block == zir_block) {
                    const target_trace_index = if (block.parent) |parent_block| tgt: {
                        break :tgt parent_block.error_return_trace_index;
                    } else sema.error_return_trace_index_on_fn_entry;

                    if (start_block.error_return_trace_index != target_trace_index)
                        break :b target_trace_index;

                    return; // No need to restore
                }
            }
            block = block.parent.?;
        }
    } else b: {
        if (start_block.error_return_trace_index != sema.error_return_trace_index_on_fn_entry)
            break :b sema.error_return_trace_index_on_fn_entry;

        return; // No need to restore
    };

    assert(saved_index != .none); // The .error_return_trace_index field was dropped somewhere

    const operand = try sema.resolveInst(inst_data.operand);
    return sema.popErrorReturnTrace(start_block, src, operand, saved_index);
}

fn addToInferredErrorSet(sema: *Sema, uncasted_operand: Air.Inst.Ref) !void {
    assert(sema.fn_ret_ty.zigTypeTag() == .ErrorUnion);

    if (sema.fn_ret_ty.errorUnionSet().castTag(.error_set_inferred)) |payload| {
        const op_ty = sema.typeOf(uncasted_operand);
        switch (op_ty.zigTypeTag()) {
            .ErrorSet => {
                try payload.data.addErrorSet(sema.gpa, op_ty);
            },
            .ErrorUnion => {
                try payload.data.addErrorSet(sema.gpa, op_ty.errorUnionSet());
            },
            else => {},
        }
    }
}

fn analyzeRet(
    sema: *Sema,
    block: *Block,
    uncasted_operand: Air.Inst.Ref,
    src: LazySrcLoc,
) CompileError!Zir.Inst.Index {
    // Special case for returning an error to an inferred error set; we need to
    // add the error tag to the inferred error set of the in-scope function, so
    // that the coercion below works correctly.
    if (sema.fn_ret_ty.zigTypeTag() == .ErrorUnion) {
        try sema.addToInferredErrorSet(uncasted_operand);
    }
    const operand = sema.coerceExtra(block, sema.fn_ret_ty, uncasted_operand, src, .{ .is_ret = true }) catch |err| switch (err) {
        error.NotCoercible => unreachable,
        else => |e| return e,
    };

    if (block.inlining) |inlining| {
        if (block.is_comptime) {
            _ = try sema.resolveConstMaybeUndefVal(block, src, operand, "value being returned at comptime must be comptime-known");
            inlining.comptime_result = operand;
            return error.ComptimeReturn;
        }
        // We are inlining a function call; rewrite the `ret` as a `break`.
        try inlining.merges.results.append(sema.gpa, operand);
        _ = try block.addBr(inlining.merges.block_inst, operand);
        return always_noreturn;
    }

    try sema.resolveTypeLayout(sema.fn_ret_ty);

    if (sema.wantErrorReturnTracing(sema.fn_ret_ty)) {
        // Avoid adding a frame to the error return trace in case the value is comptime-known
        // to be not an error.
        const is_non_err = try sema.analyzeIsNonErr(block, src, operand);
        return sema.retWithErrTracing(block, src, is_non_err, .ret, operand);
    }

    _ = try block.addUnOp(.ret, operand);
    return always_noreturn;
}

fn floatOpAllowed(tag: Zir.Inst.Tag) bool {
    // extend this swich as additional operators are implemented
    return switch (tag) {
        .add, .sub, .mul, .div, .div_exact, .div_trunc, .div_floor, .mod, .rem, .mod_rem => true,
        else => false,
    };
}

fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].ptr_type;
    const extra = sema.code.extraData(Zir.Inst.PtrType, inst_data.payload_index);
    const elem_ty_src: LazySrcLoc = .{ .node_offset_ptr_elem = extra.data.src_node };
    const sentinel_src: LazySrcLoc = .{ .node_offset_ptr_sentinel = extra.data.src_node };
    const align_src: LazySrcLoc = .{ .node_offset_ptr_align = extra.data.src_node };
    const addrspace_src: LazySrcLoc = .{ .node_offset_ptr_addrspace = extra.data.src_node };
    const bitoffset_src: LazySrcLoc = .{ .node_offset_ptr_bitoffset = extra.data.src_node };
    const hostsize_src: LazySrcLoc = .{ .node_offset_ptr_hostsize = extra.data.src_node };

    const elem_ty = blk: {
        const air_inst = try sema.resolveInst(extra.data.elem_type);
        const ty = sema.analyzeAsType(block, elem_ty_src, air_inst) catch |err| {
            if (err == error.AnalysisFail and sema.err != null and sema.typeOf(air_inst).isSinglePointer()) {
                try sema.errNote(block, elem_ty_src, sema.err.?, "use '.*' to dereference pointer", .{});
            }
            return err;
        };
        if (ty.tag() == .generic_poison) return error.GenericPoison;
        break :blk ty;
    };
    const target = sema.mod.getTarget();

    var extra_i = extra.end;

    const sentinel = if (inst_data.flags.has_sentinel) blk: {
        const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
        extra_i += 1;
        break :blk (try sema.resolveInstConst(block, sentinel_src, ref, "pointer sentinel value must be comptime-known")).val;
    } else null;

    const abi_align: u32 = if (inst_data.flags.has_align) blk: {
        const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
        extra_i += 1;
        const coerced = try sema.coerce(block, Type.u32, try sema.resolveInst(ref), align_src);
        const val = try sema.resolveConstValue(block, align_src, coerced, "pointer alignment must be comptime-known");
        // Check if this happens to be the lazy alignment of our element type, in
        // which case we can make this 0 without resolving it.
        if (val.castTag(.lazy_align)) |payload| {
            if (payload.data.eql(elem_ty, sema.mod)) {
                break :blk 0;
            }
        }
        const abi_align = @intCast(u32, (try val.getUnsignedIntAdvanced(target, sema)).?);
        try sema.validateAlign(block, align_src, abi_align);
        break :blk abi_align;
    } else 0;

    const address_space: std.builtin.AddressSpace = if (inst_data.flags.has_addrspace) blk: {
        const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
        extra_i += 1;
        break :blk try sema.analyzeAddressSpace(block, addrspace_src, ref, .pointer);
    } else if (elem_ty.zigTypeTag() == .Fn and target.cpu.arch == .avr) .flash else .generic;

    const bit_offset = if (inst_data.flags.has_bit_range) blk: {
        const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
        extra_i += 1;
        const bit_offset = try sema.resolveInt(block, bitoffset_src, ref, Type.u16, "pointer bit-offset must be comptime-known");
        break :blk @intCast(u16, bit_offset);
    } else 0;

    const host_size: u16 = if (inst_data.flags.has_bit_range) blk: {
        const ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_i]);
        extra_i += 1;
        const host_size = try sema.resolveInt(block, hostsize_src, ref, Type.u16, "pointer host size must be comptime-known");
        break :blk @intCast(u16, host_size);
    } else 0;

    if (host_size != 0 and bit_offset >= host_size * 8) {
        return sema.fail(block, bitoffset_src, "bit offset starts after end of host integer", .{});
    }

    if (elem_ty.zigTypeTag() == .NoReturn) {
        return sema.fail(block, elem_ty_src, "pointer to noreturn not allowed", .{});
    } else if (elem_ty.zigTypeTag() == .Fn) {
        if (inst_data.size != .One) {
            return sema.fail(block, elem_ty_src, "function pointers must be single pointers", .{});
        }
        const fn_align = elem_ty.fnInfo().alignment;
        if (inst_data.flags.has_align and abi_align != 0 and fn_align != 0 and
            abi_align != fn_align)
        {
            return sema.fail(block, align_src, "function pointer alignment disagrees with function alignment", .{});
        }
    } else if (inst_data.size == .Many and elem_ty.zigTypeTag() == .Opaque) {
        return sema.fail(block, elem_ty_src, "unknown-length pointer to opaque not allowed", .{});
    } else if (inst_data.size == .C) {
        if (!try sema.validateExternType(elem_ty, .other)) {
            const msg = msg: {
                const msg = try sema.errMsg(block, elem_ty_src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                const src_decl = sema.mod.declPtr(block.src_decl);
                try sema.explainWhyTypeIsNotExtern(msg, elem_ty_src.toSrcLoc(src_decl), elem_ty, .other);

                try sema.addDeclaredHereNote(msg, elem_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (elem_ty.zigTypeTag() == .Opaque) {
            return sema.fail(block, elem_ty_src, "C pointers cannot point to opaque types", .{});
        }
    }

    const ty = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = elem_ty,
        .sentinel = sentinel,
        .@"align" = abi_align,
        .@"addrspace" = address_space,
        .bit_offset = bit_offset,
        .host_size = host_size,
        .mutable = inst_data.flags.is_mutable,
        .@"allowzero" = inst_data.flags.is_allowzero,
        .@"volatile" = inst_data.flags.is_volatile,
        .size = inst_data.size,
    });
    return sema.addType(ty);
}

fn zirStructInitEmpty(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const obj_ty = try sema.resolveType(block, src, inst_data.operand);

    switch (obj_ty.zigTypeTag()) {
        .Struct => return sema.structInitEmpty(block, obj_ty, src, src),
        .Array, .Vector => return sema.arrayInitEmpty(block, src, obj_ty),
        .Void => return sema.addConstant(obj_ty, Value.void),
        .Union => return sema.fail(block, src, "union initializer must initialize one field", .{}),
        else => return sema.failWithArrayInitNotSupported(block, src, obj_ty),
    }
}

fn structInitEmpty(
    sema: *Sema,
    block: *Block,
    obj_ty: Type,
    dest_src: LazySrcLoc,
    init_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const gpa = sema.gpa;
    // This logic must be synchronized with that in `zirStructInit`.
    const struct_ty = try sema.resolveTypeFields(obj_ty);

    // The init values to use for the struct instance.
    const field_inits = try gpa.alloc(Air.Inst.Ref, struct_ty.structFieldCount());
    defer gpa.free(field_inits);
    mem.set(Air.Inst.Ref, field_inits, .none);

    return sema.finishStructInit(block, init_src, dest_src, field_inits, struct_ty, false);
}

fn arrayInitEmpty(sema: *Sema, block: *Block, src: LazySrcLoc, obj_ty: Type) CompileError!Air.Inst.Ref {
    const arr_len = obj_ty.arrayLen();
    if (arr_len != 0) {
        if (obj_ty.zigTypeTag() == .Array) {
            return sema.fail(block, src, "expected {d} array elements; found 0", .{arr_len});
        } else {
            return sema.fail(block, src, "expected {d} vector elements; found 0", .{arr_len});
        }
    }
    if (obj_ty.sentinel()) |sentinel| {
        const val = try Value.Tag.empty_array_sentinel.create(sema.arena, sentinel);
        return sema.addConstant(obj_ty, val);
    } else {
        return sema.addConstant(obj_ty, Value.initTag(.empty_array));
    }
}

fn zirUnionInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const field_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const init_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.UnionInit, inst_data.payload_index).data;
    const union_ty = try sema.resolveType(block, ty_src, extra.union_type);
    const field_name = try sema.resolveConstString(block, field_src, extra.field_name, "name of field being initialized must be comptime-known");
    const init = try sema.resolveInst(extra.init);
    return sema.unionInit(block, init, init_src, union_ty, ty_src, field_name, field_src);
}

fn unionInit(
    sema: *Sema,
    block: *Block,
    uncasted_init: Air.Inst.Ref,
    init_src: LazySrcLoc,
    union_ty: Type,
    union_ty_src: LazySrcLoc,
    field_name: []const u8,
    field_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
    const field = union_ty.unionFields().values()[field_index];
    const init = try sema.coerce(block, field.ty, uncasted_init, init_src);

    if (try sema.resolveMaybeUndefVal(init)) |init_val| {
        const tag_ty = union_ty.unionTagTypeHypothetical();
        const enum_field_index = @intCast(u32, tag_ty.enumFieldIndex(field_name).?);
        const tag_val = try Value.Tag.enum_field_index.create(sema.arena, enum_field_index);
        return sema.addConstant(union_ty, try Value.Tag.@"union".create(sema.arena, .{
            .tag = tag_val,
            .val = init_val,
        }));
    }

    try sema.requireRuntimeBlock(block, init_src, null);
    _ = union_ty_src;
    try sema.queueFullTypeResolution(union_ty);
    return block.addUnionInit(union_ty, field_index, init);
}

fn zirStructInit(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const gpa = sema.gpa;
    const zir_datas = sema.code.instructions.items(.data);
    const inst_data = zir_datas[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.StructInit, inst_data.payload_index);
    const src = inst_data.src();

    const first_item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end).data;
    const first_field_type_data = zir_datas[first_item.field_type].pl_node;
    const first_field_type_extra = sema.code.extraData(Zir.Inst.FieldType, first_field_type_data.payload_index).data;
    const resolved_ty = try sema.resolveType(block, src, first_field_type_extra.container_type);
    try sema.resolveTypeLayout(resolved_ty);

    if (resolved_ty.zigTypeTag() == .Struct) {
        // This logic must be synchronized with that in `zirStructInitEmpty`.

        // Maps field index to field_type index of where it was already initialized.
        // For making sure all fields are accounted for and no fields are duplicated.
        const found_fields = try gpa.alloc(Zir.Inst.Index, resolved_ty.structFieldCount());
        defer gpa.free(found_fields);

        // The init values to use for the struct instance.
        const field_inits = try gpa.alloc(Air.Inst.Ref, resolved_ty.structFieldCount());
        defer gpa.free(field_inits);
        mem.set(Air.Inst.Ref, field_inits, .none);

        var field_i: u32 = 0;
        var extra_index = extra.end;

        const is_packed = resolved_ty.containerLayout() == .Packed;
        while (field_i < extra.data.fields_len) : (field_i += 1) {
            const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra_index);
            extra_index = item.end;

            const field_type_data = zir_datas[item.data.field_type].pl_node;
            const field_src: LazySrcLoc = .{ .node_offset_initializer = field_type_data.src_node };
            const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
            const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
            const field_index = if (resolved_ty.isTuple())
                try sema.tupleFieldIndex(block, resolved_ty, field_name, field_src)
            else
                try sema.structFieldIndex(block, resolved_ty, field_name, field_src);
            if (field_inits[field_index] != .none) {
                const other_field_type = found_fields[field_index];
                const other_field_type_data = zir_datas[other_field_type].pl_node;
                const other_field_src: LazySrcLoc = .{ .node_offset_initializer = other_field_type_data.src_node };
                const msg = msg: {
                    const msg = try sema.errMsg(block, field_src, "duplicate field", .{});
                    errdefer msg.destroy(gpa);
                    try sema.errNote(block, other_field_src, msg, "other field here", .{});
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
            found_fields[field_index] = item.data.field_type;
            field_inits[field_index] = try sema.resolveInst(item.data.init);
            if (!is_packed) if (resolved_ty.structFieldValueComptime(field_index)) |default_value| {
                const init_val = (try sema.resolveMaybeUndefVal(field_inits[field_index])) orelse {
                    return sema.failWithNeededComptime(block, field_src, "value stored in comptime field must be comptime-known");
                };

                if (!init_val.eql(default_value, resolved_ty.structFieldType(field_index), sema.mod)) {
                    return sema.failWithInvalidComptimeFieldStore(block, field_src, resolved_ty, field_index);
                }
            };
        }

        return sema.finishStructInit(block, src, src, field_inits, resolved_ty, is_ref);
    } else if (resolved_ty.zigTypeTag() == .Union) {
        if (extra.data.fields_len != 1) {
            return sema.fail(block, src, "union initialization expects exactly one field", .{});
        }

        const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end);

        const field_type_data = zir_datas[item.data.field_type].pl_node;
        const field_src: LazySrcLoc = .{ .node_offset_initializer = field_type_data.src_node };
        const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
        const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
        const field_index = try sema.unionFieldIndex(block, resolved_ty, field_name, field_src);
        const tag_ty = resolved_ty.unionTagTypeHypothetical();
        const enum_field_index = @intCast(u32, tag_ty.enumFieldIndex(field_name).?);
        const tag_val = try Value.Tag.enum_field_index.create(sema.arena, enum_field_index);

        const init_inst = try sema.resolveInst(item.data.init);
        if (try sema.resolveMaybeUndefVal(init_inst)) |val| {
            return sema.addConstantMaybeRef(
                block,
                resolved_ty,
                try Value.Tag.@"union".create(sema.arena, .{ .tag = tag_val, .val = val }),
                is_ref,
            );
        }

        if (is_ref) {
            const target = sema.mod.getTarget();
            const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
                .pointee_type = resolved_ty,
                .@"addrspace" = target_util.defaultAddressSpace(target, .local),
            });
            const alloc = try block.addTy(.alloc, alloc_ty);
            const field_ptr = try sema.unionFieldPtr(block, field_src, alloc, field_name, field_src, resolved_ty, true);
            try sema.storePtr(block, src, field_ptr, init_inst);
            const new_tag = try sema.addConstant(resolved_ty.unionTagTypeHypothetical(), tag_val);
            _ = try block.addBinOp(.set_union_tag, alloc, new_tag);
            return alloc;
        }

        try sema.requireRuntimeBlock(block, src, null);
        try sema.queueFullTypeResolution(resolved_ty);
        return block.addUnionInit(resolved_ty, field_index, init_inst);
    } else if (resolved_ty.isAnonStruct()) {
        return sema.fail(block, src, "TODO anon struct init validation", .{});
    }
    unreachable;
}

fn finishStructInit(
    sema: *Sema,
    block: *Block,
    init_src: LazySrcLoc,
    dest_src: LazySrcLoc,
    field_inits: []Air.Inst.Ref,
    struct_ty: Type,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const gpa = sema.gpa;

    var root_msg: ?*Module.ErrorMsg = null;
    errdefer if (root_msg) |msg| msg.destroy(sema.gpa);

    if (struct_ty.isAnonStruct()) {
        const struct_obj = struct_ty.castTag(.anon_struct).?.data;
        for (struct_obj.values, 0..) |default_val, i| {
            if (field_inits[i] != .none) continue;

            if (default_val.tag() == .unreachable_value) {
                const field_name = struct_obj.names[i];
                const template = "missing struct field: {s}";
                const args = .{field_name};
                if (root_msg) |msg| {
                    try sema.errNote(block, init_src, msg, template, args);
                } else {
                    root_msg = try sema.errMsg(block, init_src, template, args);
                }
            } else {
                field_inits[i] = try sema.addConstant(struct_obj.types[i], default_val);
            }
        }
    } else if (struct_ty.isTuple()) {
        var i: u32 = 0;
        const len = struct_ty.structFieldCount();
        while (i < len) : (i += 1) {
            if (field_inits[i] != .none) continue;

            const default_val = struct_ty.structFieldDefaultValue(i);
            if (default_val.tag() == .unreachable_value) {
                const template = "missing tuple field with index {d}";
                if (root_msg) |msg| {
                    try sema.errNote(block, init_src, msg, template, .{i});
                } else {
                    root_msg = try sema.errMsg(block, init_src, template, .{i});
                }
            } else {
                field_inits[i] = try sema.addConstant(struct_ty.structFieldType(i), default_val);
            }
        }
    } else {
        const struct_obj = struct_ty.castTag(.@"struct").?.data;
        for (struct_obj.fields.values(), 0..) |field, i| {
            if (field_inits[i] != .none) continue;

            if (field.default_val.tag() == .unreachable_value) {
                const field_name = struct_obj.fields.keys()[i];
                const template = "missing struct field: {s}";
                const args = .{field_name};
                if (root_msg) |msg| {
                    try sema.errNote(block, init_src, msg, template, args);
                } else {
                    root_msg = try sema.errMsg(block, init_src, template, args);
                }
            } else {
                field_inits[i] = try sema.addConstant(field.ty, field.default_val);
            }
        }
    }

    if (root_msg) |msg| {
        if (struct_ty.castTag(.@"struct")) |struct_obj| {
            const fqn = try struct_obj.data.getFullyQualifiedName(sema.mod);
            defer gpa.free(fqn);
            try sema.mod.errNoteNonLazy(
                struct_obj.data.srcLoc(sema.mod),
                msg,
                "struct '{s}' declared here",
                .{fqn},
            );
        }
        root_msg = null;
        return sema.failWithOwnedErrorMsg(msg);
    }

    const is_comptime = for (field_inits) |field_init| {
        if (!(try sema.isComptimeKnown(field_init))) {
            break false;
        }
    } else true;

    if (is_comptime) {
        const values = try sema.arena.alloc(Value, field_inits.len);
        for (field_inits, 0..) |field_init, i| {
            values[i] = (sema.resolveMaybeUndefVal(field_init) catch unreachable).?;
        }
        const struct_val = try Value.Tag.aggregate.create(sema.arena, values);
        return sema.addConstantMaybeRef(block, struct_ty, struct_val, is_ref);
    }

    if (is_ref) {
        try sema.resolveStructLayout(struct_ty);
        const target = sema.mod.getTarget();
        const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = struct_ty,
            .@"addrspace" = target_util.defaultAddressSpace(target, .local),
        });
        const alloc = try block.addTy(.alloc, alloc_ty);
        for (field_inits, 0..) |field_init, i_usize| {
            const i = @intCast(u32, i_usize);
            const field_src = dest_src;
            const field_ptr = try sema.structFieldPtrByIndex(block, dest_src, alloc, i, field_src, struct_ty, true);
            try sema.storePtr(block, dest_src, field_ptr, field_init);
        }

        return alloc;
    }

    try sema.requireRuntimeBlock(block, dest_src, null);
    try sema.queueFullTypeResolution(struct_ty);
    return block.addAggregateInit(struct_ty, field_inits);
}

fn zirStructInitAnon(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.StructInitAnon, inst_data.payload_index);
    const types = try sema.arena.alloc(Type, extra.data.fields_len);
    const values = try sema.arena.alloc(Value, types.len);
    var fields = std.StringArrayHashMapUnmanaged(u32){};
    defer fields.deinit(sema.gpa);
    try fields.ensureUnusedCapacity(sema.gpa, types.len);

    const opt_runtime_index = rs: {
        var runtime_index: ?usize = null;
        var extra_index = extra.end;
        for (types, 0..) |*field_ty, i| {
            const item = sema.code.extraData(Zir.Inst.StructInitAnon.Item, extra_index);
            extra_index = item.end;

            const name = sema.code.nullTerminatedString(item.data.field_name);
            const gop = fields.getOrPutAssumeCapacity(name);
            if (gop.found_existing) {
                const msg = msg: {
                    const decl = sema.mod.declPtr(block.src_decl);
                    const field_src = Module.initSrc(src.node_offset.x, sema.gpa, decl, i);
                    const msg = try sema.errMsg(block, field_src, "duplicate field", .{});
                    errdefer msg.destroy(sema.gpa);

                    const prev_source = Module.initSrc(src.node_offset.x, sema.gpa, decl, gop.value_ptr.*);
                    try sema.errNote(block, prev_source, msg, "other field here", .{});
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
            gop.value_ptr.* = @intCast(u32, i);

            const init = try sema.resolveInst(item.data.init);
            field_ty.* = sema.typeOf(init);
            if (types[i].zigTypeTag() == .Opaque) {
                const msg = msg: {
                    const decl = sema.mod.declPtr(block.src_decl);
                    const field_src = Module.initSrc(src.node_offset.x, sema.gpa, decl, i);
                    const msg = try sema.errMsg(block, field_src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});
                    errdefer msg.destroy(sema.gpa);

                    try sema.addDeclaredHereNote(msg, types[i]);
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
            if (try sema.resolveMaybeUndefVal(init)) |init_val| {
                values[i] = init_val;
            } else {
                values[i] = Value.initTag(.unreachable_value);
                runtime_index = i;
            }
        }
        break :rs runtime_index;
    };

    const tuple_ty = try Type.Tag.anon_struct.create(sema.arena, .{
        .names = try sema.arena.dupe([]const u8, fields.keys()),
        .types = types,
        .values = values,
    });

    const runtime_index = opt_runtime_index orelse {
        const tuple_val = try Value.Tag.aggregate.create(sema.arena, values);
        return sema.addConstantMaybeRef(block, tuple_ty, tuple_val, is_ref);
    };

    sema.requireRuntimeBlock(block, src, .unneeded) catch |err| switch (err) {
        error.NeededSourceLocation => {
            const decl = sema.mod.declPtr(block.src_decl);
            const field_src = Module.initSrc(src.node_offset.x, sema.gpa, decl, runtime_index);
            try sema.requireRuntimeBlock(block, src, field_src);
            unreachable;
        },
        else => |e| return e,
    };

    if (is_ref) {
        const target = sema.mod.getTarget();
        const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = tuple_ty,
            .@"addrspace" = target_util.defaultAddressSpace(target, .local),
        });
        const alloc = try block.addTy(.alloc, alloc_ty);
        var extra_index = extra.end;
        for (types, 0..) |field_ty, i_usize| {
            const i = @intCast(u32, i_usize);
            const item = sema.code.extraData(Zir.Inst.StructInitAnon.Item, extra_index);
            extra_index = item.end;

            const field_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                .mutable = true,
                .@"addrspace" = target_util.defaultAddressSpace(target, .local),
                .pointee_type = field_ty,
            });
            if (values[i].tag() == .unreachable_value) {
                const init = try sema.resolveInst(item.data.init);
                const field_ptr = try block.addStructFieldPtr(alloc, i, field_ptr_ty);
                _ = try block.addBinOp(.store, field_ptr, init);
            }
        }

        return alloc;
    }

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, types.len);
    var extra_index = extra.end;
    for (types, 0..) |_, i| {
        const item = sema.code.extraData(Zir.Inst.StructInitAnon.Item, extra_index);
        extra_index = item.end;
        element_refs[i] = try sema.resolveInst(item.data.init);
    }

    return block.addAggregateInit(tuple_ty, element_refs);
}

fn zirArrayInit(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const gpa = sema.gpa;
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();

    const extra = sema.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
    const args = sema.code.refSlice(extra.end, extra.data.operands_len);
    assert(args.len >= 2); // array_ty + at least one element

    const array_ty = try sema.resolveType(block, src, args[0]);
    const sentinel_val = array_ty.sentinel();

    const resolved_args = try gpa.alloc(Air.Inst.Ref, args.len - 1 + @boolToInt(sentinel_val != null));
    defer gpa.free(resolved_args);
    for (args[1..], 0..) |arg, i| {
        const resolved_arg = try sema.resolveInst(arg);
        const elem_ty = if (array_ty.zigTypeTag() == .Struct)
            array_ty.structFieldType(i)
        else
            array_ty.elemType2();
        resolved_args[i] = sema.coerce(block, elem_ty, resolved_arg, .unneeded) catch |err| switch (err) {
            error.NeededSourceLocation => {
                const decl = sema.mod.declPtr(block.src_decl);
                const elem_src = Module.initSrc(src.node_offset.x, sema.gpa, decl, i);
                _ = try sema.coerce(block, elem_ty, resolved_arg, elem_src);
                unreachable;
            },
            else => return err,
        };
    }

    if (sentinel_val) |some| {
        resolved_args[resolved_args.len - 1] = try sema.addConstant(array_ty.elemType2(), some);
    }

    const opt_runtime_index: ?u32 = for (resolved_args, 0..) |arg, i| {
        const comptime_known = try sema.isComptimeKnown(arg);
        if (!comptime_known) break @intCast(u32, i);
    } else null;

    const runtime_index = opt_runtime_index orelse {
        const elem_vals = try sema.arena.alloc(Value, resolved_args.len);

        for (resolved_args, 0..) |arg, i| {
            // We checked that all args are comptime above.
            elem_vals[i] = (sema.resolveMaybeUndefVal(arg) catch unreachable).?;
        }

        const array_val = try Value.Tag.aggregate.create(sema.arena, elem_vals);
        return sema.addConstantMaybeRef(block, array_ty, array_val, is_ref);
    };

    sema.requireRuntimeBlock(block, src, .unneeded) catch |err| switch (err) {
        error.NeededSourceLocation => {
            const decl = sema.mod.declPtr(block.src_decl);
            const elem_src = Module.initSrc(src.node_offset.x, sema.gpa, decl, runtime_index);
            try sema.requireRuntimeBlock(block, src, elem_src);
            unreachable;
        },
        else => return err,
    };
    try sema.queueFullTypeResolution(array_ty);

    if (is_ref) {
        const target = sema.mod.getTarget();
        const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = array_ty,
            .@"addrspace" = target_util.defaultAddressSpace(target, .local),
        });
        const alloc = try block.addTy(.alloc, alloc_ty);

        if (array_ty.isTuple()) {
            for (resolved_args, 0..) |arg, i| {
                const elem_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                    .mutable = true,
                    .@"addrspace" = target_util.defaultAddressSpace(target, .local),
                    .pointee_type = array_ty.structFieldType(i),
                });
                const elem_ptr_ty_ref = try sema.addType(elem_ptr_ty);

                const index = try sema.addIntUnsigned(Type.usize, i);
                const elem_ptr = try block.addPtrElemPtrTypeRef(alloc, index, elem_ptr_ty_ref);
                _ = try block.addBinOp(.store, elem_ptr, arg);
            }
            return alloc;
        }

        const elem_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
            .mutable = true,
            .@"addrspace" = target_util.defaultAddressSpace(target, .local),
            .pointee_type = array_ty.elemType2(),
        });
        const elem_ptr_ty_ref = try sema.addType(elem_ptr_ty);

        for (resolved_args, 0..) |arg, i| {
            const index = try sema.addIntUnsigned(Type.usize, i);
            const elem_ptr = try block.addPtrElemPtrTypeRef(alloc, index, elem_ptr_ty_ref);
            _ = try block.addBinOp(.store, elem_ptr, arg);
        }
        return alloc;
    }

    return block.addAggregateInit(array_ty, resolved_args);
}

fn zirArrayInitAnon(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    is_ref: bool,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const extra = sema.code.extraData(Zir.Inst.MultiOp, inst_data.payload_index);
    const operands = sema.code.refSlice(extra.end, extra.data.operands_len);

    const types = try sema.arena.alloc(Type, operands.len);
    const values = try sema.arena.alloc(Value, operands.len);

    const opt_runtime_src = rs: {
        var runtime_src: ?LazySrcLoc = null;
        for (operands, 0..) |operand, i| {
            const operand_src = src; // TODO better source location
            const elem = try sema.resolveInst(operand);
            types[i] = sema.typeOf(elem);
            if (types[i].zigTypeTag() == .Opaque) {
                const msg = msg: {
                    const msg = try sema.errMsg(block, operand_src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});
                    errdefer msg.destroy(sema.gpa);

                    try sema.addDeclaredHereNote(msg, types[i]);
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
            if (try sema.resolveMaybeUndefVal(elem)) |val| {
                values[i] = val;
            } else {
                values[i] = Value.initTag(.unreachable_value);
                runtime_src = operand_src;
            }
        }
        break :rs runtime_src;
    };

    const tuple_ty = try Type.Tag.tuple.create(sema.arena, .{
        .types = types,
        .values = values,
    });

    const runtime_src = opt_runtime_src orelse {
        const tuple_val = try Value.Tag.aggregate.create(sema.arena, values);
        return sema.addConstantMaybeRef(block, tuple_ty, tuple_val, is_ref);
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);

    if (is_ref) {
        const target = sema.mod.getTarget();
        const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = tuple_ty,
            .@"addrspace" = target_util.defaultAddressSpace(target, .local),
        });
        const alloc = try block.addTy(.alloc, alloc_ty);
        for (operands, 0..) |operand, i_usize| {
            const i = @intCast(u32, i_usize);
            const field_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
                .mutable = true,
                .@"addrspace" = target_util.defaultAddressSpace(target, .local),
                .pointee_type = types[i],
            });
            if (values[i].tag() == .unreachable_value) {
                const field_ptr = try block.addStructFieldPtr(alloc, i, field_ptr_ty);
                _ = try block.addBinOp(.store, field_ptr, try sema.resolveInst(operand));
            }
        }

        return alloc;
    }

    const element_refs = try sema.arena.alloc(Air.Inst.Ref, operands.len);
    for (operands, 0..) |operand, i| {
        element_refs[i] = try sema.resolveInst(operand);
    }

    return block.addAggregateInit(tuple_ty, element_refs);
}

fn addConstantMaybeRef(
    sema: *Sema,
    block: *Block,
    ty: Type,
    val: Value,
    is_ref: bool,
) !Air.Inst.Ref {
    if (!is_ref) return sema.addConstant(ty, val);

    var anon_decl = try block.startAnonDecl();
    defer anon_decl.deinit();
    const decl = try anon_decl.finish(
        try ty.copy(anon_decl.arena()),
        try val.copy(anon_decl.arena()),
        0, // default alignment
    );
    return sema.analyzeDeclRef(decl);
}

fn zirFieldTypeRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.FieldTypeRef, inst_data.payload_index).data;
    const ty_src = inst_data.src();
    const field_src = inst_data.src();
    const aggregate_ty = try sema.resolveType(block, ty_src, extra.container_type);
    const field_name = try sema.resolveConstString(block, field_src, extra.field_name, "field name must be comptime-known");
    return sema.fieldType(block, aggregate_ty, field_name, field_src, ty_src);
}

fn zirFieldType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
    const ty_src = inst_data.src();
    const field_name_src: LazySrcLoc = .{ .node_offset_field_name = inst_data.src_node };
    const aggregate_ty = try sema.resolveType(block, ty_src, extra.container_type);
    if (aggregate_ty.tag() == .var_args_param) return sema.addType(aggregate_ty);
    const field_name = sema.code.nullTerminatedString(extra.name_start);
    return sema.fieldType(block, aggregate_ty, field_name, field_name_src, ty_src);
}

fn fieldType(
    sema: *Sema,
    block: *Block,
    aggregate_ty: Type,
    field_name: []const u8,
    field_src: LazySrcLoc,
    ty_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    var cur_ty = aggregate_ty;
    while (true) {
        const resolved_ty = try sema.resolveTypeFields(cur_ty);
        cur_ty = resolved_ty;
        switch (cur_ty.zigTypeTag()) {
            .Struct => {
                if (cur_ty.isAnonStruct()) {
                    const field_index = try sema.anonStructFieldIndex(block, cur_ty, field_name, field_src);
                    return sema.addType(cur_ty.tupleFields().types[field_index]);
                }
                const struct_obj = cur_ty.castTag(.@"struct").?.data;
                const field = struct_obj.fields.get(field_name) orelse
                    return sema.failWithBadStructFieldAccess(block, struct_obj, field_src, field_name);
                return sema.addType(field.ty);
            },
            .Union => {
                const union_obj = cur_ty.cast(Type.Payload.Union).?.data;
                const field = union_obj.fields.get(field_name) orelse
                    return sema.failWithBadUnionFieldAccess(block, union_obj, field_src, field_name);
                return sema.addType(field.ty);
            },
            .Optional => {
                if (cur_ty.castTag(.optional)) |some| {
                    // Struct/array init through optional requires the child type to not be a pointer.
                    // If the child of .optional is a pointer it'll error on the next loop.
                    cur_ty = some.data;
                    continue;
                }
            },
            .ErrorUnion => {
                cur_ty = cur_ty.errorUnionPayload();
                continue;
            },
            else => {},
        }
        return sema.fail(block, ty_src, "expected struct or union; found '{}'", .{
            resolved_ty.fmt(sema.mod),
        });
    }
}

fn zirErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
    return sema.getErrorReturnTrace(block);
}

fn getErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
    const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
    const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
    const opt_ptr_stack_trace_ty = try Type.Tag.optional_single_mut_pointer.create(sema.arena, stack_trace_ty);

    if (sema.owner_func != null and
        sema.owner_func.?.calls_or_awaits_errorable_fn and
        sema.mod.comp.bin_file.options.error_return_tracing and
        sema.mod.backendSupportsFeature(.error_return_trace))
    {
        return block.addTy(.err_return_trace, opt_ptr_stack_trace_ty);
    }
    return sema.addConstant(opt_ptr_stack_trace_ty, Value.null);
}

fn zirFrame(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const src = LazySrcLoc.nodeOffset(@bitCast(i32, extended.operand));
    return sema.failWithUseOfAsync(block, src);
}

fn zirAlignOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ty = try sema.resolveType(block, operand_src, inst_data.operand);
    if (ty.isNoReturn()) {
        return sema.fail(block, operand_src, "no align available for type '{}'", .{ty.fmt(sema.mod)});
    }
    const target = sema.mod.getTarget();
    const val = try ty.lazyAbiAlignment(target, sema.arena);
    if (val.tag() == .lazy_align) {
        try sema.queueFullTypeResolution(ty);
    }
    return sema.addConstant(Type.comptime_int, val);
}

fn zirBoolToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        if (val.isUndef()) return sema.addConstUndef(Type.initTag(.u1));
        const bool_ints = [2]Air.Inst.Ref{ .zero, .one };
        return bool_ints[@boolToInt(val.toBool())];
    }
    return block.addUnOp(.bool_to_int, operand);
}

fn zirErrorName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };

    if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
        const bytes = val.castTag(.@"error").?.data.name;
        return sema.addStrLit(block, bytes);
    }

    // Similar to zirTagName, we have special AIR instruction for the error name in case an optimimzation pass
    // might be able to resolve the result at compile time.
    return block.addUnOp(.error_name, operand);
}

fn zirUnaryMath(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    air_tag: Air.Inst.Tag,
    comptime eval: fn (Value, Type, Allocator, *Module) Allocator.Error!Value,
) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_ty = sema.typeOf(operand);

    switch (operand_ty.zigTypeTag()) {
        .ComptimeFloat, .Float => {},
        .Vector => {
            const scalar_ty = operand_ty.scalarType();
            switch (scalar_ty.zigTypeTag()) {
                .ComptimeFloat, .Float => {},
                else => return sema.fail(block, operand_src, "expected vector of floats or float type, found '{}'", .{scalar_ty.fmt(sema.mod)}),
            }
        },
        else => return sema.fail(block, operand_src, "expected vector of floats or float type, found '{}'", .{operand_ty.fmt(sema.mod)}),
    }

    switch (operand_ty.zigTypeTag()) {
        .Vector => {
            const scalar_ty = operand_ty.scalarType();
            const vec_len = operand_ty.vectorLen();
            const result_ty = try Type.vector(sema.arena, vec_len, scalar_ty);
            if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef())
                    return sema.addConstUndef(result_ty);

                var elem_buf: Value.ElemValueBuffer = undefined;
                const elems = try sema.arena.alloc(Value, vec_len);
                for (elems, 0..) |*elem, i| {
                    const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
                    elem.* = try eval(elem_val, scalar_ty, sema.arena, sema.mod);
                }
                return sema.addConstant(
                    result_ty,
                    try Value.Tag.aggregate.create(sema.arena, elems),
                );
            }

            try sema.requireRuntimeBlock(block, operand_src, null);
            return block.addUnOp(air_tag, operand);
        },
        .ComptimeFloat, .Float => {
            if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
                if (operand_val.isUndef())
                    return sema.addConstUndef(operand_ty);
                const result_val = try eval(operand_val, operand_ty, sema.arena, sema.mod);
                return sema.addConstant(operand_ty, result_val);
            }

            try sema.requireRuntimeBlock(block, operand_src, null);
            return block.addUnOp(air_tag, operand);
        },
        else => unreachable,
    }
}

fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const src = inst_data.src();
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    const mod = sema.mod;

    try sema.resolveTypeLayout(operand_ty);
    const enum_ty = switch (operand_ty.zigTypeTag()) {
        .EnumLiteral => {
            const val = try sema.resolveConstValue(block, .unneeded, operand, "");
            const bytes = val.castTag(.enum_literal).?.data;
            return sema.addStrLit(block, bytes);
        },
        .Enum => operand_ty,
        .Union => operand_ty.unionTagType() orelse {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "union '{}' is untagged", .{
                    operand_ty.fmt(sema.mod),
                });
                errdefer msg.destroy(sema.gpa);
                try sema.addDeclaredHereNote(msg, operand_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        else => return sema.fail(block, operand_src, "expected enum or union; found '{}'", .{
            operand_ty.fmt(mod),
        }),
    };
    if (enum_ty.enumFieldCount() == 0) {
        // TODO I don't think this is the correct way to handle this but
        // it prevents a crash.
        return sema.fail(block, operand_src, "cannot get @tagName of empty enum '{}'", .{
            enum_ty.fmt(mod),
        });
    }
    const enum_decl_index = enum_ty.getOwnerDecl();
    const casted_operand = try sema.coerce(block, enum_ty, operand, operand_src);
    if (try sema.resolveDefinedValue(block, operand_src, casted_operand)) |val| {
        const field_index = enum_ty.enumTagFieldIndex(val, mod) orelse {
            const enum_decl = mod.declPtr(enum_decl_index);
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "no field with value '{}' in enum '{s}'", .{
                    val.fmtValue(enum_ty, sema.mod), enum_decl.name,
                });
                errdefer msg.destroy(sema.gpa);
                try mod.errNoteNonLazy(enum_decl.srcLoc(), msg, "declared here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        };
        const field_name = enum_ty.enumFieldName(field_index);
        return sema.addStrLit(block, field_name);
    }
    try sema.requireRuntimeBlock(block, src, operand_src);
    if (block.wantSafety() and sema.mod.backendSupportsFeature(.is_named_enum_value)) {
        const ok = try block.addUnOp(.is_named_enum_value, casted_operand);
        try sema.addSafetyCheck(block, ok, .invalid_enum_value);
    }
    // In case the value is runtime-known, we have an AIR instruction for this instead
    // of trying to lower it in Sema because an optimization pass may result in the operand
    // being comptime-known, which would let us elide the `tag_name` AIR instruction.
    return block.addUnOp(.tag_name, casted_operand);
}

fn zirReify(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const mod = sema.mod;
    const name_strategy = @intToEnum(Zir.Inst.NameStrategy, extended.small);
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const type_info_ty = try sema.getBuiltinType("Type");
    const uncasted_operand = try sema.resolveInst(extra.operand);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);
    const val = try sema.resolveConstValue(block, operand_src, type_info, "operand to @Type must be comptime-known");
    const union_val = val.cast(Value.Payload.Union).?.data;
    const target = mod.getTarget();
    const tag_index = type_info_ty.unionTagFieldIndex(union_val.tag, mod).?;
    if (union_val.val.anyUndef(mod)) return sema.failWithUseOfUndef(block, src);
    switch (@intToEnum(std.builtin.TypeId, tag_index)) {
        .Type => return Air.Inst.Ref.type_type,
        .Void => return Air.Inst.Ref.void_type,
        .Bool => return Air.Inst.Ref.bool_type,
        .NoReturn => return Air.Inst.Ref.noreturn_type,
        .ComptimeFloat => return Air.Inst.Ref.comptime_float_type,
        .ComptimeInt => return Air.Inst.Ref.comptime_int_type,
        .Undefined => return Air.Inst.Ref.undefined_type,
        .Null => return Air.Inst.Ref.null_type,
        .AnyFrame => return sema.failWithUseOfAsync(block, src),
        .EnumLiteral => return Air.Inst.Ref.enum_literal_type,
        .Int => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            const signedness_val = struct_val[0];
            const bits_val = struct_val[1];

            const signedness = signedness_val.toEnum(std.builtin.Signedness);
            const bits = @intCast(u16, bits_val.toUnsignedInt(target));
            const ty = switch (signedness) {
                .signed => try Type.Tag.int_signed.create(sema.arena, bits),
                .unsigned => try Type.Tag.int_unsigned.create(sema.arena, bits),
            };
            return sema.addType(ty);
        },
        .Vector => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            const len_val = struct_val[0];
            const child_val = struct_val[1];

            const len = len_val.toUnsignedInt(target);
            var buffer: Value.ToTypeBuffer = undefined;
            const child_ty = child_val.toType(&buffer);

            try sema.checkVectorElemType(block, src, child_ty);

            const ty = try Type.vector(sema.arena, len, try child_ty.copy(sema.arena));
            return sema.addType(ty);
        },
        .Float => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            // bits: comptime_int,
            const bits_val = struct_val[0];

            const bits = @intCast(u16, bits_val.toUnsignedInt(target));
            const ty = switch (bits) {
                16 => Type.f16,
                32 => Type.f32,
                64 => Type.f64,
                80 => Type.f80,
                128 => Type.f128,
                else => return sema.fail(block, src, "{}-bit float unsupported", .{bits}),
            };
            return sema.addType(ty);
        },
        .Pointer => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            const size_val = struct_val[0];
            const is_const_val = struct_val[1];
            const is_volatile_val = struct_val[2];
            const alignment_val = struct_val[3];
            const address_space_val = struct_val[4];
            const child_val = struct_val[5];
            const is_allowzero_val = struct_val[6];
            const sentinel_val = struct_val[7];

            if (!try sema.intFitsInType(alignment_val, Type.u32, null)) {
                return sema.fail(block, src, "alignment must fit in 'u32'", .{});
            }
            const abi_align = @intCast(u29, (try alignment_val.getUnsignedIntAdvanced(target, sema)).?);

            var buffer: Value.ToTypeBuffer = undefined;
            const unresolved_elem_ty = child_val.toType(&buffer);
            const elem_ty = if (abi_align == 0)
                unresolved_elem_ty
            else t: {
                const elem_ty = try sema.resolveTypeFields(unresolved_elem_ty);
                try sema.resolveTypeLayout(elem_ty);
                break :t elem_ty;
            };

            const ptr_size = size_val.toEnum(std.builtin.Type.Pointer.Size);

            var actual_sentinel: ?Value = null;
            if (!sentinel_val.isNull()) {
                if (ptr_size == .One or ptr_size == .C) {
                    return sema.fail(block, src, "sentinels are only allowed on slices and unknown-length pointers", .{});
                }
                const sentinel_ptr_val = sentinel_val.castTag(.opt_payload).?.data;
                const ptr_ty = try Type.ptr(sema.arena, mod, .{
                    .@"addrspace" = .generic,
                    .pointee_type = try elem_ty.copy(sema.arena),
                });
                actual_sentinel = (try sema.pointerDeref(block, src, sentinel_ptr_val, ptr_ty)).?;
            }

            if (elem_ty.zigTypeTag() == .NoReturn) {
                return sema.fail(block, src, "pointer to noreturn not allowed", .{});
            } else if (elem_ty.zigTypeTag() == .Fn) {
                if (ptr_size != .One) {
                    return sema.fail(block, src, "function pointers must be single pointers", .{});
                }
                const fn_align = elem_ty.fnInfo().alignment;
                if (abi_align != 0 and fn_align != 0 and
                    abi_align != fn_align)
                {
                    return sema.fail(block, src, "function pointer alignment disagrees with function alignment", .{});
                }
            } else if (ptr_size == .Many and elem_ty.zigTypeTag() == .Opaque) {
                return sema.fail(block, src, "unknown-length pointer to opaque not allowed", .{});
            } else if (ptr_size == .C) {
                if (!try sema.validateExternType(elem_ty, .other)) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(sema.mod)});
                        errdefer msg.destroy(sema.gpa);

                        const src_decl = sema.mod.declPtr(block.src_decl);
                        try sema.explainWhyTypeIsNotExtern(msg, src.toSrcLoc(src_decl), elem_ty, .other);

                        try sema.addDeclaredHereNote(msg, elem_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
                if (elem_ty.zigTypeTag() == .Opaque) {
                    return sema.fail(block, src, "C pointers cannot point to opaque types", .{});
                }
            }

            const ty = try Type.ptr(sema.arena, mod, .{
                .size = ptr_size,
                .mutable = !is_const_val.toBool(),
                .@"volatile" = is_volatile_val.toBool(),
                .@"align" = abi_align,
                .@"addrspace" = address_space_val.toEnum(std.builtin.AddressSpace),
                .pointee_type = try elem_ty.copy(sema.arena),
                .@"allowzero" = is_allowzero_val.toBool(),
                .sentinel = actual_sentinel,
            });
            return sema.addType(ty);
        },
        .Array => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            // len: comptime_int,
            const len_val = struct_val[0];
            // child: type,
            const child_val = struct_val[1];
            // sentinel: ?*const anyopaque,
            const sentinel_val = struct_val[2];

            const len = len_val.toUnsignedInt(target);
            var buffer: Value.ToTypeBuffer = undefined;
            const child_ty = try child_val.toType(&buffer).copy(sema.arena);
            const sentinel = if (sentinel_val.castTag(.opt_payload)) |p| blk: {
                const ptr_ty = try Type.ptr(sema.arena, mod, .{
                    .@"addrspace" = .generic,
                    .pointee_type = child_ty,
                });
                break :blk (try sema.pointerDeref(block, src, p.data, ptr_ty)).?;
            } else null;

            const ty = try Type.array(sema.arena, len, sentinel, child_ty, sema.mod);
            return sema.addType(ty);
        },
        .Optional => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            // child: type,
            const child_val = struct_val[0];

            var buffer: Value.ToTypeBuffer = undefined;
            const child_ty = try child_val.toType(&buffer).copy(sema.arena);

            const ty = try Type.optional(sema.arena, child_ty);
            return sema.addType(ty);
        },
        .ErrorUnion => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            // error_set: type,
            const error_set_val = struct_val[0];
            // payload: type,
            const payload_val = struct_val[1];

            var buffer: Value.ToTypeBuffer = undefined;
            const error_set_ty = try error_set_val.toType(&buffer).copy(sema.arena);
            const payload_ty = try payload_val.toType(&buffer).copy(sema.arena);

            if (error_set_ty.zigTypeTag() != .ErrorSet) {
                return sema.fail(block, src, "Type.ErrorUnion.error_set must be an error set type", .{});
            }

            const ty = try Type.Tag.error_union.create(sema.arena, .{
                .error_set = error_set_ty,
                .payload = payload_ty,
            });
            return sema.addType(ty);
        },
        .ErrorSet => {
            const payload_val = union_val.val.optionalValue() orelse
                return sema.addType(Type.initTag(.anyerror));
            const slice_val = payload_val.castTag(.slice).?.data;

            const len = try sema.usizeCast(block, src, slice_val.len.toUnsignedInt(mod.getTarget()));
            var names: Module.ErrorSet.NameMap = .{};
            try names.ensureUnusedCapacity(sema.arena, len);
            var i: usize = 0;
            while (i < len) : (i += 1) {
                var buf: Value.ElemValueBuffer = undefined;
                const elem_val = slice_val.ptr.elemValueBuffer(mod, i, &buf);
                const struct_val = elem_val.castTag(.aggregate).?.data;
                // TODO use reflection instead of magic numbers here
                // error_set: type,
                const name_val = struct_val[0];
                const name_str = try name_val.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, sema.mod);

                const kv = try mod.getErrorValue(name_str);
                const gop = names.getOrPutAssumeCapacity(kv.key);
                if (gop.found_existing) {
                    return sema.fail(block, src, "duplicate error '{s}'", .{name_str});
                }
            }

            // names must be sorted
            Module.ErrorSet.sortNames(&names);
            const ty = try Type.Tag.error_set_merged.create(sema.arena, names);
            return sema.addType(ty);
        },
        .Struct => {
            // TODO use reflection instead of magic numbers here
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // layout: containerlayout,
            const layout_val = struct_val[0];
            // backing_int: ?type,
            const backing_int_val = struct_val[1];
            // fields: []const enumfield,
            const fields_val = struct_val[2];
            // decls: []const declaration,
            const decls_val = struct_val[3];
            // is_tuple: bool,
            const is_tuple_val = struct_val[4];
            assert(struct_val.len == 5);

            const layout = layout_val.toEnum(std.builtin.Type.ContainerLayout);

            // Decls
            if (decls_val.sliceLen(mod) > 0) {
                return sema.fail(block, src, "reified structs must have no decls", .{});
            }

            if (layout != .Packed and !backing_int_val.isNull()) {
                return sema.fail(block, src, "non-packed struct does not support backing integer type", .{});
            }

            return try sema.reifyStruct(block, inst, src, layout, backing_int_val, fields_val, name_strategy, is_tuple_val.toBool());
        },
        .Enum => {
            const struct_val: []const Value = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            // tag_type: type,
            const tag_type_val = struct_val[0];
            // fields: []const EnumField,
            const fields_val = struct_val[1];
            // decls: []const Declaration,
            const decls_val = struct_val[2];
            // is_exhaustive: bool,
            const is_exhaustive_val = struct_val[3];

            // Decls
            if (decls_val.sliceLen(mod) > 0) {
                return sema.fail(block, src, "reified enums must have no decls", .{});
            }

            const gpa = sema.gpa;
            var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
            errdefer new_decl_arena.deinit();
            const new_decl_arena_allocator = new_decl_arena.allocator();

            // Define our empty enum decl
            const enum_obj = try new_decl_arena_allocator.create(Module.EnumFull);
            const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumFull);
            enum_ty_payload.* = .{
                .base = .{
                    .tag = if (!is_exhaustive_val.toBool())
                        .enum_nonexhaustive
                    else
                        .enum_full,
                },
                .data = enum_obj,
            };
            const enum_ty = Type.initPayload(&enum_ty_payload.base);
            const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
            const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
                .ty = Type.type,
                .val = enum_val,
            }, name_strategy, "enum", inst);
            const new_decl = mod.declPtr(new_decl_index);
            new_decl.owns_tv = true;
            errdefer mod.abortAnonDecl(new_decl_index);

            enum_obj.* = .{
                .owner_decl = new_decl_index,
                .tag_ty = Type.null,
                .tag_ty_inferred = false,
                .fields = .{},
                .values = .{},
                .namespace = .{
                    .parent = block.namespace,
                    .ty = enum_ty,
                    .file_scope = block.getFileScope(),
                },
            };

            // Enum tag type
            var buffer: Value.ToTypeBuffer = undefined;
            const int_tag_ty = try tag_type_val.toType(&buffer).copy(new_decl_arena_allocator);

            if (int_tag_ty.zigTypeTag() != .Int) {
                return sema.fail(block, src, "Type.Enum.tag_type must be an integer type", .{});
            }
            enum_obj.tag_ty = int_tag_ty;

            // Fields
            const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
            try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
            try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{
                .ty = enum_obj.tag_ty,
                .mod = mod,
            });

            var field_i: usize = 0;
            while (field_i < fields_len) : (field_i += 1) {
                const elem_val = try fields_val.elemValue(sema.mod, sema.arena, field_i);
                const field_struct_val: []const Value = elem_val.castTag(.aggregate).?.data;
                // TODO use reflection instead of magic numbers here
                // name: []const u8
                const name_val = field_struct_val[0];
                // value: comptime_int
                const value_val = field_struct_val[1];

                const field_name = try name_val.toAllocatedBytes(
                    Type.initTag(.const_slice_u8),
                    new_decl_arena_allocator,
                    sema.mod,
                );

                if (!try sema.intFitsInType(value_val, enum_obj.tag_ty, null)) {
                    // TODO: better source location
                    return sema.fail(block, src, "field '{s}' with enumeration value '{}' is too large for backing int type '{}'", .{
                        field_name,
                        value_val.fmtValue(Type.comptime_int, mod),
                        enum_obj.tag_ty.fmt(mod),
                    });
                }

                const gop_field = enum_obj.fields.getOrPutAssumeCapacity(field_name);
                if (gop_field.found_existing) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "duplicate enum field '{s}'", .{field_name});
                        errdefer msg.destroy(gpa);
                        try sema.errNote(block, src, msg, "other field here", .{});
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }

                const copied_tag_val = try value_val.copy(new_decl_arena_allocator);
                const gop_val = enum_obj.values.getOrPutAssumeCapacityContext(copied_tag_val, .{
                    .ty = enum_obj.tag_ty,
                    .mod = mod,
                });
                if (gop_val.found_existing) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "enum tag value {} already taken", .{value_val.fmtValue(Type.comptime_int, mod)});
                        errdefer msg.destroy(gpa);
                        try sema.errNote(block, src, msg, "other enum tag value here", .{});
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            }

            try new_decl.finalizeNewArena(&new_decl_arena);
            return sema.analyzeDeclVal(block, src, new_decl_index);
        },
        .Opaque => {
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // decls: []const Declaration,
            const decls_val = struct_val[0];

            // Decls
            if (decls_val.sliceLen(mod) > 0) {
                return sema.fail(block, src, "reified opaque must have no decls", .{});
            }

            var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
            errdefer new_decl_arena.deinit();
            const new_decl_arena_allocator = new_decl_arena.allocator();

            const opaque_obj = try new_decl_arena_allocator.create(Module.Opaque);
            const opaque_ty_payload = try new_decl_arena_allocator.create(Type.Payload.Opaque);
            opaque_ty_payload.* = .{
                .base = .{ .tag = .@"opaque" },
                .data = opaque_obj,
            };
            const opaque_ty = Type.initPayload(&opaque_ty_payload.base);
            const opaque_val = try Value.Tag.ty.create(new_decl_arena_allocator, opaque_ty);
            const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
                .ty = Type.type,
                .val = opaque_val,
            }, name_strategy, "opaque", inst);
            const new_decl = mod.declPtr(new_decl_index);
            new_decl.owns_tv = true;
            errdefer mod.abortAnonDecl(new_decl_index);

            opaque_obj.* = .{
                .owner_decl = new_decl_index,
                .namespace = .{
                    .parent = block.namespace,
                    .ty = opaque_ty,
                    .file_scope = block.getFileScope(),
                },
            };

            try new_decl.finalizeNewArena(&new_decl_arena);
            return sema.analyzeDeclVal(block, src, new_decl_index);
        },
        .Union => {
            // TODO use reflection instead of magic numbers here
            const struct_val = union_val.val.castTag(.aggregate).?.data;
            // layout: containerlayout,
            const layout_val = struct_val[0];
            // tag_type: ?type,
            const tag_type_val = struct_val[1];
            // fields: []const enumfield,
            const fields_val = struct_val[2];
            // decls: []const declaration,
            const decls_val = struct_val[3];

            // Decls
            if (decls_val.sliceLen(mod) > 0) {
                return sema.fail(block, src, "reified unions must have no decls", .{});
            }
            const layout = layout_val.toEnum(std.builtin.Type.ContainerLayout);

            var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
            errdefer new_decl_arena.deinit();
            const new_decl_arena_allocator = new_decl_arena.allocator();

            const union_obj = try new_decl_arena_allocator.create(Module.Union);
            const type_tag = if (!tag_type_val.isNull())
                Type.Tag.union_tagged
            else if (layout != .Auto)
                Type.Tag.@"union"
            else switch (block.sema.mod.optimizeMode()) {
                .Debug, .ReleaseSafe => Type.Tag.union_safety_tagged,
                .ReleaseFast, .ReleaseSmall => Type.Tag.@"union",
            };
            const union_payload = try new_decl_arena_allocator.create(Type.Payload.Union);
            union_payload.* = .{
                .base = .{ .tag = type_tag },
                .data = union_obj,
            };
            const union_ty = Type.initPayload(&union_payload.base);
            const new_union_val = try Value.Tag.ty.create(new_decl_arena_allocator, union_ty);
            const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
                .ty = Type.type,
                .val = new_union_val,
            }, name_strategy, "union", inst);
            const new_decl = mod.declPtr(new_decl_index);
            new_decl.owns_tv = true;
            errdefer mod.abortAnonDecl(new_decl_index);
            union_obj.* = .{
                .owner_decl = new_decl_index,
                .tag_ty = Type.initTag(.null),
                .fields = .{},
                .zir_index = inst,
                .layout = layout,
                .status = .have_field_types,
                .namespace = .{
                    .parent = block.namespace,
                    .ty = union_ty,
                    .file_scope = block.getFileScope(),
                },
            };

            // Tag type
            var tag_ty_field_names: ?Module.EnumFull.NameMap = null;
            var enum_field_names: ?*Module.EnumNumbered.NameMap = null;
            const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
            if (tag_type_val.optionalValue()) |payload_val| {
                var buffer: Value.ToTypeBuffer = undefined;
                union_obj.tag_ty = try payload_val.toType(&buffer).copy(new_decl_arena_allocator);

                if (union_obj.tag_ty.zigTypeTag() != .Enum) {
                    return sema.fail(block, src, "Type.Union.tag_type must be an enum type", .{});
                }
                tag_ty_field_names = try union_obj.tag_ty.enumFields().clone(sema.arena);
            } else {
                union_obj.tag_ty = try sema.generateUnionTagTypeSimple(block, fields_len, null);
                enum_field_names = &union_obj.tag_ty.castTag(.enum_simple).?.data.fields;
            }

            // Fields
            try union_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);

            var i: usize = 0;
            while (i < fields_len) : (i += 1) {
                const elem_val = try fields_val.elemValue(sema.mod, sema.arena, i);
                const field_struct_val = elem_val.castTag(.aggregate).?.data;
                // TODO use reflection instead of magic numbers here
                // name: []const u8
                const name_val = field_struct_val[0];
                // type: type,
                const type_val = field_struct_val[1];
                // alignment: comptime_int,
                const alignment_val = field_struct_val[2];

                const field_name = try name_val.toAllocatedBytes(
                    Type.initTag(.const_slice_u8),
                    new_decl_arena_allocator,
                    sema.mod,
                );

                if (enum_field_names) |set| {
                    set.putAssumeCapacity(field_name, {});
                }

                if (tag_ty_field_names) |*names| {
                    const enum_has_field = names.orderedRemove(field_name);
                    if (!enum_has_field) {
                        const msg = msg: {
                            const msg = try sema.errMsg(block, src, "no field named '{s}' in enum '{}'", .{ field_name, union_obj.tag_ty.fmt(sema.mod) });
                            errdefer msg.destroy(sema.gpa);
                            try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
                            break :msg msg;
                        };
                        return sema.failWithOwnedErrorMsg(msg);
                    }
                }

                const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
                if (gop.found_existing) {
                    // TODO: better source location
                    return sema.fail(block, src, "duplicate union field {s}", .{field_name});
                }

                var buffer: Value.ToTypeBuffer = undefined;
                const field_ty = try type_val.toType(&buffer).copy(new_decl_arena_allocator);
                gop.value_ptr.* = .{
                    .ty = field_ty,
                    .abi_align = @intCast(u32, (try alignment_val.getUnsignedIntAdvanced(target, sema)).?),
                };

                if (field_ty.zigTypeTag() == .Opaque) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "opaque types have unknown size and therefore cannot be directly embedded in unions", .{});
                        errdefer msg.destroy(sema.gpa);

                        try sema.addDeclaredHereNote(msg, field_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
                if (union_obj.layout == .Extern and !try sema.validateExternType(field_ty, .union_field)) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
                        errdefer msg.destroy(sema.gpa);

                        const src_decl = sema.mod.declPtr(block.src_decl);
                        try sema.explainWhyTypeIsNotExtern(msg, src.toSrcLoc(src_decl), field_ty, .union_field);

                        try sema.addDeclaredHereNote(msg, field_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                } else if (union_obj.layout == .Packed and !(validatePackedType(field_ty))) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
                        errdefer msg.destroy(sema.gpa);

                        const src_decl = sema.mod.declPtr(block.src_decl);
                        try sema.explainWhyTypeIsNotPacked(msg, src.toSrcLoc(src_decl), field_ty);

                        try sema.addDeclaredHereNote(msg, field_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            }

            if (tag_ty_field_names) |names| {
                if (names.count() > 0) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "enum field(s) missing in union", .{});
                        errdefer msg.destroy(sema.gpa);

                        const enum_ty = union_obj.tag_ty;
                        for (names.keys()) |field_name| {
                            const field_index = enum_ty.enumFieldIndex(field_name).?;
                            try sema.addFieldErrNote(enum_ty, field_index, msg, "field '{s}' missing, declared here", .{field_name});
                        }
                        try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            }

            try new_decl.finalizeNewArena(&new_decl_arena);
            return sema.analyzeDeclVal(block, src, new_decl_index);
        },
        .Fn => {
            const struct_val: []const Value = union_val.val.castTag(.aggregate).?.data;
            // TODO use reflection instead of magic numbers here
            // calling_convention: CallingConvention,
            const cc = struct_val[0].toEnum(std.builtin.CallingConvention);
            // alignment: comptime_int,
            const alignment_val = struct_val[1];
            // is_generic: bool,
            const is_generic = struct_val[2].toBool();
            // is_var_args: bool,
            const is_var_args = struct_val[3].toBool();
            // return_type: ?type,
            const return_type_val = struct_val[4];
            // args: []const Param,
            const args_val = struct_val[5];

            if (is_generic) {
                return sema.fail(block, src, "Type.Fn.is_generic must be false for @Type", .{});
            }

            if (is_var_args and cc != .C) {
                return sema.fail(block, src, "varargs functions must have C calling convention", .{});
            }

            const alignment = alignment: {
                if (!try sema.intFitsInType(alignment_val, Type.u32, null)) {
                    return sema.fail(block, src, "alignment must fit in 'u32'", .{});
                }
                const alignment = @intCast(u29, alignment_val.toUnsignedInt(target));
                if (alignment == target_util.defaultFunctionAlignment(target)) {
                    break :alignment 0;
                } else {
                    break :alignment alignment;
                }
            };
            const return_type = return_type_val.optionalValue() orelse
                return sema.fail(block, src, "Type.Fn.return_type must be non-null for @Type", .{});

            var buf: Value.ToTypeBuffer = undefined;

            const args_slice_val = args_val.castTag(.slice).?.data;
            const args_len = try sema.usizeCast(block, src, args_slice_val.len.toUnsignedInt(mod.getTarget()));

            const param_types = try sema.arena.alloc(Type, args_len);
            const comptime_params = try sema.arena.alloc(bool, args_len);

            var noalias_bits: u32 = 0;
            var i: usize = 0;
            while (i < args_len) : (i += 1) {
                var arg_buf: Value.ElemValueBuffer = undefined;
                const arg = args_slice_val.ptr.elemValueBuffer(mod, i, &arg_buf);
                const arg_val = arg.castTag(.aggregate).?.data;
                // TODO use reflection instead of magic numbers here
                // is_generic: bool,
                const arg_is_generic = arg_val[0].toBool();
                // is_noalias: bool,
                const arg_is_noalias = arg_val[1].toBool();
                // type: ?type,
                const param_type_opt_val = arg_val[2];

                if (arg_is_generic) {
                    return sema.fail(block, src, "Type.Fn.Param.is_generic must be false for @Type", .{});
                }

                const param_type_val = param_type_opt_val.optionalValue() orelse
                    return sema.fail(block, src, "Type.Fn.Param.arg_type must be non-null for @Type", .{});
                const param_type = try param_type_val.toType(&buf).copy(sema.arena);

                if (arg_is_noalias) {
                    if (!param_type.isPtrAtRuntime()) {
                        return sema.fail(block, src, "non-pointer parameter declared noalias", .{});
                    }
                    noalias_bits |= @as(u32, 1) << (std.math.cast(u5, i) orelse
                        return sema.fail(block, src, "this compiler implementation only supports 'noalias' on the first 32 parameters", .{}));
                }

                param_types[i] = param_type;
                comptime_params[i] = false;
            }

            var fn_info = Type.Payload.Function.Data{
                .param_types = param_types,
                .comptime_params = comptime_params.ptr,
                .noalias_bits = noalias_bits,
                .return_type = try return_type.toType(&buf).copy(sema.arena),
                .alignment = alignment,
                .cc = cc,
                .is_var_args = is_var_args,
                .is_generic = false,
                .align_is_generic = false,
                .cc_is_generic = false,
                .section_is_generic = false,
                .addrspace_is_generic = false,
            };

            const ty = try Type.Tag.function.create(sema.arena, fn_info);
            return sema.addType(ty);
        },
        .Frame => return sema.failWithUseOfAsync(block, src),
    }
}

fn reifyStruct(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    src: LazySrcLoc,
    layout: std.builtin.Type.ContainerLayout,
    backing_int_val: Value,
    fields_val: Value,
    name_strategy: Zir.Inst.NameStrategy,
    is_tuple: bool,
) CompileError!Air.Inst.Ref {
    var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const struct_obj = try new_decl_arena_allocator.create(Module.Struct);
    const struct_ty = try Type.Tag.@"struct".create(new_decl_arena_allocator, struct_obj);
    const new_struct_val = try Value.Tag.ty.create(new_decl_arena_allocator, struct_ty);
    const mod = sema.mod;
    const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
        .ty = Type.type,
        .val = new_struct_val,
    }, name_strategy, "struct", inst);
    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer mod.abortAnonDecl(new_decl_index);
    struct_obj.* = .{
        .owner_decl = new_decl_index,
        .fields = .{},
        .zir_index = inst,
        .layout = layout,
        .status = .have_field_types,
        .known_non_opv = false,
        .is_tuple = is_tuple,
        .namespace = .{
            .parent = block.namespace,
            .ty = struct_ty,
            .file_scope = block.getFileScope(),
        },
    };

    const target = mod.getTarget();

    // Fields
    const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
    try struct_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
    var i: usize = 0;
    while (i < fields_len) : (i += 1) {
        const elem_val = try fields_val.elemValue(sema.mod, sema.arena, i);
        const field_struct_val = elem_val.castTag(.aggregate).?.data;
        // TODO use reflection instead of magic numbers here
        // name: []const u8
        const name_val = field_struct_val[0];
        // type: type,
        const type_val = field_struct_val[1];
        // default_value: ?*const anyopaque,
        const default_value_val = field_struct_val[2];
        // is_comptime: bool,
        const is_comptime_val = field_struct_val[3];
        // alignment: comptime_int,
        const alignment_val = field_struct_val[4];

        if (!try sema.intFitsInType(alignment_val, Type.u32, null)) {
            return sema.fail(block, src, "alignment must fit in 'u32'", .{});
        }
        const abi_align = @intCast(u29, (try alignment_val.getUnsignedIntAdvanced(target, sema)).?);

        if (layout == .Packed) {
            if (abi_align != 0) return sema.fail(block, src, "alignment in a packed struct field must be set to 0", .{});
            if (is_comptime_val.toBool()) return sema.fail(block, src, "packed struct fields cannot be marked comptime", .{});
        }
        if (layout == .Extern and is_comptime_val.toBool()) {
            return sema.fail(block, src, "extern struct fields cannot be marked comptime", .{});
        }

        const field_name = try name_val.toAllocatedBytes(
            Type.initTag(.const_slice_u8),
            new_decl_arena_allocator,
            mod,
        );

        if (is_tuple) {
            const field_index = std.fmt.parseUnsigned(u32, field_name, 10) catch {
                return sema.fail(
                    block,
                    src,
                    "tuple cannot have non-numeric field '{s}'",
                    .{field_name},
                );
            };

            if (field_index >= fields_len) {
                return sema.fail(
                    block,
                    src,
                    "tuple field {} exceeds tuple field count",
                    .{field_index},
                );
            }
        }
        const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
        if (gop.found_existing) {
            // TODO: better source location
            return sema.fail(block, src, "duplicate struct field {s}", .{field_name});
        }

        const default_val = if (default_value_val.optionalValue()) |opt_val| blk: {
            const payload_val = if (opt_val.pointerDecl()) |opt_decl|
                mod.declPtr(opt_decl).val
            else
                opt_val;
            break :blk try payload_val.copy(new_decl_arena_allocator);
        } else Value.initTag(.unreachable_value);
        if (is_comptime_val.toBool() and default_val.tag() == .unreachable_value) {
            return sema.fail(block, src, "comptime field without default initialization value", .{});
        }

        var buffer: Value.ToTypeBuffer = undefined;
        const field_ty = try type_val.toType(&buffer).copy(new_decl_arena_allocator);
        gop.value_ptr.* = .{
            .ty = field_ty,
            .abi_align = abi_align,
            .default_val = default_val,
            .is_comptime = is_comptime_val.toBool(),
            .offset = undefined,
        };

        if (field_ty.zigTypeTag() == .Opaque) {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});
                errdefer msg.destroy(sema.gpa);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (field_ty.zigTypeTag() == .NoReturn) {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "struct fields cannot be 'noreturn'", .{});
                errdefer msg.destroy(sema.gpa);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (struct_obj.layout == .Extern and !try sema.validateExternType(field_ty, .struct_field)) {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                const src_decl = sema.mod.declPtr(block.src_decl);
                try sema.explainWhyTypeIsNotExtern(msg, src.toSrcLoc(src_decl), field_ty, .struct_field);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        } else if (struct_obj.layout == .Packed and !(validatePackedType(field_ty))) {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                const src_decl = sema.mod.declPtr(block.src_decl);
                try sema.explainWhyTypeIsNotPacked(msg, src.toSrcLoc(src_decl), field_ty);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
    }

    if (layout == .Packed) {
        struct_obj.status = .layout_wip;

        for (struct_obj.fields.values(), 0..) |field, index| {
            sema.resolveTypeLayout(field.ty) catch |err| switch (err) {
                error.AnalysisFail => {
                    const msg = sema.err orelse return err;
                    try sema.addFieldErrNote(struct_ty, index, msg, "while checking this field", .{});
                    return err;
                },
                else => return err,
            };
        }

        var fields_bit_sum: u64 = 0;
        for (struct_obj.fields.values()) |field| {
            fields_bit_sum += field.ty.bitSize(target);
        }

        if (backing_int_val.optionalValue()) |payload| {
            var buf: Value.ToTypeBuffer = undefined;
            const backing_int_ty = payload.toType(&buf);
            try sema.checkBackingIntType(block, src, backing_int_ty, fields_bit_sum);
            struct_obj.backing_int_ty = try backing_int_ty.copy(new_decl_arena_allocator);
        } else {
            var buf: Type.Payload.Bits = .{
                .base = .{ .tag = .int_unsigned },
                .data = @intCast(u16, fields_bit_sum),
            };
            struct_obj.backing_int_ty = try Type.initPayload(&buf.base).copy(new_decl_arena_allocator);
        }

        struct_obj.status = .have_layout;
    }

    try new_decl.finalizeNewArena(&new_decl_arena);
    return sema.analyzeDeclVal(block, src, new_decl_index);
}

fn zirAddrSpaceCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const addrspace_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };

    const dest_addrspace = try sema.analyzeAddressSpace(block, addrspace_src, extra.lhs, .pointer);
    const ptr = try sema.resolveInst(extra.rhs);
    const ptr_ty = sema.typeOf(ptr);

    try sema.checkPtrOperand(block, ptr_src, ptr_ty);

    var ptr_info = ptr_ty.ptrInfo().data;
    const src_addrspace = ptr_info.@"addrspace";
    if (!target_util.addrSpaceCastIsValid(sema.mod.getTarget(), src_addrspace, dest_addrspace)) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "invalid address space cast", .{});
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, src, msg, "address space '{s}' is not compatible with address space '{s}'", .{ @tagName(src_addrspace), @tagName(dest_addrspace) });
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    ptr_info.@"addrspace" = dest_addrspace;
    const dest_ptr_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);
    const dest_ty = if (ptr_ty.zigTypeTag() == .Optional)
        try Type.optional(sema.arena, dest_ptr_ty)
    else
        dest_ptr_ty;

    try sema.requireRuntimeBlock(block, src, ptr_src);
    // TODO: Address space cast safety?

    return block.addInst(.{
        .tag = .addrspace_cast,
        .data = .{ .ty_op = .{
            .ty = try sema.addType(dest_ty),
            .operand = ptr,
        } },
    });
}

fn resolveVaListRef(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) CompileError!Air.Inst.Ref {
    const va_list_ty = try sema.getBuiltinType("VaList");
    const va_list_ptr = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = va_list_ty,
        .mutable = true,
        .@"addrspace" = .generic,
    });

    const inst = try sema.resolveInst(zir_ref);
    return sema.coerce(block, va_list_ptr, inst, src);
}

fn zirCVaArg(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const va_list_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };

    const va_list_ref = try sema.resolveVaListRef(block, va_list_src, extra.lhs);
    const arg_ty = try sema.resolveType(block, ty_src, extra.rhs);

    if (!try sema.validateExternType(arg_ty, .param_ty)) {
        const msg = msg: {
            const msg = try sema.errMsg(block, ty_src, "cannot get '{}' from variadic argument", .{arg_ty.fmt(sema.mod)});
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsNotExtern(msg, ty_src.toSrcLoc(src_decl), arg_ty, .param_ty);

            try sema.addDeclaredHereNote(msg, arg_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.c_va_arg, arg_ty, va_list_ref);
}

fn zirCVaCopy(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const va_list_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };

    const va_list_ref = try sema.resolveVaListRef(block, va_list_src, extra.operand);
    const va_list_ty = try sema.getBuiltinType("VaList");

    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.c_va_copy, va_list_ty, va_list_ref);
}

fn zirCVaEnd(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const va_list_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };

    const va_list_ref = try sema.resolveVaListRef(block, va_list_src, extra.operand);

    try sema.requireRuntimeBlock(block, src, null);
    return block.addUnOp(.c_va_end, va_list_ref);
}

fn zirCVaStart(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const src = LazySrcLoc.nodeOffset(@bitCast(i32, extended.operand));

    const va_list_ty = try sema.getBuiltinType("VaList");
    try sema.requireRuntimeBlock(block, src, null);
    return block.addInst(.{
        .tag = .c_va_start,
        .data = .{ .ty = va_list_ty },
    });
}

fn zirTypeName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ty = try sema.resolveType(block, ty_src, inst_data.operand);

    var anon_decl = try block.startAnonDecl();
    defer anon_decl.deinit();

    const bytes = try ty.nameAllocArena(anon_decl.arena(), sema.mod);

    const new_decl = try anon_decl.finish(
        try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
        try Value.Tag.bytes.create(anon_decl.arena(), bytes[0 .. bytes.len + 1]),
        0, // default alignment
    );

    return sema.analyzeDeclRef(new_decl);
}

fn zirFrameType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    return sema.failWithUseOfAsync(block, src);
}

fn zirFrameSize(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    return sema.failWithUseOfAsync(block, src);
}

fn zirFloatToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const dest_ty = try sema.resolveType(block, ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);
    const operand_ty = sema.typeOf(operand);

    _ = try sema.checkIntType(block, ty_src, dest_ty);
    try sema.checkFloatType(block, operand_src, operand_ty);

    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        const result_val = try sema.floatToInt(block, operand_src, val, operand_ty, dest_ty);
        return sema.addConstant(dest_ty, result_val);
    } else if (dest_ty.zigTypeTag() == .ComptimeInt) {
        return sema.failWithNeededComptime(block, operand_src, "value being casted to 'comptime_int' must be comptime-known");
    }

    try sema.requireRuntimeBlock(block, inst_data.src(), operand_src);
    if (dest_ty.intInfo(sema.mod.getTarget()).bits == 0) {
        if (block.wantSafety()) {
            const ok = try block.addBinOp(if (block.float_mode == .Optimized) .cmp_eq_optimized else .cmp_eq, operand, try sema.addConstant(operand_ty, Value.zero));
            try sema.addSafetyCheck(block, ok, .integer_part_out_of_bounds);
        }
        return sema.addConstant(dest_ty, Value.zero);
    }
    const result = try block.addTyOp(if (block.float_mode == .Optimized) .float_to_int_optimized else .float_to_int, dest_ty, operand);
    if (block.wantSafety()) {
        const back = try block.addTyOp(.int_to_float, operand_ty, result);
        const diff = try block.addBinOp(.sub, operand, back);
        const ok_pos = try block.addBinOp(if (block.float_mode == .Optimized) .cmp_lt_optimized else .cmp_lt, diff, try sema.addConstant(operand_ty, Value.one));
        const ok_neg = try block.addBinOp(if (block.float_mode == .Optimized) .cmp_gt_optimized else .cmp_gt, diff, try sema.addConstant(operand_ty, Value.negative_one));
        const ok = try block.addBinOp(.bool_and, ok_pos, ok_neg);
        try sema.addSafetyCheck(block, ok, .integer_part_out_of_bounds);
    }
    return result;
}

fn zirIntToFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const dest_ty = try sema.resolveType(block, ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);
    const operand_ty = sema.typeOf(operand);

    try sema.checkFloatType(block, ty_src, dest_ty);
    _ = try sema.checkIntType(block, operand_src, operand_ty);

    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        const result_val = try val.intToFloatAdvanced(sema.arena, operand_ty, dest_ty, sema.mod, sema);
        return sema.addConstant(dest_ty, result_val);
    } else if (dest_ty.zigTypeTag() == .ComptimeFloat) {
        return sema.failWithNeededComptime(block, operand_src, "value being casted to 'comptime_float' must be comptime-known");
    }

    try sema.requireRuntimeBlock(block, inst_data.src(), operand_src);
    return block.addTyOp(.int_to_float, dest_ty, operand);
}

fn zirIntToPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();

    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;

    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const operand_res = try sema.resolveInst(extra.rhs);
    const operand_coerced = try sema.coerce(block, Type.usize, operand_res, operand_src);

    const type_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ptr_ty = try sema.resolveType(block, src, extra.lhs);
    try sema.checkPtrType(block, type_src, ptr_ty);
    const elem_ty = ptr_ty.elemType2();
    const target = sema.mod.getTarget();
    const ptr_align = try ptr_ty.ptrAlignmentAdvanced(target, sema);

    if (try sema.resolveDefinedValue(block, operand_src, operand_coerced)) |val| {
        const addr = val.toUnsignedInt(target);
        if (!ptr_ty.isAllowzeroPtr() and addr == 0)
            return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{ptr_ty.fmt(sema.mod)});
        if (addr != 0 and ptr_align != 0 and addr % ptr_align != 0)
            return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{ptr_ty.fmt(sema.mod)});

        const val_payload = try sema.arena.create(Value.Payload.U64);
        val_payload.* = .{
            .base = .{ .tag = .int_u64 },
            .data = addr,
        };
        return sema.addConstant(ptr_ty, Value.initPayload(&val_payload.base));
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    if (block.wantSafety() and try sema.typeHasRuntimeBits(elem_ty)) {
        if (!ptr_ty.isAllowzeroPtr()) {
            const is_non_zero = try block.addBinOp(.cmp_neq, operand_coerced, .zero_usize);
            try sema.addSafetyCheck(block, is_non_zero, .cast_to_null);
        }

        if (ptr_align > 1) {
            const val_payload = try sema.arena.create(Value.Payload.U64);
            val_payload.* = .{
                .base = .{ .tag = .int_u64 },
                .data = ptr_align - 1,
            };
            const align_minus_1 = try sema.addConstant(
                Type.usize,
                Value.initPayload(&val_payload.base),
            );
            const remainder = try block.addBinOp(.bit_and, operand_coerced, align_minus_1);
            const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
            try sema.addSafetyCheck(block, is_aligned, .incorrect_alignment);
        }
    }
    return block.addBitCast(ptr_ty, operand_coerced);
}

fn zirErrSetCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
    const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);
    const operand_ty = sema.typeOf(operand);
    try sema.checkErrorSetType(block, dest_ty_src, dest_ty);
    try sema.checkErrorSetType(block, operand_src, operand_ty);

    // operand must be defined since it can be an invalid error value
    const maybe_operand_val = try sema.resolveDefinedValue(block, operand_src, operand);

    if (disjoint: {
        // Try avoiding resolving inferred error sets if we can
        if (!dest_ty.isAnyError() and dest_ty.errorSetNames().len == 0) break :disjoint true;
        if (!operand_ty.isAnyError() and operand_ty.errorSetNames().len == 0) break :disjoint true;
        if (dest_ty.isAnyError()) break :disjoint false;
        if (operand_ty.isAnyError()) break :disjoint false;
        for (dest_ty.errorSetNames()) |dest_err_name|
            if (operand_ty.errorSetHasField(dest_err_name))
                break :disjoint false;

        if (dest_ty.tag() != .error_set_inferred and operand_ty.tag() != .error_set_inferred)
            break :disjoint true;

        try sema.resolveInferredErrorSetTy(block, dest_ty_src, dest_ty);
        try sema.resolveInferredErrorSetTy(block, operand_src, operand_ty);
        for (dest_ty.errorSetNames()) |dest_err_name|
            if (operand_ty.errorSetHasField(dest_err_name))
                break :disjoint false;

        break :disjoint true;
    }) {
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                src,
                "error sets '{}' and '{}' have no common errors",
                .{ operand_ty.fmt(sema.mod), dest_ty.fmt(sema.mod) },
            );
            errdefer msg.destroy(sema.gpa);
            try sema.addDeclaredHereNote(msg, operand_ty);
            try sema.addDeclaredHereNote(msg, dest_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (maybe_operand_val) |val| {
        if (!dest_ty.isAnyError()) {
            const error_name = val.castTag(.@"error").?.data.name;
            if (!dest_ty.errorSetHasField(error_name)) {
                const msg = msg: {
                    const msg = try sema.errMsg(
                        block,
                        src,
                        "'error.{s}' not a member of error set '{}'",
                        .{ error_name, dest_ty.fmt(sema.mod) },
                    );
                    errdefer msg.destroy(sema.gpa);
                    try sema.addDeclaredHereNote(msg, dest_ty);
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
        }

        return sema.addConstant(dest_ty, val);
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    if (block.wantSafety() and !dest_ty.isAnyError() and sema.mod.backendSupportsFeature(.error_set_has_value)) {
        const err_int_inst = try block.addBitCast(Type.err_int, operand);
        const ok = try block.addTyOp(.error_set_has_value, dest_ty, err_int_inst);
        try sema.addSafetyCheck(block, ok, .invalid_error_code);
    }
    return block.addBitCast(dest_ty, operand);
}

fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);
    const operand_ty = sema.typeOf(operand);
    const target = sema.mod.getTarget();

    try sema.checkPtrType(block, dest_ty_src, dest_ty);
    try sema.checkPtrOperand(block, operand_src, operand_ty);

    const operand_info = operand_ty.ptrInfo().data;
    const dest_info = dest_ty.ptrInfo().data;
    if (!operand_info.mutable and dest_info.mutable) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "cast discards const qualifier", .{});
            errdefer msg.destroy(sema.gpa);

            try sema.errNote(block, src, msg, "consider using '@constCast'", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    if (operand_info.@"volatile" and !dest_info.@"volatile") {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "cast discards volatile qualifier", .{});
            errdefer msg.destroy(sema.gpa);

            try sema.errNote(block, src, msg, "consider using '@volatileCast'", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    if (operand_info.@"addrspace" != dest_info.@"addrspace") {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "cast changes pointer address space", .{});
            errdefer msg.destroy(sema.gpa);

            try sema.errNote(block, src, msg, "consider using '@addrSpaceCast'", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const dest_is_slice = dest_ty.isSlice();
    const operand_is_slice = operand_ty.isSlice();
    if (dest_is_slice and !operand_is_slice) {
        return sema.fail(block, dest_ty_src, "illegal pointer cast to slice", .{});
    }
    const ptr = if (operand_is_slice and !dest_is_slice)
        try sema.analyzeSlicePtr(block, operand_src, operand, operand_ty)
    else
        operand;

    const dest_elem_ty = dest_ty.elemType2();
    try sema.resolveTypeLayout(dest_elem_ty);
    const dest_align = dest_ty.ptrAlignment(target);

    const operand_elem_ty = operand_ty.elemType2();
    try sema.resolveTypeLayout(operand_elem_ty);
    const operand_align = operand_ty.ptrAlignment(target);

    // If the destination is less aligned than the source, preserve the source alignment
    const aligned_dest_ty = if (operand_align <= dest_align) dest_ty else blk: {
        // Unwrap the pointer (or pointer-like optional) type, set alignment, and re-wrap into result
        if (dest_ty.zigTypeTag() == .Optional) {
            var buf: Type.Payload.ElemType = undefined;
            var dest_ptr_info = dest_ty.optionalChild(&buf).ptrInfo().data;
            dest_ptr_info.@"align" = operand_align;
            break :blk try Type.optional(sema.arena, try Type.ptr(sema.arena, sema.mod, dest_ptr_info));
        } else {
            var dest_ptr_info = dest_ty.ptrInfo().data;
            dest_ptr_info.@"align" = operand_align;
            break :blk try Type.ptr(sema.arena, sema.mod, dest_ptr_info);
        }
    };

    if (dest_is_slice) {
        const operand_elem_size = operand_elem_ty.abiSize(target);
        const dest_elem_size = dest_elem_ty.abiSize(target);
        if (operand_elem_size != dest_elem_size) {
            return sema.fail(block, dest_ty_src, "TODO: implement @ptrCast between slices changing the length", .{});
        }
    }

    if (dest_align > operand_align) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "cast increases pointer alignment", .{});
            errdefer msg.destroy(sema.gpa);

            try sema.errNote(block, operand_src, msg, "'{}' has alignment '{d}'", .{
                operand_ty.fmt(sema.mod), operand_align,
            });
            try sema.errNote(block, dest_ty_src, msg, "'{}' has alignment '{d}'", .{
                dest_ty.fmt(sema.mod), dest_align,
            });

            try sema.errNote(block, src, msg, "consider using '@alignCast'", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (try sema.resolveMaybeUndefVal(ptr)) |operand_val| {
        if (!dest_ty.ptrAllowsZero() and operand_val.isUndef()) {
            return sema.failWithUseOfUndef(block, operand_src);
        }
        if (!dest_ty.ptrAllowsZero() and operand_val.isNull()) {
            return sema.fail(block, operand_src, "null pointer casted to type {}", .{dest_ty.fmt(sema.mod)});
        }
        if (dest_ty.zigTypeTag() == .Optional and sema.typeOf(ptr).zigTypeTag() != .Optional) {
            return sema.addConstant(dest_ty, try Value.Tag.opt_payload.create(sema.arena, operand_val));
        }
        return sema.addConstant(aligned_dest_ty, operand_val);
    }

    try sema.requireRuntimeBlock(block, src, null);
    if (block.wantSafety() and operand_ty.ptrAllowsZero() and !dest_ty.ptrAllowsZero() and
        try sema.typeHasRuntimeBits(dest_ty.elemType2()))
    {
        const ptr_int = try block.addUnOp(.ptrtoint, ptr);
        const is_non_zero = try block.addBinOp(.cmp_neq, ptr_int, .zero_usize);
        const ok = if (operand_is_slice) ok: {
            const len = try sema.analyzeSliceLen(block, operand_src, operand);
            const len_zero = try block.addBinOp(.cmp_eq, len, .zero_usize);
            break :ok try block.addBinOp(.bit_or, len_zero, is_non_zero);
        } else is_non_zero;
        try sema.addSafetyCheck(block, ok, .cast_to_null);
    }

    return block.addBitCast(aligned_dest_ty, ptr);
}

fn zirConstCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const operand = try sema.resolveInst(extra.operand);
    const operand_ty = sema.typeOf(operand);
    try sema.checkPtrOperand(block, operand_src, operand_ty);

    var ptr_info = operand_ty.ptrInfo().data;
    ptr_info.mutable = true;
    const dest_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);

    if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
        return sema.addConstant(dest_ty, operand_val);
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addBitCast(dest_ty, operand);
}

fn zirVolatileCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const operand = try sema.resolveInst(extra.operand);
    const operand_ty = sema.typeOf(operand);
    try sema.checkPtrOperand(block, operand_src, operand_ty);

    var ptr_info = operand_ty.ptrInfo().data;
    ptr_info.@"volatile" = false;
    const dest_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);

    if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
        return sema.addConstant(dest_ty, operand_val);
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addBitCast(dest_ty, operand);
}

fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src = inst_data.src();
    const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const dest_scalar_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
    const operand = try sema.resolveInst(extra.rhs);
    const dest_is_comptime_int = try sema.checkIntType(block, dest_ty_src, dest_scalar_ty);
    const operand_ty = sema.typeOf(operand);
    const operand_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, operand_ty, operand_src);
    const is_vector = operand_ty.zigTypeTag() == .Vector;
    const dest_ty = if (is_vector)
        try Type.vector(sema.arena, operand_ty.vectorLen(), dest_scalar_ty)
    else
        dest_scalar_ty;

    if (dest_is_comptime_int) {
        return sema.coerce(block, dest_ty, operand, operand_src);
    }

    const target = sema.mod.getTarget();
    const dest_info = dest_scalar_ty.intInfo(target);

    if (try sema.typeHasOnePossibleValue(dest_ty)) |val| {
        return sema.addConstant(dest_ty, val);
    }

    if (operand_scalar_ty.zigTypeTag() != .ComptimeInt) {
        const operand_info = operand_ty.intInfo(target);
        if (try sema.typeHasOnePossibleValue(operand_ty)) |val| {
            return sema.addConstant(operand_ty, val);
        }

        if (operand_info.signedness != dest_info.signedness) {
            return sema.fail(block, operand_src, "expected {s} integer type, found '{}'", .{
                @tagName(dest_info.signedness), operand_ty.fmt(sema.mod),
            });
        }
        if (operand_info.bits < dest_info.bits) {
            const msg = msg: {
                const msg = try sema.errMsg(
                    block,
                    src,
                    "destination type '{}' has more bits than source type '{}'",
                    .{ dest_ty.fmt(sema.mod), operand_ty.fmt(sema.mod) },
                );
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, dest_ty_src, msg, "destination type has {d} bits", .{
                    dest_info.bits,
                });
                try sema.errNote(block, operand_src, msg, "operand type has {d} bits", .{
                    operand_info.bits,
                });
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
    }

    if (try sema.resolveMaybeUndefValIntable(operand)) |val| {
        if (val.isUndef()) return sema.addConstUndef(dest_ty);
        if (!is_vector) {
            return sema.addConstant(
                dest_ty,
                try val.intTrunc(operand_ty, sema.arena, dest_info.signedness, dest_info.bits, sema.mod),
            );
        }
        var elem_buf: Value.ElemValueBuffer = undefined;
        const elems = try sema.arena.alloc(Value, operand_ty.vectorLen());
        for (elems, 0..) |*elem, i| {
            const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
            elem.* = try elem_val.intTrunc(operand_scalar_ty, sema.arena, dest_info.signedness, dest_info.bits, sema.mod);
        }
        return sema.addConstant(
            dest_ty,
            try Value.Tag.aggregate.create(sema.arena, elems),
        );
    }

    try sema.requireRuntimeBlock(block, src, operand_src);
    return block.addTyOp(.trunc, dest_ty, operand);
}

fn zirAlignCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const align_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const dest_align = try sema.resolveAlign(block, align_src, extra.lhs);
    const ptr = try sema.resolveInst(extra.rhs);
    const ptr_ty = sema.typeOf(ptr);

    try sema.checkPtrOperand(block, ptr_src, ptr_ty);

    var ptr_info = ptr_ty.ptrInfo().data;
    ptr_info.@"align" = dest_align;
    var dest_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);
    if (ptr_ty.zigTypeTag() == .Optional) {
        dest_ty = try Type.Tag.optional.create(sema.arena, dest_ty);
    }

    if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |val| {
        if (try val.getUnsignedIntAdvanced(sema.mod.getTarget(), null)) |addr| {
            if (addr % dest_align != 0) {
                return sema.fail(block, ptr_src, "pointer address 0x{X} is not aligned to {d} bytes", .{ addr, dest_align });
            }
        }
        return sema.addConstant(dest_ty, val);
    }

    try sema.requireRuntimeBlock(block, inst_data.src(), ptr_src);
    if (block.wantSafety() and dest_align > 1 and
        try sema.typeHasRuntimeBits(ptr_info.pointee_type))
    {
        const val_payload = try sema.arena.create(Value.Payload.U64);
        val_payload.* = .{
            .base = .{ .tag = .int_u64 },
            .data = dest_align - 1,
        };
        const align_minus_1 = try sema.addConstant(
            Type.usize,
            Value.initPayload(&val_payload.base),
        );
        const actual_ptr = if (ptr_ty.isSlice())
            try sema.analyzeSlicePtr(block, ptr_src, ptr, ptr_ty)
        else
            ptr;
        const ptr_int = try block.addUnOp(.ptrtoint, actual_ptr);
        const remainder = try block.addBinOp(.bit_and, ptr_int, align_minus_1);
        const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
        const ok = if (ptr_ty.isSlice()) ok: {
            const len = try sema.analyzeSliceLen(block, ptr_src, ptr);
            const len_zero = try block.addBinOp(.cmp_eq, len, .zero_usize);
            break :ok try block.addBinOp(.bit_or, len_zero, is_aligned);
        } else is_aligned;
        try sema.addSafetyCheck(block, ok, .incorrect_alignment);
    }
    return sema.bitCast(block, dest_ty, ptr, ptr_src, null);
}

fn zirBitCount(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    air_tag: Air.Inst.Tag,
    comptime comptimeOp: fn (val: Value, ty: Type, target: std.Target) u64,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    _ = try sema.checkIntOrVector(block, operand, operand_src);
    const target = sema.mod.getTarget();
    const bits = operand_ty.intInfo(target).bits;

    if (try sema.typeHasOnePossibleValue(operand_ty)) |val| {
        return sema.addConstant(operand_ty, val);
    }

    const result_scalar_ty = try Type.smallestUnsignedInt(sema.arena, bits);
    switch (operand_ty.zigTypeTag()) {
        .Vector => {
            const vec_len = operand_ty.vectorLen();
            const result_ty = try Type.vector(sema.arena, vec_len, result_scalar_ty);
            if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef()) return sema.addConstUndef(result_ty);

                var elem_buf: Value.ElemValueBuffer = undefined;
                const elems = try sema.arena.alloc(Value, vec_len);
                const scalar_ty = operand_ty.scalarType();
                for (elems, 0..) |*elem, i| {
                    const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
                    const count = comptimeOp(elem_val, scalar_ty, target);
                    elem.* = try Value.Tag.int_u64.create(sema.arena, count);
                }
                return sema.addConstant(
                    result_ty,
                    try Value.Tag.aggregate.create(sema.arena, elems),
                );
            } else {
                try sema.requireRuntimeBlock(block, src, operand_src);
                return block.addTyOp(air_tag, result_ty, operand);
            }
        },
        .Int => {
            if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef()) return sema.addConstUndef(result_scalar_ty);
                try sema.resolveLazyValue(val);
                return sema.addIntUnsigned(result_scalar_ty, comptimeOp(val, operand_ty, target));
            } else {
                try sema.requireRuntimeBlock(block, src, operand_src);
                return block.addTyOp(air_tag, result_scalar_ty, operand);
            }
        },
        else => unreachable,
    }
}

fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    const scalar_ty = try sema.checkIntOrVector(block, operand, operand_src);
    const target = sema.mod.getTarget();
    const bits = scalar_ty.intInfo(target).bits;
    if (bits % 8 != 0) {
        return sema.fail(
            block,
            operand_src,
            "@byteSwap requires the number of bits to be evenly divisible by 8, but {} has {} bits",
            .{ scalar_ty.fmt(sema.mod), bits },
        );
    }

    if (try sema.typeHasOnePossibleValue(operand_ty)) |val| {
        return sema.addConstant(operand_ty, val);
    }

    switch (operand_ty.zigTypeTag()) {
        .Int => {
            const runtime_src = if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef()) return sema.addConstUndef(operand_ty);
                const result_val = try val.byteSwap(operand_ty, target, sema.arena);
                return sema.addConstant(operand_ty, result_val);
            } else operand_src;

            try sema.requireRuntimeBlock(block, src, runtime_src);
            return block.addTyOp(.byte_swap, operand_ty, operand);
        },
        .Vector => {
            const runtime_src = if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef())
                    return sema.addConstUndef(operand_ty);

                const vec_len = operand_ty.vectorLen();
                var elem_buf: Value.ElemValueBuffer = undefined;
                const elems = try sema.arena.alloc(Value, vec_len);
                for (elems, 0..) |*elem, i| {
                    const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
                    elem.* = try elem_val.byteSwap(operand_ty, target, sema.arena);
                }
                return sema.addConstant(
                    operand_ty,
                    try Value.Tag.aggregate.create(sema.arena, elems),
                );
            } else operand_src;

            try sema.requireRuntimeBlock(block, src, runtime_src);
            return block.addTyOp(.byte_swap, operand_ty, operand);
        },
        else => unreachable,
    }
}

fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand = try sema.resolveInst(inst_data.operand);
    const operand_ty = sema.typeOf(operand);
    const scalar_ty = try sema.checkIntOrVector(block, operand, operand_src);

    if (try sema.typeHasOnePossibleValue(operand_ty)) |val| {
        return sema.addConstant(operand_ty, val);
    }

    const target = sema.mod.getTarget();
    switch (operand_ty.zigTypeTag()) {
        .Int => {
            const runtime_src = if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef()) return sema.addConstUndef(operand_ty);
                const result_val = try val.bitReverse(operand_ty, target, sema.arena);
                return sema.addConstant(operand_ty, result_val);
            } else operand_src;

            try sema.requireRuntimeBlock(block, src, runtime_src);
            return block.addTyOp(.bit_reverse, operand_ty, operand);
        },
        .Vector => {
            const runtime_src = if (try sema.resolveMaybeUndefVal(operand)) |val| {
                if (val.isUndef())
                    return sema.addConstUndef(operand_ty);

                const vec_len = operand_ty.vectorLen();
                var elem_buf: Value.ElemValueBuffer = undefined;
                const elems = try sema.arena.alloc(Value, vec_len);
                for (elems, 0..) |*elem, i| {
                    const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
                    elem.* = try elem_val.bitReverse(scalar_ty, target, sema.arena);
                }
                return sema.addConstant(
                    operand_ty,
                    try Value.Tag.aggregate.create(sema.arena, elems),
                );
            } else operand_src;

            try sema.requireRuntimeBlock(block, src, runtime_src);
            return block.addTyOp(.bit_reverse, operand_ty, operand);
        },
        else => unreachable,
    }
}

fn zirBitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const offset = try sema.bitOffsetOf(block, inst);
    return sema.addIntUnsigned(Type.comptime_int, offset);
}

fn zirOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const offset = try sema.bitOffsetOf(block, inst);
    // TODO reminder to make this a compile error for packed structs
    return sema.addIntUnsigned(Type.comptime_int, offset / 8);
}

fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u64 {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
    sema.src = src;
    const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;

    const ty = try sema.resolveType(block, lhs_src, extra.lhs);
    const field_name = try sema.resolveConstString(block, rhs_src, extra.rhs, "name of field must be comptime-known");
    const target = sema.mod.getTarget();

    try sema.resolveTypeLayout(ty);
    switch (ty.zigTypeTag()) {
        .Struct => {},
        else => {
            const msg = msg: {
                const msg = try sema.errMsg(block, lhs_src, "expected struct type, found '{}'", .{ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);
                try sema.addDeclaredHereNote(msg, ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
    }

    const field_index = if (ty.isTuple()) blk: {
        if (mem.eql(u8, field_name, "len")) {
            return sema.fail(block, src, "no offset available for 'len' field of tuple", .{});
        }
        break :blk try sema.tupleFieldIndex(block, ty, field_name, rhs_src);
    } else try sema.structFieldIndex(block, ty, field_name, rhs_src);

    if (ty.structFieldIsComptime(field_index)) {
        return sema.fail(block, src, "no offset available for comptime field", .{});
    }

    switch (ty.containerLayout()) {
        .Packed => {
            var bit_sum: u64 = 0;
            const fields = ty.structFields();
            for (fields.values(), 0..) |field, i| {
                if (i == field_index) {
                    return bit_sum;
                }
                bit_sum += field.ty.bitSize(target);
            } else unreachable;
        },
        else => return ty.structFieldOffset(field_index, target) * 8,
    }
}

fn checkNamespaceType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Struct, .Enum, .Union, .Opaque => return,
        else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(sema.mod)}),
    }
}

/// Returns `true` if the type was a comptime_int.
fn checkIntType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!bool {
    switch (try ty.zigTypeTagOrPoison()) {
        .ComptimeInt => return true,
        .Int => return false,
        else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(sema.mod)}),
    }
}

fn checkInvalidPtrArithmetic(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    switch (try ty.zigTypeTagOrPoison()) {
        .Pointer => switch (ty.ptrSize()) {
            .One, .Slice => return,
            .Many, .C => return sema.fail(
                block,
                src,
                "invalid pointer arithmetic operator",
                .{},
            ),
        },
        else => return,
    }
}

fn checkArithmeticOp(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    scalar_tag: std.builtin.TypeId,
    lhs_zig_ty_tag: std.builtin.TypeId,
    rhs_zig_ty_tag: std.builtin.TypeId,
    zir_tag: Zir.Inst.Tag,
) CompileError!void {
    const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;
    const is_float = scalar_tag == .Float or scalar_tag == .ComptimeFloat;

    if (!is_int and !(is_float and floatOpAllowed(zir_tag))) {
        return sema.fail(block, src, "invalid operands to binary expression: '{s}' and '{s}'", .{
            @tagName(lhs_zig_ty_tag), @tagName(rhs_zig_ty_tag),
        });
    }
}

fn checkPtrOperand(
    sema: *Sema,
    block: *Block,
    ty_src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Pointer => return,
        .Fn => {
            const msg = msg: {
                const msg = try sema.errMsg(
                    block,
                    ty_src,
                    "expected pointer, found '{}'",
                    .{ty.fmt(sema.mod)},
                );
                errdefer msg.destroy(sema.gpa);

                try sema.errNote(block, ty_src, msg, "use '&' to obtain a function pointer", .{});

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        .Optional => if (ty.isPtrLikeOptional()) return,
        else => {},
    }
    return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(sema.mod)});
}

fn checkPtrType(
    sema: *Sema,
    block: *Block,
    ty_src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Pointer => return,
        .Fn => {
            const msg = msg: {
                const msg = try sema.errMsg(
                    block,
                    ty_src,
                    "expected pointer type, found '{}'",
                    .{ty.fmt(sema.mod)},
                );
                errdefer msg.destroy(sema.gpa);

                try sema.errNote(block, ty_src, msg, "use '*const ' to make a function pointer type", .{});

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        },
        .Optional => if (ty.isPtrLikeOptional()) return,
        else => {},
    }
    return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(sema.mod)});
}

fn checkVectorElemType(
    sema: *Sema,
    block: *Block,
    ty_src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Int, .Float, .Bool => return,
        else => if (ty.isPtrAtRuntime()) return,
    }
    return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(sema.mod)});
}

fn checkFloatType(
    sema: *Sema,
    block: *Block,
    ty_src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    switch (ty.zigTypeTag()) {
        .ComptimeInt, .ComptimeFloat, .Float => {},
        else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(sema.mod)}),
    }
}

fn checkNumericType(
    sema: *Sema,
    block: *Block,
    ty_src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    switch (ty.zigTypeTag()) {
        .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
        .Vector => switch (ty.childType().zigTypeTag()) {
            .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
            else => |t| return sema.fail(block, ty_src, "expected number, found '{}'", .{t}),
        },
        else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(sema.mod)}),
    }
}

/// Returns the casted pointer.
fn checkAtomicPtrOperand(
    sema: *Sema,
    block: *Block,
    elem_ty: Type,
    elem_ty_src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    ptr_src: LazySrcLoc,
    ptr_const: bool,
) CompileError!Air.Inst.Ref {
    const target = sema.mod.getTarget();
    var diag: target_util.AtomicPtrAlignmentDiagnostics = .{};
    const alignment = target_util.atomicPtrAlignment(target, elem_ty, &diag) catch |err| switch (err) {
        error.FloatTooBig => return sema.fail(
            block,
            elem_ty_src,
            "expected {d}-bit float type or smaller; found {d}-bit float type",
            .{ diag.max_bits, diag.bits },
        ),
        error.IntTooBig => return sema.fail(
            block,
            elem_ty_src,
            "expected {d}-bit integer type or smaller; found {d}-bit integer type",
            .{ diag.max_bits, diag.bits },
        ),
        error.BadType => return sema.fail(
            block,
            elem_ty_src,
            "expected bool, integer, float, enum, or pointer type; found '{}'",
            .{elem_ty.fmt(sema.mod)},
        ),
    };

    var wanted_ptr_data: Type.Payload.Pointer.Data = .{
        .pointee_type = elem_ty,
        .@"align" = alignment,
        .@"addrspace" = .generic,
        .mutable = !ptr_const,
    };

    const ptr_ty = sema.typeOf(ptr);
    const ptr_data = switch (try ptr_ty.zigTypeTagOrPoison()) {
        .Pointer => ptr_ty.ptrInfo().data,
        else => {
            const wanted_ptr_ty = try Type.ptr(sema.arena, sema.mod, wanted_ptr_data);
            _ = try sema.coerce(block, wanted_ptr_ty, ptr, ptr_src);
            unreachable;
        },
    };

    wanted_ptr_data.@"addrspace" = ptr_data.@"addrspace";
    wanted_ptr_data.@"allowzero" = ptr_data.@"allowzero";
    wanted_ptr_data.@"volatile" = ptr_data.@"volatile";

    const wanted_ptr_ty = try Type.ptr(sema.arena, sema.mod, wanted_ptr_data);
    const casted_ptr = try sema.coerce(block, wanted_ptr_ty, ptr, ptr_src);

    return casted_ptr;
}

fn checkPtrIsNotComptimeMutable(
    sema: *Sema,
    block: *Block,
    ptr_val: Value,
    ptr_src: LazySrcLoc,
    operand_src: LazySrcLoc,
) CompileError!void {
    _ = operand_src;
    if (ptr_val.isComptimeMutablePtr()) {
        return sema.fail(block, ptr_src, "cannot store runtime value in compile time variable", .{});
    }
}

fn checkComptimeVarStore(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    decl_ref_mut: Value.Payload.DeclRefMut.Data,
) CompileError!void {
    if (@enumToInt(decl_ref_mut.runtime_index) < @enumToInt(block.runtime_index)) {
        if (block.runtime_cond) |cond_src| {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "store to comptime variable depends on runtime condition", .{});
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, cond_src, msg, "runtime condition here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (block.runtime_loop) |loop_src| {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "cannot store to comptime variable in non-inline loop", .{});
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, loop_src, msg, "non-inline loop here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        unreachable;
    }
}

fn checkIntOrVector(
    sema: *Sema,
    block: *Block,
    operand: Air.Inst.Ref,
    operand_src: LazySrcLoc,
) CompileError!Type {
    const operand_ty = sema.typeOf(operand);
    switch (try operand_ty.zigTypeTagOrPoison()) {
        .Int => return operand_ty,
        .Vector => {
            const elem_ty = operand_ty.childType();
            switch (try elem_ty.zigTypeTagOrPoison()) {
                .Int => return elem_ty,
                else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
                    elem_ty.fmt(sema.mod),
                }),
            }
        },
        else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
            operand_ty.fmt(sema.mod),
        }),
    }
}

fn checkIntOrVectorAllowComptime(
    sema: *Sema,
    block: *Block,
    operand_ty: Type,
    operand_src: LazySrcLoc,
) CompileError!Type {
    switch (try operand_ty.zigTypeTagOrPoison()) {
        .Int, .ComptimeInt => return operand_ty,
        .Vector => {
            const elem_ty = operand_ty.childType();
            switch (try elem_ty.zigTypeTagOrPoison()) {
                .Int, .ComptimeInt => return elem_ty,
                else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
                    elem_ty.fmt(sema.mod),
                }),
            }
        },
        else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
            operand_ty.fmt(sema.mod),
        }),
    }
}

fn checkErrorSetType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
    switch (ty.zigTypeTag()) {
        .ErrorSet => return,
        else => return sema.fail(block, src, "expected error set type, found '{}'", .{ty.fmt(sema.mod)}),
    }
}

const SimdBinOp = struct {
    len: ?usize,
    /// Coerced to `result_ty`.
    lhs: Air.Inst.Ref,
    /// Coerced to `result_ty`.
    rhs: Air.Inst.Ref,
    lhs_val: ?Value,
    rhs_val: ?Value,
    /// Only different than `scalar_ty` when it is a vector operation.
    result_ty: Type,
    scalar_ty: Type,
};

fn checkSimdBinOp(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    uncasted_lhs: Air.Inst.Ref,
    uncasted_rhs: Air.Inst.Ref,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
) CompileError!SimdBinOp {
    const lhs_ty = sema.typeOf(uncasted_lhs);
    const rhs_ty = sema.typeOf(uncasted_rhs);

    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
    var vec_len: ?usize = if (lhs_ty.zigTypeTag() == .Vector) lhs_ty.vectorLen() else null;
    const result_ty = try sema.resolvePeerTypes(block, src, &.{ uncasted_lhs, uncasted_rhs }, .{
        .override = &[_]LazySrcLoc{ lhs_src, rhs_src },
    });
    const lhs = try sema.coerce(block, result_ty, uncasted_lhs, lhs_src);
    const rhs = try sema.coerce(block, result_ty, uncasted_rhs, rhs_src);

    return SimdBinOp{
        .len = vec_len,
        .lhs = lhs,
        .rhs = rhs,
        .lhs_val = try sema.resolveMaybeUndefVal(lhs),
        .rhs_val = try sema.resolveMaybeUndefVal(rhs),
        .result_ty = result_ty,
        .scalar_ty = result_ty.scalarType(),
    };
}

fn checkVectorizableBinaryOperands(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    lhs_ty: Type,
    rhs_ty: Type,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
) CompileError!void {
    const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison();
    const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison();
    if (lhs_zig_ty_tag != .Vector and rhs_zig_ty_tag != .Vector) return;

    const lhs_is_vector = switch (lhs_zig_ty_tag) {
        .Vector, .Array => true,
        else => false,
    };
    const rhs_is_vector = switch (rhs_zig_ty_tag) {
        .Vector, .Array => true,
        else => false,
    };

    if (lhs_is_vector and rhs_is_vector) {
        const lhs_len = lhs_ty.arrayLen();
        const rhs_len = rhs_ty.arrayLen();
        if (lhs_len != rhs_len) {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "vector length mismatch", .{});
                errdefer msg.destroy(sema.gpa);
                try sema.errNote(block, lhs_src, msg, "length {d} here", .{lhs_len});
                try sema.errNote(block, rhs_src, msg, "length {d} here", .{rhs_len});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
    } else {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "mixed scalar and vector operands: '{}' and '{}'", .{
                lhs_ty.fmt(sema.mod), rhs_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            if (lhs_is_vector) {
                try sema.errNote(block, lhs_src, msg, "vector here", .{});
                try sema.errNote(block, rhs_src, msg, "scalar here", .{});
            } else {
                try sema.errNote(block, lhs_src, msg, "scalar here", .{});
                try sema.errNote(block, rhs_src, msg, "vector here", .{});
            }
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
}

fn maybeOptionsSrc(sema: *Sema, block: *Block, base_src: LazySrcLoc, wanted: []const u8) LazySrcLoc {
    if (base_src == .unneeded) return .unneeded;
    return Module.optionsSrc(sema.gpa, sema.mod.declPtr(block.src_decl), base_src, wanted);
}

fn resolveExportOptions(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
) CompileError!std.builtin.ExportOptions {
    const export_options_ty = try sema.getBuiltinType("ExportOptions");
    const air_ref = try sema.resolveInst(zir_ref);
    const options = try sema.coerce(block, export_options_ty, air_ref, src);

    const name_src = sema.maybeOptionsSrc(block, src, "name");
    const linkage_src = sema.maybeOptionsSrc(block, src, "linkage");
    const section_src = sema.maybeOptionsSrc(block, src, "section");
    const visibility_src = sema.maybeOptionsSrc(block, src, "visibility");

    const name_operand = try sema.fieldVal(block, src, options, "name", name_src);
    const name_val = try sema.resolveConstValue(block, name_src, name_operand, "name of exported value must be comptime-known");
    const name_ty = Type.initTag(.const_slice_u8);
    const name = try name_val.toAllocatedBytes(name_ty, sema.arena, sema.mod);

    const linkage_operand = try sema.fieldVal(block, src, options, "linkage", linkage_src);
    const linkage_val = try sema.resolveConstValue(block, linkage_src, linkage_operand, "linkage of exported value must be comptime-known");
    const linkage = linkage_val.toEnum(std.builtin.GlobalLinkage);

    const section_operand = try sema.fieldVal(block, src, options, "section", section_src);
    const section_opt_val = try sema.resolveConstValue(block, section_src, section_operand, "linksection of exported value must be comptime-known");
    const section_ty = Type.initTag(.const_slice_u8);
    const section = if (section_opt_val.optionalValue()) |section_val|
        try section_val.toAllocatedBytes(section_ty, sema.arena, sema.mod)
    else
        null;

    const visibility_operand = try sema.fieldVal(block, src, options, "visibility", visibility_src);
    const visibility_val = try sema.resolveConstValue(block, visibility_src, visibility_operand, "visibility of exported value must be comptime-known");
    const visibility = visibility_val.toEnum(std.builtin.SymbolVisibility);

    if (name.len < 1) {
        return sema.fail(block, name_src, "exported symbol name cannot be empty", .{});
    }

    if (visibility != .default and linkage == .Internal) {
        return sema.fail(block, visibility_src, "symbol '{s}' exported with internal linkage has non-default visibility {s}", .{
            name, @tagName(visibility),
        });
    }

    return std.builtin.ExportOptions{
        .name = name,
        .linkage = linkage,
        .section = section,
        .visibility = visibility,
    };
}

fn resolveBuiltinEnum(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    comptime name: []const u8,
    reason: []const u8,
) CompileError!@field(std.builtin, name) {
    const ty = try sema.getBuiltinType(name);
    const air_ref = try sema.resolveInst(zir_ref);
    const coerced = try sema.coerce(block, ty, air_ref, src);
    const val = try sema.resolveConstValue(block, src, coerced, reason);
    return val.toEnum(@field(std.builtin, name));
}

fn resolveAtomicOrder(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    reason: []const u8,
) CompileError!std.builtin.AtomicOrder {
    return sema.resolveBuiltinEnum(block, src, zir_ref, "AtomicOrder", reason);
}

fn resolveAtomicRmwOp(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
) CompileError!std.builtin.AtomicRmwOp {
    return sema.resolveBuiltinEnum(block, src, zir_ref, "AtomicRmwOp", "@atomicRmW operation must be comptime-known");
}

fn zirCmpxchg(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.Cmpxchg, extended.operand).data;
    const air_tag: Air.Inst.Tag = switch (extended.small) {
        0 => .cmpxchg_weak,
        1 => .cmpxchg_strong,
        else => unreachable,
    };
    const src = LazySrcLoc.nodeOffset(extra.node);
    // zig fmt: off
    const elem_ty_src      : LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const ptr_src          : LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
    const expected_src     : LazySrcLoc = .{ .node_offset_builtin_call_arg2 = extra.node };
    const new_value_src    : LazySrcLoc = .{ .node_offset_builtin_call_arg3 = extra.node };
    const success_order_src: LazySrcLoc = .{ .node_offset_builtin_call_arg4 = extra.node };
    const failure_order_src: LazySrcLoc = .{ .node_offset_builtin_call_arg5 = extra.node };
    // zig fmt: on
    const expected_value = try sema.resolveInst(extra.expected_value);
    const elem_ty = sema.typeOf(expected_value);
    if (elem_ty.zigTypeTag() == .Float) {
        return sema.fail(
            block,
            elem_ty_src,
            "expected bool, integer, enum, or pointer type; found '{}'",
            .{elem_ty.fmt(sema.mod)},
        );
    }
    const uncasted_ptr = try sema.resolveInst(extra.ptr);
    const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);
    const new_value = try sema.coerce(block, elem_ty, try sema.resolveInst(extra.new_value), new_value_src);
    const success_order = try sema.resolveAtomicOrder(block, success_order_src, extra.success_order, "atomic order of cmpxchg success must be comptime-known");
    const failure_order = try sema.resolveAtomicOrder(block, failure_order_src, extra.failure_order, "atomic order of cmpxchg failure must be comptime-known");

    if (@enumToInt(success_order) < @enumToInt(std.builtin.AtomicOrder.Monotonic)) {
        return sema.fail(block, success_order_src, "success atomic ordering must be Monotonic or stricter", .{});
    }
    if (@enumToInt(failure_order) < @enumToInt(std.builtin.AtomicOrder.Monotonic)) {
        return sema.fail(block, failure_order_src, "failure atomic ordering must be Monotonic or stricter", .{});
    }
    if (@enumToInt(failure_order) > @enumToInt(success_order)) {
        return sema.fail(block, failure_order_src, "failure atomic ordering must be no stricter than success", .{});
    }
    if (failure_order == .Release or failure_order == .AcqRel) {
        return sema.fail(block, failure_order_src, "failure atomic ordering must not be Release or AcqRel", .{});
    }

    const result_ty = try Type.optional(sema.arena, elem_ty);

    // special case zero bit types
    if ((try sema.typeHasOnePossibleValue(elem_ty)) != null) {
        return sema.addConstant(result_ty, Value.null);
    }

    const runtime_src = if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| rs: {
        if (try sema.resolveMaybeUndefVal(expected_value)) |expected_val| {
            if (try sema.resolveMaybeUndefVal(new_value)) |new_val| {
                if (expected_val.isUndef() or new_val.isUndef()) {
                    // TODO: this should probably cause the memory stored at the pointer
                    // to become undef as well
                    return sema.addConstUndef(result_ty);
                }
                const ptr_ty = sema.typeOf(ptr);
                const stored_val = (try sema.pointerDeref(block, ptr_src, ptr_val, ptr_ty)) orelse break :rs ptr_src;
                const result_val = if (stored_val.eql(expected_val, elem_ty, sema.mod)) blk: {
                    try sema.storePtr(block, src, ptr, new_value);
                    break :blk Value.null;
                } else try Value.Tag.opt_payload.create(sema.arena, stored_val);

                return sema.addConstant(result_ty, result_val);
            } else break :rs new_value_src;
        } else break :rs expected_src;
    } else ptr_src;

    const flags: u32 = @as(u32, @enumToInt(success_order)) |
        (@as(u32, @enumToInt(failure_order)) << 3);

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addInst(.{
        .tag = air_tag,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(result_ty),
            .payload = try sema.addExtra(Air.Cmpxchg{
                .ptr = ptr,
                .expected_value = expected_value,
                .new_value = new_value,
                .flags = flags,
            }),
        } },
    });
}

fn zirSplat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const len_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
    const scalar_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
    const len = @intCast(u32, try sema.resolveInt(block, len_src, extra.lhs, Type.u32, "vector splat destination length must be comptime-known"));
    const scalar = try sema.resolveInst(extra.rhs);
    const scalar_ty = sema.typeOf(scalar);
    try sema.checkVectorElemType(block, scalar_src, scalar_ty);
    const vector_ty = try Type.Tag.vector.create(sema.arena, .{
        .len = len,
        .elem_type = scalar_ty,
    });
    if (try sema.resolveMaybeUndefVal(scalar)) |scalar_val| {
        if (scalar_val.isUndef()) return sema.addConstUndef(vector_ty);

        return sema.addConstant(
            vector_ty,
            try Value.Tag.repeated.create(sema.arena, scalar_val),
        );
    }

    try sema.requireRuntimeBlock(block, inst_data.src(), scalar_src);
    return block.addTyOp(.splat, vector_ty, scalar);
}

fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const op_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const operation = try sema.resolveBuiltinEnum(block, op_src, extra.lhs, "ReduceOp", "@reduce operation must be comptime-known");
    const operand = try sema.resolveInst(extra.rhs);
    const operand_ty = sema.typeOf(operand);
    const target = sema.mod.getTarget();

    if (operand_ty.zigTypeTag() != .Vector) {
        return sema.fail(block, operand_src, "expected vector, found '{}'", .{operand_ty.fmt(sema.mod)});
    }

    const scalar_ty = operand_ty.childType();

    // Type-check depending on operation.
    switch (operation) {
        .And, .Or, .Xor => switch (scalar_ty.zigTypeTag()) {
            .Int, .Bool => {},
            else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or boolean operand; found '{}'", .{
                @tagName(operation), operand_ty.fmt(sema.mod),
            }),
        },
        .Min, .Max, .Add, .Mul => switch (scalar_ty.zigTypeTag()) {
            .Int, .Float => {},
            else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or float operand; found '{}'", .{
                @tagName(operation), operand_ty.fmt(sema.mod),
            }),
        },
    }

    const vec_len = operand_ty.vectorLen();
    if (vec_len == 0) {
        // TODO re-evaluate if we should introduce a "neutral value" for some operations,
        // e.g. zero for add and one for mul.
        return sema.fail(block, operand_src, "@reduce operation requires a vector with nonzero length", .{});
    }

    if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
        if (operand_val.isUndef()) return sema.addConstUndef(scalar_ty);

        var accum: Value = try operand_val.elemValue(sema.mod, sema.arena, 0);
        var elem_buf: Value.ElemValueBuffer = undefined;
        var i: u32 = 1;
        while (i < vec_len) : (i += 1) {
            const elem_val = operand_val.elemValueBuffer(sema.mod, i, &elem_buf);
            switch (operation) {
                .And => accum = try accum.bitwiseAnd(elem_val, scalar_ty, sema.arena, sema.mod),
                .Or => accum = try accum.bitwiseOr(elem_val, scalar_ty, sema.arena, sema.mod),
                .Xor => accum = try accum.bitwiseXor(elem_val, scalar_ty, sema.arena, sema.mod),
                .Min => accum = accum.numberMin(elem_val, target),
                .Max => accum = accum.numberMax(elem_val, target),
                .Add => accum = try sema.numberAddWrapScalar(accum, elem_val, scalar_ty),
                .Mul => accum = try accum.numberMulWrap(elem_val, scalar_ty, sema.arena, sema.mod),
            }
        }
        return sema.addConstant(scalar_ty, accum);
    }

    try sema.requireRuntimeBlock(block, inst_data.src(), operand_src);
    return block.addInst(.{
        .tag = if (block.float_mode == .Optimized) .reduce_optimized else .reduce,
        .data = .{ .reduce = .{
            .operand = operand,
            .operation = operation,
        } },
    });
}

fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Shuffle, inst_data.payload_index).data;
    const elem_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const mask_src: LazySrcLoc = .{ .node_offset_builtin_call_arg3 = inst_data.src_node };

    const elem_ty = try sema.resolveType(block, elem_ty_src, extra.elem_type);
    try sema.checkVectorElemType(block, elem_ty_src, elem_ty);
    var a = try sema.resolveInst(extra.a);
    var b = try sema.resolveInst(extra.b);
    var mask = try sema.resolveInst(extra.mask);
    var mask_ty = sema.typeOf(mask);

    const mask_len = switch (sema.typeOf(mask).zigTypeTag()) {
        .Array, .Vector => sema.typeOf(mask).arrayLen(),
        else => return sema.fail(block, mask_src, "expected vector or array, found '{}'", .{sema.typeOf(mask).fmt(sema.mod)}),
    };
    mask_ty = try Type.Tag.vector.create(sema.arena, .{
        .len = mask_len,
        .elem_type = Type.i32,
    });
    mask = try sema.coerce(block, mask_ty, mask, mask_src);
    const mask_val = try sema.resolveConstMaybeUndefVal(block, mask_src, mask, "shuffle mask must be comptime-known");
    return sema.analyzeShuffle(block, inst_data.src_node, elem_ty, a, b, mask_val, @intCast(u32, mask_len));
}

fn analyzeShuffle(
    sema: *Sema,
    block: *Block,
    src_node: i32,
    elem_ty: Type,
    a_arg: Air.Inst.Ref,
    b_arg: Air.Inst.Ref,
    mask: Value,
    mask_len: u32,
) CompileError!Air.Inst.Ref {
    const a_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = src_node };
    const b_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = src_node };
    const mask_src: LazySrcLoc = .{ .node_offset_builtin_call_arg3 = src_node };
    var a = a_arg;
    var b = b_arg;

    const res_ty = try Type.Tag.vector.create(sema.arena, .{
        .len = mask_len,
        .elem_type = elem_ty,
    });

    var maybe_a_len = switch (sema.typeOf(a).zigTypeTag()) {
        .Array, .Vector => sema.typeOf(a).arrayLen(),
        .Undefined => null,
        else => return sema.fail(block, a_src, "expected vector or array with element type '{}', found '{}'", .{
            elem_ty.fmt(sema.mod),
            sema.typeOf(a).fmt(sema.mod),
        }),
    };
    var maybe_b_len = switch (sema.typeOf(b).zigTypeTag()) {
        .Array, .Vector => sema.typeOf(b).arrayLen(),
        .Undefined => null,
        else => return sema.fail(block, b_src, "expected vector or array with element type '{}', found '{}'", .{
            elem_ty.fmt(sema.mod),
            sema.typeOf(b).fmt(sema.mod),
        }),
    };
    if (maybe_a_len == null and maybe_b_len == null) {
        return sema.addConstUndef(res_ty);
    }
    const a_len = maybe_a_len orelse maybe_b_len.?;
    const b_len = maybe_b_len orelse a_len;

    const a_ty = try Type.Tag.vector.create(sema.arena, .{
        .len = a_len,
        .elem_type = elem_ty,
    });
    const b_ty = try Type.Tag.vector.create(sema.arena, .{
        .len = b_len,
        .elem_type = elem_ty,
    });

    if (maybe_a_len == null) a = try sema.addConstUndef(a_ty) else a = try sema.coerce(block, a_ty, a, a_src);
    if (maybe_b_len == null) b = try sema.addConstUndef(b_ty) else b = try sema.coerce(block, b_ty, b, b_src);

    const operand_info = [2]std.meta.Tuple(&.{ u64, LazySrcLoc, Type }){
        .{ a_len, a_src, a_ty },
        .{ b_len, b_src, b_ty },
    };

    var i: usize = 0;
    while (i < mask_len) : (i += 1) {
        var buf: Value.ElemValueBuffer = undefined;
        const elem = mask.elemValueBuffer(sema.mod, i, &buf);
        if (elem.isUndef()) continue;
        const int = elem.toSignedInt(sema.mod.getTarget());
        var unsigned: u32 = undefined;
        var chosen: u32 = undefined;
        if (int >= 0) {
            unsigned = @intCast(u32, int);
            chosen = 0;
        } else {
            unsigned = @intCast(u32, ~int);
            chosen = 1;
        }
        if (unsigned >= operand_info[chosen][0]) {
            const msg = msg: {
                const msg = try sema.errMsg(block, mask_src, "mask index '{d}' has out-of-bounds selection", .{i});
                errdefer msg.destroy(sema.gpa);

                try sema.errNote(block, operand_info[chosen][1], msg, "selected index '{d}' out of bounds of '{}'", .{
                    unsigned,
                    operand_info[chosen][2].fmt(sema.mod),
                });

                if (chosen == 0) {
                    try sema.errNote(block, b_src, msg, "selections from the second vector are specified with negative numbers", .{});
                }

                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
    }

    if (try sema.resolveMaybeUndefVal(a)) |a_val| {
        if (try sema.resolveMaybeUndefVal(b)) |b_val| {
            const values = try sema.arena.alloc(Value, mask_len);

            i = 0;
            while (i < mask_len) : (i += 1) {
                var buf: Value.ElemValueBuffer = undefined;
                const mask_elem_val = mask.elemValueBuffer(sema.mod, i, &buf);
                if (mask_elem_val.isUndef()) {
                    values[i] = Value.undef;
                    continue;
                }
                const int = mask_elem_val.toSignedInt(sema.mod.getTarget());
                const unsigned = if (int >= 0) @intCast(u32, int) else @intCast(u32, ~int);
                if (int >= 0) {
                    values[i] = try a_val.elemValue(sema.mod, sema.arena, unsigned);
                } else {
                    values[i] = try b_val.elemValue(sema.mod, sema.arena, unsigned);
                }
            }
            const res_val = try Value.Tag.aggregate.create(sema.arena, values);
            return sema.addConstant(res_ty, res_val);
        }
    }

    // All static analysis passed, and not comptime.
    // For runtime codegen, vectors a and b must be the same length. Here we
    // recursively @shuffle the smaller vector to append undefined elements
    // to it up to the length of the longer vector. This recursion terminates
    // in 1 call because these calls to analyzeShuffle guarantee a_len == b_len.
    if (a_len != b_len) {
        const min_len = std.math.min(a_len, b_len);
        const max_src = if (a_len > b_len) a_src else b_src;
        const max_len = try sema.usizeCast(block, max_src, std.math.max(a_len, b_len));

        const expand_mask_values = try sema.arena.alloc(Value, max_len);
        i = 0;
        while (i < min_len) : (i += 1) {
            expand_mask_values[i] = try Value.Tag.int_u64.create(sema.arena, i);
        }
        while (i < max_len) : (i += 1) {
            expand_mask_values[i] = Value.negative_one;
        }
        const expand_mask = try Value.Tag.aggregate.create(sema.arena, expand_mask_values);

        if (a_len < b_len) {
            const undef = try sema.addConstUndef(a_ty);
            a = try sema.analyzeShuffle(block, src_node, elem_ty, a, undef, expand_mask, @intCast(u32, max_len));
        } else {
            const undef = try sema.addConstUndef(b_ty);
            b = try sema.analyzeShuffle(block, src_node, elem_ty, b, undef, expand_mask, @intCast(u32, max_len));
        }
    }

    const mask_index = @intCast(u32, sema.air_values.items.len);
    try sema.air_values.append(sema.gpa, mask);
    return block.addInst(.{
        .tag = .shuffle,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(res_ty),
            .payload = try block.sema.addExtra(Air.Shuffle{
                .a = a,
                .b = b,
                .mask = mask_index,
                .mask_len = mask_len,
            }),
        } },
    });
}

fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.Select, extended.operand).data;

    const src = LazySrcLoc.nodeOffset(extra.node);
    const elem_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const pred_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
    const a_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = extra.node };
    const b_src: LazySrcLoc = .{ .node_offset_builtin_call_arg3 = extra.node };

    const elem_ty = try sema.resolveType(block, elem_ty_src, extra.elem_type);
    try sema.checkVectorElemType(block, elem_ty_src, elem_ty);
    const pred_uncoerced = try sema.resolveInst(extra.pred);
    const pred_ty = sema.typeOf(pred_uncoerced);

    const vec_len_u64 = switch (try pred_ty.zigTypeTagOrPoison()) {
        .Vector, .Array => pred_ty.arrayLen(),
        else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(sema.mod)}),
    };
    const vec_len = try sema.usizeCast(block, pred_src, vec_len_u64);

    const bool_vec_ty = try Type.vector(sema.arena, vec_len, Type.bool);
    const pred = try sema.coerce(block, bool_vec_ty, pred_uncoerced, pred_src);

    const vec_ty = try Type.vector(sema.arena, vec_len, elem_ty);
    const a = try sema.coerce(block, vec_ty, try sema.resolveInst(extra.a), a_src);
    const b = try sema.coerce(block, vec_ty, try sema.resolveInst(extra.b), b_src);

    const maybe_pred = try sema.resolveMaybeUndefVal(pred);
    const maybe_a = try sema.resolveMaybeUndefVal(a);
    const maybe_b = try sema.resolveMaybeUndefVal(b);

    const runtime_src = if (maybe_pred) |pred_val| rs: {
        if (pred_val.isUndef()) return sema.addConstUndef(vec_ty);

        if (maybe_a) |a_val| {
            if (a_val.isUndef()) return sema.addConstUndef(vec_ty);

            if (maybe_b) |b_val| {
                if (b_val.isUndef()) return sema.addConstUndef(vec_ty);

                var buf: Value.ElemValueBuffer = undefined;
                const elems = try sema.gpa.alloc(Value, vec_len);
                for (elems, 0..) |*elem, i| {
                    const pred_elem_val = pred_val.elemValueBuffer(sema.mod, i, &buf);
                    const should_choose_a = pred_elem_val.toBool();
                    if (should_choose_a) {
                        elem.* = a_val.elemValueBuffer(sema.mod, i, &buf);
                    } else {
                        elem.* = b_val.elemValueBuffer(sema.mod, i, &buf);
                    }
                }

                return sema.addConstant(
                    vec_ty,
                    try Value.Tag.aggregate.create(sema.arena, elems),
                );
            } else {
                break :rs b_src;
            }
        } else {
            if (maybe_b) |b_val| {
                if (b_val.isUndef()) return sema.addConstUndef(vec_ty);
            }
            break :rs a_src;
        }
    } else rs: {
        if (maybe_a) |a_val| {
            if (a_val.isUndef()) return sema.addConstUndef(vec_ty);
        }
        if (maybe_b) |b_val| {
            if (b_val.isUndef()) return sema.addConstUndef(vec_ty);
        }
        break :rs pred_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addInst(.{
        .tag = .select,
        .data = .{ .pl_op = .{
            .operand = pred,
            .payload = try block.sema.addExtra(Air.Bin{
                .lhs = a,
                .rhs = b,
            }),
        } },
    });
}

fn zirAtomicLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.AtomicLoad, inst_data.payload_index).data;
    // zig fmt: off
    const elem_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ptr_src    : LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const order_src  : LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    // zig fmt: on
    const elem_ty = try sema.resolveType(block, elem_ty_src, extra.elem_type);
    const uncasted_ptr = try sema.resolveInst(extra.ptr);
    const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, true);
    const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, "atomic order of @atomicLoad must be comptime-known");

    switch (order) {
        .Release, .AcqRel => {
            return sema.fail(
                block,
                order_src,
                "@atomicLoad atomic ordering must not be Release or AcqRel",
                .{},
            );
        },
        else => {},
    }

    if (try sema.typeHasOnePossibleValue(elem_ty)) |val| {
        return sema.addConstant(elem_ty, val);
    }

    if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| {
        if (try sema.pointerDeref(block, ptr_src, ptr_val, sema.typeOf(ptr))) |elem_val| {
            return sema.addConstant(elem_ty, elem_val);
        }
    }

    try sema.requireRuntimeBlock(block, inst_data.src(), ptr_src);
    return block.addInst(.{
        .tag = .atomic_load,
        .data = .{ .atomic_load = .{
            .ptr = ptr,
            .order = order,
        } },
    });
}

fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.AtomicRmw, inst_data.payload_index).data;
    const src = inst_data.src();
    // zig fmt: off
    const elem_ty_src   : LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ptr_src       : LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const op_src        : LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const operand_src   : LazySrcLoc = .{ .node_offset_builtin_call_arg3 = inst_data.src_node };
    const order_src     : LazySrcLoc = .{ .node_offset_builtin_call_arg4 = inst_data.src_node };
    // zig fmt: on
    const operand = try sema.resolveInst(extra.operand);
    const elem_ty = sema.typeOf(operand);
    const uncasted_ptr = try sema.resolveInst(extra.ptr);
    const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);
    const op = try sema.resolveAtomicRmwOp(block, op_src, extra.operation);

    switch (elem_ty.zigTypeTag()) {
        .Enum => if (op != .Xchg) {
            return sema.fail(block, op_src, "@atomicRmw with enum only allowed with .Xchg", .{});
        },
        .Bool => if (op != .Xchg) {
            return sema.fail(block, op_src, "@atomicRmw with bool only allowed with .Xchg", .{});
        },
        .Float => switch (op) {
            .Xchg, .Add, .Sub => {},
            else => return sema.fail(block, op_src, "@atomicRmw with float only allowed with .Xchg, .Add, and .Sub", .{}),
        },
        else => {},
    }
    const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, "atomic order of @atomicRmW must be comptime-known");

    if (order == .Unordered) {
        return sema.fail(block, order_src, "@atomicRmw atomic ordering must not be Unordered", .{});
    }

    // special case zero bit types
    if (try sema.typeHasOnePossibleValue(elem_ty)) |val| {
        return sema.addConstant(elem_ty, val);
    }

    const runtime_src = if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| rs: {
        const maybe_operand_val = try sema.resolveMaybeUndefVal(operand);
        const operand_val = maybe_operand_val orelse {
            try sema.checkPtrIsNotComptimeMutable(block, ptr_val, ptr_src, operand_src);
            break :rs operand_src;
        };
        if (ptr_val.isComptimeMutablePtr()) {
            const target = sema.mod.getTarget();
            const ptr_ty = sema.typeOf(ptr);
            const stored_val = (try sema.pointerDeref(block, ptr_src, ptr_val, ptr_ty)) orelse break :rs ptr_src;
            const new_val = switch (op) {
                // zig fmt: off
                .Xchg => operand_val,
                .Add  => try sema.numberAddWrapScalar(stored_val, operand_val, elem_ty),
                .Sub  => try sema.numberSubWrapScalar(stored_val, operand_val, elem_ty),
                .And  => try                   stored_val.bitwiseAnd   (operand_val, elem_ty, sema.arena, sema.mod),
                .Nand => try                   stored_val.bitwiseNand  (operand_val, elem_ty, sema.arena, sema.mod),
                .Or   => try                   stored_val.bitwiseOr    (operand_val, elem_ty, sema.arena, sema.mod),
                .Xor  => try                   stored_val.bitwiseXor   (operand_val, elem_ty, sema.arena, sema.mod),
                .Max  =>                       stored_val.numberMax    (operand_val,                      target),
                .Min  =>                       stored_val.numberMin    (operand_val,                      target),
                // zig fmt: on
            };
            try sema.storePtrVal(block, src, ptr_val, new_val, elem_ty);
            return sema.addConstant(elem_ty, stored_val);
        } else break :rs ptr_src;
    } else ptr_src;

    const flags: u32 = @as(u32, @enumToInt(order)) | (@as(u32, @enumToInt(op)) << 3);

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addInst(.{
        .tag = .atomic_rmw,
        .data = .{ .pl_op = .{
            .operand = ptr,
            .payload = try sema.addExtra(Air.AtomicRmw{
                .operand = operand,
                .flags = flags,
            }),
        } },
    });
}

fn zirAtomicStore(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.AtomicStore, inst_data.payload_index).data;
    const src = inst_data.src();
    // zig fmt: off
    const elem_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const ptr_src       : LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const operand_src   : LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const order_src     : LazySrcLoc = .{ .node_offset_builtin_call_arg3 = inst_data.src_node };
    // zig fmt: on
    const operand = try sema.resolveInst(extra.operand);
    const elem_ty = sema.typeOf(operand);
    const uncasted_ptr = try sema.resolveInst(extra.ptr);
    const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);
    const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, "atomic order of @atomicStore must be comptime-known");

    const air_tag: Air.Inst.Tag = switch (order) {
        .Acquire, .AcqRel => {
            return sema.fail(
                block,
                order_src,
                "@atomicStore atomic ordering must not be Acquire or AcqRel",
                .{},
            );
        },
        .Unordered => .atomic_store_unordered,
        .Monotonic => .atomic_store_monotonic,
        .Release => .atomic_store_release,
        .SeqCst => .atomic_store_seq_cst,
    };

    return sema.storePtr2(block, src, ptr, ptr_src, operand, operand_src, air_tag);
}

fn zirMulAdd(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.MulAdd, inst_data.payload_index).data;
    const src = inst_data.src();

    const mulend1_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const mulend2_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const addend_src: LazySrcLoc = .{ .node_offset_builtin_call_arg3 = inst_data.src_node };

    const addend = try sema.resolveInst(extra.addend);
    const ty = sema.typeOf(addend);
    const mulend1 = try sema.coerce(block, ty, try sema.resolveInst(extra.mulend1), mulend1_src);
    const mulend2 = try sema.coerce(block, ty, try sema.resolveInst(extra.mulend2), mulend2_src);

    const maybe_mulend1 = try sema.resolveMaybeUndefVal(mulend1);
    const maybe_mulend2 = try sema.resolveMaybeUndefVal(mulend2);
    const maybe_addend = try sema.resolveMaybeUndefVal(addend);

    switch (ty.zigTypeTag()) {
        .ComptimeFloat, .Float, .Vector => {},
        else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(sema.mod)}),
    }

    const runtime_src = if (maybe_mulend1) |mulend1_val| rs: {
        if (maybe_mulend2) |mulend2_val| {
            if (mulend2_val.isUndef()) return sema.addConstUndef(ty);

            if (maybe_addend) |addend_val| {
                if (addend_val.isUndef()) return sema.addConstUndef(ty);
                const result_val = try Value.mulAdd(ty, mulend1_val, mulend2_val, addend_val, sema.arena, sema.mod);
                return sema.addConstant(ty, result_val);
            } else {
                break :rs addend_src;
            }
        } else {
            if (maybe_addend) |addend_val| {
                if (addend_val.isUndef()) return sema.addConstUndef(ty);
            }
            break :rs mulend2_src;
        }
    } else rs: {
        if (maybe_mulend2) |mulend2_val| {
            if (mulend2_val.isUndef()) return sema.addConstUndef(ty);
        }
        if (maybe_addend) |addend_val| {
            if (addend_val.isUndef()) return sema.addConstUndef(ty);
        }
        break :rs mulend1_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addInst(.{
        .tag = .mul_add,
        .data = .{ .pl_op = .{
            .operand = addend,
            .payload = try sema.addExtra(Air.Bin{
                .lhs = mulend1,
                .rhs = mulend2,
            }),
        } },
    });
}

fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const modifier_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const func_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const args_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const call_src = inst_data.src();

    const extra = sema.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data;
    var func = try sema.resolveInst(extra.callee);

    const modifier_ty = try sema.getBuiltinType("CallModifier");
    const air_ref = try sema.resolveInst(extra.modifier);
    const modifier_ref = try sema.coerce(block, modifier_ty, air_ref, modifier_src);
    const modifier_val = try sema.resolveConstValue(block, modifier_src, modifier_ref, "call modifier must be comptime-known");
    var modifier = modifier_val.toEnum(std.builtin.CallModifier);
    switch (modifier) {
        // These can be upgraded to comptime or nosuspend calls.
        .auto, .never_tail, .no_async => {
            if (extra.flags.is_comptime) {
                if (modifier == .never_tail) {
                    return sema.fail(block, modifier_src, "unable to perform 'never_tail' call at compile-time", .{});
                }
                modifier = .compile_time;
            } else if (extra.flags.is_nosuspend) {
                modifier = .no_async;
            }
        },
        // These can be upgraded to comptime. nosuspend bit can be safely ignored.
        .always_inline, .compile_time => {
            _ = (try sema.resolveDefinedValue(block, func_src, func)) orelse {
                return sema.fail(block, func_src, "modifier '{s}' requires a comptime-known function", .{@tagName(modifier)});
            };

            if (extra.flags.is_comptime) {
                modifier = .compile_time;
            }
        },
        .always_tail => {
            if (extra.flags.is_comptime) {
                modifier = .compile_time;
            }
        },
        .async_kw => {
            if (extra.flags.is_nosuspend) {
                return sema.fail(block, modifier_src, "modifier 'async_kw' cannot be used inside nosuspend block", .{});
            }
            if (extra.flags.is_comptime) {
                return sema.fail(block, modifier_src, "modifier 'async_kw' cannot be used in combination with comptime function call", .{});
            }
        },
        .never_inline => {
            if (extra.flags.is_comptime) {
                return sema.fail(block, modifier_src, "unable to perform 'never_inline' call at compile-time", .{});
            }
        },
    }

    const args = try sema.resolveInst(extra.args);

    const args_ty = sema.typeOf(args);
    if (!args_ty.isTuple() and args_ty.tag() != .empty_struct_literal) {
        return sema.fail(block, args_src, "expected a tuple, found '{}'", .{args_ty.fmt(sema.mod)});
    }

    var resolved_args: []Air.Inst.Ref = undefined;

    // Desugar bound functions here
    var bound_arg_src: ?LazySrcLoc = null;
    if (sema.typeOf(func).tag() == .bound_fn) {
        bound_arg_src = func_src;
        const bound_func = try sema.resolveValue(block, .unneeded, func, "");
        const bound_data = &bound_func.cast(Value.Payload.BoundFn).?.data;
        func = bound_data.func_inst;
        resolved_args = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount() + 1);
        resolved_args[0] = bound_data.arg0_inst;
        for (resolved_args[1..], 0..) |*resolved, i| {
            resolved.* = try sema.tupleFieldValByIndex(block, args_src, args, @intCast(u32, i), args_ty);
        }
    } else {
        resolved_args = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount());
        for (resolved_args, 0..) |*resolved, i| {
            resolved.* = try sema.tupleFieldValByIndex(block, args_src, args, @intCast(u32, i), args_ty);
        }
    }
    const ensure_result_used = extra.flags.ensure_result_used;
    return sema.analyzeCall(block, func, func_src, call_src, modifier, ensure_result_used, resolved_args, bound_arg_src);
}

fn zirFieldParentPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.FieldParentPtr, inst_data.payload_index).data;
    const src = inst_data.src();
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };

    const parent_ty = try sema.resolveType(block, ty_src, extra.parent_type);
    const field_name = try sema.resolveConstString(block, name_src, extra.field_name, "field name must be comptime-known");
    const field_ptr = try sema.resolveInst(extra.field_ptr);
    const field_ptr_ty = sema.typeOf(field_ptr);

    if (parent_ty.zigTypeTag() != .Struct and parent_ty.zigTypeTag() != .Union) {
        return sema.fail(block, ty_src, "expected struct or union type, found '{}'", .{parent_ty.fmt(sema.mod)});
    }
    try sema.resolveTypeLayout(parent_ty);

    const field_index = switch (parent_ty.zigTypeTag()) {
        .Struct => blk: {
            if (parent_ty.isTuple()) {
                if (mem.eql(u8, field_name, "len")) {
                    return sema.fail(block, src, "cannot get @fieldParentPtr of 'len' field of tuple", .{});
                }
                break :blk try sema.tupleFieldIndex(block, parent_ty, field_name, name_src);
            } else {
                break :blk try sema.structFieldIndex(block, parent_ty, field_name, name_src);
            }
        },
        .Union => try sema.unionFieldIndex(block, parent_ty, field_name, name_src),
        else => unreachable,
    };

    if (parent_ty.zigTypeTag() == .Struct and parent_ty.structFieldIsComptime(field_index)) {
        return sema.fail(block, src, "cannot get @fieldParentPtr of a comptime field", .{});
    }

    try sema.checkPtrOperand(block, ptr_src, field_ptr_ty);
    const field_ptr_ty_info = field_ptr_ty.ptrInfo().data;

    var ptr_ty_data: Type.Payload.Pointer.Data = .{
        .pointee_type = parent_ty.structFieldType(field_index),
        .mutable = field_ptr_ty_info.mutable,
        .@"addrspace" = field_ptr_ty_info.@"addrspace",
    };

    if (parent_ty.containerLayout() == .Packed) {
        return sema.fail(block, src, "TODO handle packed structs/unions with @fieldParentPtr", .{});
    } else {
        ptr_ty_data.@"align" = blk: {
            if (parent_ty.castTag(.@"struct")) |struct_obj| {
                break :blk struct_obj.data.fields.values()[field_index].abi_align;
            } else if (parent_ty.cast(Type.Payload.Union)) |union_obj| {
                break :blk union_obj.data.fields.values()[field_index].abi_align;
            } else {
                break :blk 0;
            }
        };
    }

    const actual_field_ptr_ty = try Type.ptr(sema.arena, sema.mod, ptr_ty_data);
    const casted_field_ptr = try sema.coerce(block, actual_field_ptr_ty, field_ptr, ptr_src);

    ptr_ty_data.pointee_type = parent_ty;
    const result_ptr = try Type.ptr(sema.arena, sema.mod, ptr_ty_data);

    if (try sema.resolveDefinedValue(block, src, casted_field_ptr)) |field_ptr_val| {
        const payload = field_ptr_val.castTag(.field_ptr) orelse {
            return sema.fail(block, ptr_src, "pointer value not based on parent struct", .{});
        };
        if (payload.data.field_index != field_index) {
            const msg = msg: {
                const msg = try sema.errMsg(
                    block,
                    src,
                    "field '{s}' has index '{d}' but pointer value is index '{d}' of struct '{}'",
                    .{
                        field_name,
                        field_index,
                        payload.data.field_index,
                        parent_ty.fmt(sema.mod),
                    },
                );
                errdefer msg.destroy(sema.gpa);
                try sema.addDeclaredHereNote(msg, parent_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        return sema.addConstant(result_ptr, payload.data.container_ptr);
    }

    try sema.requireRuntimeBlock(block, src, ptr_src);
    try sema.queueFullTypeResolution(result_ptr);
    return block.addInst(.{
        .tag = .field_parent_ptr,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(result_ptr),
            .payload = try block.sema.addExtra(Air.FieldParentPtr{
                .field_ptr = casted_field_ptr,
                .field_index = @intCast(u32, field_index),
            }),
        } },
    });
}

fn zirMinMax(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
    comptime air_tag: Air.Inst.Tag,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
    const src = inst_data.src();
    const lhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const rhs_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const lhs = try sema.resolveInst(extra.lhs);
    const rhs = try sema.resolveInst(extra.rhs);
    try sema.checkNumericType(block, lhs_src, sema.typeOf(lhs));
    try sema.checkNumericType(block, rhs_src, sema.typeOf(rhs));
    return sema.analyzeMinMax(block, src, lhs, rhs, air_tag, lhs_src, rhs_src);
}

fn analyzeMinMax(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    lhs: Air.Inst.Ref,
    rhs: Air.Inst.Ref,
    comptime air_tag: Air.Inst.Tag,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const simd_op = try sema.checkSimdBinOp(block, src, lhs, rhs, lhs_src, rhs_src);

    // TODO @max(max_int, undefined) should return max_int

    const runtime_src = if (simd_op.lhs_val) |lhs_val| rs: {
        if (lhs_val.isUndef()) return sema.addConstUndef(simd_op.result_ty);

        const rhs_val = simd_op.rhs_val orelse break :rs rhs_src;

        if (rhs_val.isUndef()) return sema.addConstUndef(simd_op.result_ty);

        try sema.resolveLazyValue(lhs_val);
        try sema.resolveLazyValue(rhs_val);

        const opFunc = switch (air_tag) {
            .min => Value.numberMin,
            .max => Value.numberMax,
            else => unreachable,
        };
        const target = sema.mod.getTarget();
        const vec_len = simd_op.len orelse {
            const result_val = opFunc(lhs_val, rhs_val, target);
            return sema.addConstant(simd_op.result_ty, result_val);
        };
        var lhs_buf: Value.ElemValueBuffer = undefined;
        var rhs_buf: Value.ElemValueBuffer = undefined;
        const elems = try sema.arena.alloc(Value, vec_len);
        for (elems, 0..) |*elem, i| {
            const lhs_elem_val = lhs_val.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem_val = rhs_val.elemValueBuffer(sema.mod, i, &rhs_buf);
            elem.* = opFunc(lhs_elem_val, rhs_elem_val, target);
        }
        return sema.addConstant(
            simd_op.result_ty,
            try Value.Tag.aggregate.create(sema.arena, elems),
        );
    } else rs: {
        if (simd_op.rhs_val) |rhs_val| {
            if (rhs_val.isUndef()) return sema.addConstUndef(simd_op.result_ty);
        }
        break :rs lhs_src;
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addBinOp(air_tag, simd_op.lhs, simd_op.rhs);
}

fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Memcpy, inst_data.payload_index).data;
    const src = inst_data.src();
    const dest_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const src_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const len_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const uncasted_dest_ptr = try sema.resolveInst(extra.dest);

    // TODO AstGen's coerced_ty cannot handle volatile here
    var dest_ptr_info = Type.initTag(.manyptr_u8).ptrInfo().data;
    dest_ptr_info.@"volatile" = sema.typeOf(uncasted_dest_ptr).isVolatilePtr();
    const dest_ptr_ty = try Type.ptr(sema.arena, sema.mod, dest_ptr_info);
    const dest_ptr = try sema.coerce(block, dest_ptr_ty, uncasted_dest_ptr, dest_src);

    const uncasted_src_ptr = try sema.resolveInst(extra.source);
    var src_ptr_info = Type.initTag(.manyptr_const_u8).ptrInfo().data;
    src_ptr_info.@"volatile" = sema.typeOf(uncasted_src_ptr).isVolatilePtr();
    const src_ptr_ty = try Type.ptr(sema.arena, sema.mod, src_ptr_info);
    const src_ptr = try sema.coerce(block, src_ptr_ty, uncasted_src_ptr, src_src);
    const len = try sema.coerce(block, Type.usize, try sema.resolveInst(extra.byte_count), len_src);

    const runtime_src = if (try sema.resolveDefinedValue(block, dest_src, dest_ptr)) |dest_ptr_val| rs: {
        if (!dest_ptr_val.isComptimeMutablePtr()) break :rs dest_src;
        if (try sema.resolveDefinedValue(block, src_src, src_ptr)) |src_ptr_val| {
            if (!src_ptr_val.isComptimeMutablePtr()) break :rs src_src;
            if (try sema.resolveDefinedValue(block, len_src, len)) |len_val| {
                _ = len_val;
                return sema.fail(block, src, "TODO: Sema.zirMemcpy at comptime", .{});
            } else break :rs len_src;
        } else break :rs src_src;
    } else dest_src;

    try sema.requireRuntimeBlock(block, src, runtime_src);
    _ = try block.addInst(.{
        .tag = .memcpy,
        .data = .{ .pl_op = .{
            .operand = dest_ptr,
            .payload = try sema.addExtra(Air.Bin{
                .lhs = src_ptr,
                .rhs = len,
            }),
        } },
    });
}

fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.Memset, inst_data.payload_index).data;
    const src = inst_data.src();
    const dest_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
    const value_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
    const len_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
    const uncasted_dest_ptr = try sema.resolveInst(extra.dest);

    // TODO AstGen's coerced_ty cannot handle volatile here
    var ptr_info = Type.initTag(.manyptr_u8).ptrInfo().data;
    ptr_info.@"volatile" = sema.typeOf(uncasted_dest_ptr).isVolatilePtr();
    const dest_ptr_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);
    const dest_ptr = try sema.coerce(block, dest_ptr_ty, uncasted_dest_ptr, dest_src);

    const value = try sema.coerce(block, Type.u8, try sema.resolveInst(extra.byte), value_src);
    const len = try sema.coerce(block, Type.usize, try sema.resolveInst(extra.byte_count), len_src);

    const runtime_src = if (try sema.resolveDefinedValue(block, dest_src, dest_ptr)) |ptr_val| rs: {
        if (!ptr_val.isComptimeMutablePtr()) break :rs dest_src;
        if (try sema.resolveDefinedValue(block, len_src, len)) |len_val| {
            if (try sema.resolveMaybeUndefVal(value)) |val| {
                _ = len_val;
                _ = val;
                return sema.fail(block, src, "TODO: Sema.zirMemset at comptime", .{});
            } else break :rs value_src;
        } else break :rs len_src;
    } else dest_src;

    try sema.requireRuntimeBlock(block, src, runtime_src);
    _ = try block.addInst(.{
        .tag = .memset,
        .data = .{ .pl_op = .{
            .operand = dest_ptr,
            .payload = try sema.addExtra(Air.Bin{
                .lhs = value,
                .rhs = len,
            }),
        } },
    });
}

fn zirBuiltinAsyncCall(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);
    return sema.failWithUseOfAsync(block, src);
}

fn zirResume(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();
    return sema.failWithUseOfAsync(block, src);
}

fn zirAwait(
    sema: *Sema,
    block: *Block,
    inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
    const inst_data = sema.code.instructions.items(.data)[inst].un_node;
    const src = inst_data.src();

    return sema.failWithUseOfAsync(block, src);
}

fn zirAwaitNosuspend(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src = LazySrcLoc.nodeOffset(extra.node);

    return sema.failWithUseOfAsync(block, src);
}

fn zirVarExtended(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.ExtendedVar, extended.operand);
    const ty_src: LazySrcLoc = .{ .node_offset_var_decl_ty = 0 };
    const init_src: LazySrcLoc = .{ .node_offset_var_decl_init = 0 };
    const small = @bitCast(Zir.Inst.ExtendedVar.Small, extended.small);

    var extra_index: usize = extra.end;

    const lib_name: ?[]const u8 = if (small.has_lib_name) blk: {
        const lib_name = sema.code.nullTerminatedString(sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk lib_name;
    } else null;

    // ZIR supports encoding this information but it is not used; the information
    // is encoded via the Decl entry.
    assert(!small.has_align);

    const uncasted_init: Air.Inst.Ref = if (small.has_init) blk: {
        const init_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk try sema.resolveInst(init_ref);
    } else .none;

    const have_ty = extra.data.var_type != .none;
    const var_ty = if (have_ty)
        try sema.resolveType(block, ty_src, extra.data.var_type)
    else
        sema.typeOf(uncasted_init);

    const init_val = if (uncasted_init != .none) blk: {
        const init = if (have_ty)
            try sema.coerce(block, var_ty, uncasted_init, init_src)
        else
            uncasted_init;

        break :blk (try sema.resolveMaybeUndefVal(init)) orelse
            return sema.failWithNeededComptime(block, init_src, "container level variable initializers must be comptime-known");
    } else Value.initTag(.unreachable_value);

    try sema.validateVarType(block, ty_src, var_ty, small.is_extern);

    const new_var = try sema.gpa.create(Module.Var);
    errdefer sema.gpa.destroy(new_var);

    log.debug("created variable {*} owner_decl: {*} ({s})", .{
        new_var, sema.owner_decl, sema.owner_decl.name,
    });

    new_var.* = .{
        .owner_decl = sema.owner_decl_index,
        .init = init_val,
        .is_extern = small.is_extern,
        .is_mutable = true,
        .is_threadlocal = small.is_threadlocal,
        .is_weak_linkage = false,
        .lib_name = null,
    };

    if (lib_name) |lname| {
        new_var.lib_name = try sema.handleExternLibName(block, ty_src, lname);
    }

    const result = try sema.addConstant(
        var_ty,
        try Value.Tag.variable.create(sema.arena, new_var),
    );
    return result;
}

fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
    const tracy = trace(@src());
    defer tracy.end();

    const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
    const extra = sema.code.extraData(Zir.Inst.FuncFancy, inst_data.payload_index);
    const target = sema.mod.getTarget();

    const align_src: LazySrcLoc = .{ .node_offset_fn_type_align = inst_data.src_node };
    const addrspace_src: LazySrcLoc = .{ .node_offset_fn_type_addrspace = inst_data.src_node };
    const section_src: LazySrcLoc = .{ .node_offset_fn_type_section = inst_data.src_node };
    const cc_src: LazySrcLoc = .{ .node_offset_fn_type_cc = inst_data.src_node };
    const ret_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = inst_data.src_node };
    const has_body = extra.data.body_len != 0;

    var extra_index: usize = extra.end;

    const lib_name: ?[]const u8 = if (extra.data.bits.has_lib_name) blk: {
        const lib_name = sema.code.nullTerminatedString(sema.code.extra[extra_index]);
        extra_index += 1;
        break :blk lib_name;
    } else null;

    if (has_body and
        (extra.data.bits.has_align_body or extra.data.bits.has_align_ref) and
        !target_util.supportsFunctionAlignment(target))
    {
        return sema.fail(block, align_src, "target does not support function alignment", .{});
    }

    const @"align": ?u32 = if (extra.data.bits.has_align_body) blk: {
        const body_len = sema.code.extra[extra_index];
        extra_index += 1;
        const body = sema.code.extra[extra_index..][0..body_len];
        extra_index += body.len;

        const val = try sema.resolveGenericBody(block, align_src, body, inst, Type.u29, "alignment must be comptime-known");
        if (val.tag() == .generic_poison) {
            break :blk null;
        }
        const alignment = @intCast(u32, val.toUnsignedInt(target));
        try sema.validateAlign(block, align_src, alignment);
        if (alignment == target_util.defaultFunctionAlignment(target)) {
            break :blk 0;
        } else {
            break :blk alignment;
        }
    } else if (extra.data.bits.has_align_ref) blk: {
        const align_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const align_tv = sema.resolveInstConst(block, align_src, align_ref, "alignment must be comptime-known") catch |err| switch (err) {
            error.GenericPoison => {
                break :blk null;
            },
            else => |e| return e,
        };
        const alignment = @intCast(u32, align_tv.val.toUnsignedInt(target));
        try sema.validateAlign(block, align_src, alignment);
        if (alignment == target_util.defaultFunctionAlignment(target)) {
            break :blk 0;
        } else {
            break :blk alignment;
        }
    } else 0;

    const @"addrspace": ?std.builtin.AddressSpace = if (extra.data.bits.has_addrspace_body) blk: {
        const body_len = sema.code.extra[extra_index];
        extra_index += 1;
        const body = sema.code.extra[extra_index..][0..body_len];
        extra_index += body.len;

        const addrspace_ty = try sema.getBuiltinType("AddressSpace");
        const val = try sema.resolveGenericBody(block, addrspace_src, body, inst, addrspace_ty, "addrespace must be comptime-known");
        if (val.tag() == .generic_poison) {
            break :blk null;
        }
        break :blk val.toEnum(std.builtin.AddressSpace);
    } else if (extra.data.bits.has_addrspace_ref) blk: {
        const addrspace_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const addrspace_tv = sema.resolveInstConst(block, addrspace_src, addrspace_ref, "addrespace must be comptime-known") catch |err| switch (err) {
            error.GenericPoison => {
                break :blk null;
            },
            else => |e| return e,
        };
        break :blk addrspace_tv.val.toEnum(std.builtin.AddressSpace);
    } else target_util.defaultAddressSpace(target, .function);

    const @"linksection": FuncLinkSection = if (extra.data.bits.has_section_body) blk: {
        const body_len = sema.code.extra[extra_index];
        extra_index += 1;
        const body = sema.code.extra[extra_index..][0..body_len];
        extra_index += body.len;

        const ty = Type.initTag(.const_slice_u8);
        const val = try sema.resolveGenericBody(block, section_src, body, inst, ty, "linksection must be comptime-known");
        if (val.tag() == .generic_poison) {
            break :blk FuncLinkSection{ .generic = {} };
        }
        break :blk FuncLinkSection{ .explicit = try val.toAllocatedBytes(ty, sema.arena, sema.mod) };
    } else if (extra.data.bits.has_section_ref) blk: {
        const section_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const section_name = sema.resolveConstString(block, section_src, section_ref, "linksection must be comptime-known") catch |err| switch (err) {
            error.GenericPoison => {
                break :blk FuncLinkSection{ .generic = {} };
            },
            else => |e| return e,
        };
        break :blk FuncLinkSection{ .explicit = section_name };
    } else FuncLinkSection{ .default = {} };

    const cc: ?std.builtin.CallingConvention = if (extra.data.bits.has_cc_body) blk: {
        const body_len = sema.code.extra[extra_index];
        extra_index += 1;
        const body = sema.code.extra[extra_index..][0..body_len];
        extra_index += body.len;

        const cc_ty = try sema.getBuiltinType("CallingConvention");
        const val = try sema.resolveGenericBody(block, cc_src, body, inst, cc_ty, "calling convention must be comptime-known");
        if (val.tag() == .generic_poison) {
            break :blk null;
        }
        break :blk val.toEnum(std.builtin.CallingConvention);
    } else if (extra.data.bits.has_cc_ref) blk: {
        const cc_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const cc_tv = sema.resolveInstConst(block, cc_src, cc_ref, "calling convention must be comptime-known") catch |err| switch (err) {
            error.GenericPoison => {
                break :blk null;
            },
            else => |e| return e,
        };
        break :blk cc_tv.val.toEnum(std.builtin.CallingConvention);
    } else if (sema.owner_decl.is_exported and has_body)
        .C
    else
        .Unspecified;

    const ret_ty: Type = if (extra.data.bits.has_ret_ty_body) blk: {
        const body_len = sema.code.extra[extra_index];
        extra_index += 1;
        const body = sema.code.extra[extra_index..][0..body_len];
        extra_index += body.len;

        const val = try sema.resolveGenericBody(block, ret_src, body, inst, Type.type, "return type must be comptime-known");
        var buffer: Value.ToTypeBuffer = undefined;
        const ty = try val.toType(&buffer).copy(sema.arena);
        break :blk ty;
    } else if (extra.data.bits.has_ret_ty_ref) blk: {
        const ret_ty_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
        extra_index += 1;
        const ret_ty_tv = sema.resolveInstConst(block, ret_src, ret_ty_ref, "return type must be comptime-known") catch |err| switch (err) {
            error.GenericPoison => {
                break :blk Type.initTag(.generic_poison);
            },
            else => |e| return e,
        };
        var buffer: Value.ToTypeBuffer = undefined;
        const ty = try ret_ty_tv.val.toType(&buffer).copy(sema.arena);
        break :blk ty;
    } else Type.void;

    const noalias_bits: u32 = if (extra.data.bits.has_any_noalias) blk: {
        const x = sema.code.extra[extra_index];
        extra_index += 1;
        break :blk x;
    } else 0;

    var src_locs: Zir.Inst.Func.SrcLocs = undefined;
    if (has_body) {
        extra_index += extra.data.body_len;
        src_locs = sema.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
    }

    const is_var_args = extra.data.bits.is_var_args;
    const is_inferred_error = extra.data.bits.is_inferred_error;
    const is_extern = extra.data.bits.is_extern;
    const is_noinline = extra.data.bits.is_noinline;

    return sema.funcCommon(
        block,
        inst_data.src_node,
        inst,
        @"align",
        @"addrspace",
        @"linksection",
        cc,
        ret_ty,
        is_var_args,
        is_inferred_error,
        is_extern,
        has_body,
        src_locs,
        lib_name,
        noalias_bits,
        is_noinline,
    );
}

fn zirCUndef(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };

    const name = try sema.resolveConstString(block, src, extra.operand, "name of macro being undefined must be comptime-known");
    try block.c_import_buf.?.writer().print("#undef {s}\n", .{name});
    return Air.Inst.Ref.void_value;
}

fn zirCInclude(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };

    const name = try sema.resolveConstString(block, src, extra.operand, "path being included must be comptime-known");
    try block.c_import_buf.?.writer().print("#include <{s}>\n", .{name});
    return Air.Inst.Ref.void_value;
}

fn zirCDefine(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const name_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const val_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };

    const name = try sema.resolveConstString(block, name_src, extra.lhs, "name of macro being undefined must be comptime-known");
    const rhs = try sema.resolveInst(extra.rhs);
    if (sema.typeOf(rhs).zigTypeTag() != .Void) {
        const value = try sema.resolveConstString(block, val_src, extra.rhs, "value of macro being undefined must be comptime-known");
        try block.c_import_buf.?.writer().print("#define {s} {s}\n", .{ name, value });
    } else {
        try block.c_import_buf.?.writer().print("#define {s}\n", .{name});
    }
    return Air.Inst.Ref.void_value;
}

fn zirWasmMemorySize(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
    const index_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const builtin_src = LazySrcLoc.nodeOffset(extra.node);
    const target = sema.mod.getTarget();
    if (!target.isWasm()) {
        return sema.fail(block, builtin_src, "builtin @wasmMemorySize is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
    }

    const index = @intCast(u32, try sema.resolveInt(block, index_src, extra.operand, Type.u32, "wasm memory size index must be comptime-known"));
    try sema.requireRuntimeBlock(block, builtin_src, null);
    return block.addInst(.{
        .tag = .wasm_memory_size,
        .data = .{ .pl_op = .{
            .operand = .none,
            .payload = index,
        } },
    });
}

fn zirWasmMemoryGrow(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const builtin_src = LazySrcLoc.nodeOffset(extra.node);
    const index_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const delta_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
    const target = sema.mod.getTarget();
    if (!target.isWasm()) {
        return sema.fail(block, builtin_src, "builtin @wasmMemoryGrow is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
    }

    const index = @intCast(u32, try sema.resolveInt(block, index_src, extra.lhs, Type.u32, "wasm memory size index must be comptime-known"));
    const delta = try sema.coerce(block, Type.u32, try sema.resolveInst(extra.rhs), delta_src);

    try sema.requireRuntimeBlock(block, builtin_src, null);
    return block.addInst(.{
        .tag = .wasm_memory_grow,
        .data = .{ .pl_op = .{
            .operand = delta,
            .payload = index,
        } },
    });
}

fn resolvePrefetchOptions(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
) CompileError!std.builtin.PrefetchOptions {
    const options_ty = try sema.getBuiltinType("PrefetchOptions");
    const options = try sema.coerce(block, options_ty, try sema.resolveInst(zir_ref), src);
    const target = sema.mod.getTarget();

    const rw_src = sema.maybeOptionsSrc(block, src, "rw");
    const locality_src = sema.maybeOptionsSrc(block, src, "locality");
    const cache_src = sema.maybeOptionsSrc(block, src, "cache");

    const rw = try sema.fieldVal(block, src, options, "rw", rw_src);
    const rw_val = try sema.resolveConstValue(block, rw_src, rw, "prefetch read/write must be comptime-known");

    const locality = try sema.fieldVal(block, src, options, "locality", locality_src);
    const locality_val = try sema.resolveConstValue(block, locality_src, locality, "prefetch locality must be comptime-known");

    const cache = try sema.fieldVal(block, src, options, "cache", cache_src);
    const cache_val = try sema.resolveConstValue(block, cache_src, cache, "prefetch cache must be comptime-known");

    return std.builtin.PrefetchOptions{
        .rw = rw_val.toEnum(std.builtin.PrefetchOptions.Rw),
        .locality = @intCast(u2, locality_val.toUnsignedInt(target)),
        .cache = cache_val.toEnum(std.builtin.PrefetchOptions.Cache),
    };
}

fn zirPrefetch(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const opts_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
    const ptr = try sema.resolveInst(extra.lhs);
    try sema.checkPtrOperand(block, ptr_src, sema.typeOf(ptr));

    const options = sema.resolvePrefetchOptions(block, .unneeded, extra.rhs) catch |err| switch (err) {
        error.NeededSourceLocation => {
            _ = try sema.resolvePrefetchOptions(block, opts_src, extra.rhs);
            unreachable;
        },
        else => |e| return e,
    };

    if (!block.is_comptime) {
        _ = try block.addInst(.{
            .tag = .prefetch,
            .data = .{ .prefetch = .{
                .ptr = ptr,
                .rw = options.rw,
                .locality = options.locality,
                .cache = options.cache,
            } },
        });
    }

    return Air.Inst.Ref.void_value;
}

fn resolveExternOptions(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
) CompileError!std.builtin.ExternOptions {
    const options_inst = try sema.resolveInst(zir_ref);
    const extern_options_ty = try sema.getBuiltinType("ExternOptions");
    const options = try sema.coerce(block, extern_options_ty, options_inst, src);
    const mod = sema.mod;

    const name_src = sema.maybeOptionsSrc(block, src, "name");
    const library_src = sema.maybeOptionsSrc(block, src, "library");
    const linkage_src = sema.maybeOptionsSrc(block, src, "linkage");
    const thread_local_src = sema.maybeOptionsSrc(block, src, "thread_local");

    const name_ref = try sema.fieldVal(block, src, options, "name", name_src);
    const name_val = try sema.resolveConstValue(block, name_src, name_ref, "name of the extern symbol must be comptime-known");
    const name = try name_val.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, mod);

    const library_name_inst = try sema.fieldVal(block, src, options, "library_name", library_src);
    const library_name_val = try sema.resolveConstValue(block, library_src, library_name_inst, "library in which extern symbol is must be comptime-known");

    const linkage_ref = try sema.fieldVal(block, src, options, "linkage", linkage_src);
    const linkage_val = try sema.resolveConstValue(block, linkage_src, linkage_ref, "linkage of the extern symbol must be comptime-known");
    const linkage = linkage_val.toEnum(std.builtin.GlobalLinkage);

    const is_thread_local = try sema.fieldVal(block, src, options, "is_thread_local", thread_local_src);
    const is_thread_local_val = try sema.resolveConstValue(block, thread_local_src, is_thread_local, "threadlocality of the extern symbol must be comptime-known");

    const library_name = if (!library_name_val.isNull()) blk: {
        const payload = library_name_val.castTag(.opt_payload).?.data;
        const library_name = try payload.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, mod);
        if (library_name.len == 0) {
            return sema.fail(block, library_src, "library name name cannot be empty", .{});
        }
        break :blk try sema.handleExternLibName(block, library_src, library_name);
    } else null;

    if (name.len == 0) {
        return sema.fail(block, name_src, "extern symbol name cannot be empty", .{});
    }

    if (linkage != .Weak and linkage != .Strong) {
        return sema.fail(block, linkage_src, "extern symbol must use strong or weak linkage", .{});
    }

    return std.builtin.ExternOptions{
        .name = name,
        .library_name = library_name,
        .linkage = linkage,
        .is_thread_local = is_thread_local_val.toBool(),
    };
}

fn zirBuiltinExtern(
    sema: *Sema,
    block: *Block,
    extended: Zir.Inst.Extended.InstData,
) CompileError!Air.Inst.Ref {
    const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
    const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
    const options_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };

    var ty = try sema.resolveType(block, ty_src, extra.lhs);
    if (!ty.isPtrAtRuntime()) {
        return sema.fail(block, ty_src, "expected (optional) pointer", .{});
    }

    const options = sema.resolveExternOptions(block, .unneeded, extra.rhs) catch |err| switch (err) {
        error.NeededSourceLocation => {
            _ = try sema.resolveExternOptions(block, options_src, extra.rhs);
            unreachable;
        },
        else => |e| return e,
    };

    if (options.linkage == .Weak and !ty.ptrAllowsZero()) {
        ty = try Type.optional(sema.arena, ty);
    }

    // TODO check duplicate extern

    const new_decl_index = try sema.mod.allocateNewDecl(sema.owner_decl.src_namespace, sema.owner_decl.src_node, null);
    errdefer sema.mod.destroyDecl(new_decl_index);
    const new_decl = sema.mod.declPtr(new_decl_index);
    new_decl.name = try sema.gpa.dupeZ(u8, options.name);

    {
        var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
        errdefer new_decl_arena.deinit();
        const new_decl_arena_allocator = new_decl_arena.allocator();

        const new_var = try new_decl_arena_allocator.create(Module.Var);
        new_var.* = .{
            .owner_decl = sema.owner_decl_index,
            .init = Value.initTag(.unreachable_value),
            .is_extern = true,
            .is_mutable = false,
            .is_threadlocal = options.is_thread_local,
            .is_weak_linkage = options.linkage == .Weak,
            .lib_name = null,
        };

        new_decl.src_line = sema.owner_decl.src_line;
        // We only access this decl through the decl_ref with the correct type created
        // below, so this type doesn't matter
        new_decl.ty = Type.Tag.init(.anyopaque);
        new_decl.val = try Value.Tag.variable.create(new_decl_arena_allocator, new_var);
        new_decl.@"align" = 0;
        new_decl.@"linksection" = null;
        new_decl.has_tv = true;
        new_decl.analysis = .complete;
        new_decl.generation = sema.mod.generation;

        try new_decl.finalizeNewArena(&new_decl_arena);
    }

    try sema.mod.declareDeclDependency(sema.owner_decl_index, new_decl_index);
    try sema.ensureDeclAnalyzed(new_decl_index);

    const ref = try Value.Tag.decl_ref.create(sema.arena, new_decl_index);
    return sema.addConstant(ty, ref);
}

fn requireRuntimeBlock(sema: *Sema, block: *Block, src: LazySrcLoc, runtime_src: ?LazySrcLoc) !void {
    if (block.is_comptime) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "unable to evaluate comptime expression", .{});
            errdefer msg.destroy(sema.gpa);

            if (runtime_src) |some| {
                try sema.errNote(block, some, msg, "operation is runtime due to this operand", .{});
            }
            if (block.comptime_reason) |some| {
                try some.explain(sema, msg);
            }
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
}

/// Emit a compile error if type cannot be used for a runtime variable.
fn validateVarType(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    var_ty: Type,
    is_extern: bool,
) CompileError!void {
    if (try sema.validateRunTimeType(var_ty, is_extern)) return;

    const mod = sema.mod;

    const msg = msg: {
        const msg = try sema.errMsg(block, src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(mod)});
        errdefer msg.destroy(sema.gpa);

        const src_decl = mod.declPtr(block.src_decl);
        try sema.explainWhyTypeIsComptime(block, src, msg, src.toSrcLoc(src_decl), var_ty);
        if (var_ty.zigTypeTag() == .ComptimeInt or var_ty.zigTypeTag() == .ComptimeFloat) {
            try sema.errNote(block, src, msg, "to modify this variable at runtime, it must be given an explicit fixed-size number type", .{});
        }

        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn validateRunTimeType(
    sema: *Sema,
    var_ty: Type,
    is_extern: bool,
) CompileError!bool {
    var ty = var_ty;
    while (true) switch (ty.zigTypeTag()) {
        .Bool,
        .Int,
        .Float,
        .ErrorSet,
        .Frame,
        .AnyFrame,
        .Void,
        => return true,

        .Enum => return !(try sema.typeRequiresComptime(ty)),

        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .NoReturn,
        .Type,
        .Undefined,
        .Null,
        .Fn,
        => return false,

        .Pointer => {
            const elem_ty = ty.childType();
            switch (elem_ty.zigTypeTag()) {
                .Opaque => return true,
                .Fn => return elem_ty.isFnOrHasRuntimeBits(),
                else => ty = elem_ty,
            }
        },
        .Opaque => return is_extern,

        .Optional => {
            var buf: Type.Payload.ElemType = undefined;
            const child_ty = ty.optionalChild(&buf);
            return sema.validateRunTimeType(child_ty, is_extern);
        },
        .Array, .Vector => ty = ty.elemType(),

        .ErrorUnion => ty = ty.errorUnionPayload(),

        .Struct, .Union => {
            const resolved_ty = try sema.resolveTypeFields(ty);
            const needs_comptime = try sema.typeRequiresComptime(resolved_ty);
            return !needs_comptime;
        },
    };
}

const TypeSet = std.HashMapUnmanaged(Type, void, Type.HashContext64, std.hash_map.default_max_load_percentage);

fn explainWhyTypeIsComptime(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    msg: *Module.ErrorMsg,
    src_loc: Module.SrcLoc,
    ty: Type,
) CompileError!void {
    var type_set = TypeSet{};
    defer type_set.deinit(sema.gpa);

    try sema.resolveTypeFully(ty);
    return sema.explainWhyTypeIsComptimeInner(block, src, msg, src_loc, ty, &type_set);
}

fn explainWhyTypeIsComptimeInner(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    msg: *Module.ErrorMsg,
    src_loc: Module.SrcLoc,
    ty: Type,
    type_set: *TypeSet,
) CompileError!void {
    const mod = sema.mod;
    switch (ty.zigTypeTag()) {
        .Bool,
        .Int,
        .Float,
        .ErrorSet,
        .Enum,
        .Frame,
        .AnyFrame,
        .Void,
        => return,

        .Fn => {
            try mod.errNoteNonLazy(src_loc, msg, "use '*const {}' for a function pointer type", .{
                ty.fmt(sema.mod),
            });
        },

        .Type => {
            try mod.errNoteNonLazy(src_loc, msg, "types are not available at runtime", .{});
        },

        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .NoReturn,
        .Undefined,
        .Null,
        => return,

        .Opaque => {
            try mod.errNoteNonLazy(src_loc, msg, "opaque type '{}' has undefined size", .{ty.fmt(sema.mod)});
        },

        .Array, .Vector => {
            try sema.explainWhyTypeIsComptimeInner(block, src, msg, src_loc, ty.elemType(), type_set);
        },
        .Pointer => {
            const elem_ty = ty.elemType2();
            if (elem_ty.zigTypeTag() == .Fn) {
                const fn_info = elem_ty.fnInfo();
                if (fn_info.is_generic) {
                    try mod.errNoteNonLazy(src_loc, msg, "function is generic", .{});
                }
                switch (fn_info.cc) {
                    .Inline => try mod.errNoteNonLazy(src_loc, msg, "function has inline calling convention", .{}),
                    else => {},
                }
                if (fn_info.return_type.comptimeOnly()) {
                    try mod.errNoteNonLazy(src_loc, msg, "function has a comptime-only return type", .{});
                }
                return;
            }
            try sema.explainWhyTypeIsComptimeInner(block, src, msg, src_loc, ty.elemType(), type_set);
        },

        .Optional => {
            var buf: Type.Payload.ElemType = undefined;
            try sema.explainWhyTypeIsComptimeInner(block, src, msg, src_loc, ty.optionalChild(&buf), type_set);
        },
        .ErrorUnion => {
            try sema.explainWhyTypeIsComptimeInner(block, src, msg, src_loc, ty.errorUnionPayload(), type_set);
        },

        .Struct => {
            if ((try type_set.getOrPutContext(sema.gpa, ty, .{ .mod = mod })).found_existing) return;

            if (ty.castTag(.@"struct")) |payload| {
                const struct_obj = payload.data;
                for (struct_obj.fields.values(), 0..) |field, i| {
                    const field_src_loc = struct_obj.fieldSrcLoc(sema.mod, .{
                        .index = i,
                        .range = .type,
                    });

                    if (try sema.typeRequiresComptime(field.ty)) {
                        try mod.errNoteNonLazy(field_src_loc, msg, "struct requires comptime because of this field", .{});
                        try sema.explainWhyTypeIsComptimeInner(block, src, msg, field_src_loc, field.ty, type_set);
                    }
                }
            }
            // TODO tuples
        },

        .Union => {
            if ((try type_set.getOrPutContext(sema.gpa, ty, .{ .mod = mod })).found_existing) return;

            if (ty.cast(Type.Payload.Union)) |payload| {
                const union_obj = payload.data;
                for (union_obj.fields.values(), 0..) |field, i| {
                    const field_src_loc = union_obj.fieldSrcLoc(sema.mod, .{
                        .index = i,
                        .range = .type,
                    });

                    if (try sema.typeRequiresComptime(field.ty)) {
                        try mod.errNoteNonLazy(field_src_loc, msg, "union requires comptime because of this field", .{});
                        try sema.explainWhyTypeIsComptimeInner(block, src, msg, field_src_loc, field.ty, type_set);
                    }
                }
            }
        },
    }
}

const ExternPosition = enum {
    ret_ty,
    param_ty,
    union_field,
    struct_field,
    element,
    other,
};

/// Returns true if `ty` is allowed in extern types.
/// Does *NOT* require `ty` to be resolved in any way.
/// Calls `resolveTypeLayout` for packed containers.
fn validateExternType(
    sema: *Sema,
    ty: Type,
    position: ExternPosition,
) !bool {
    switch (ty.zigTypeTag()) {
        .Type,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .Undefined,
        .Null,
        .ErrorUnion,
        .ErrorSet,
        .Frame,
        => return false,
        .Void => return position == .union_field or position == .ret_ty,
        .NoReturn => return position == .ret_ty,
        .Opaque,
        .Bool,
        .Float,
        .AnyFrame,
        => return true,
        .Pointer => return !ty.isSlice(),
        .Int => switch (ty.intInfo(sema.mod.getTarget()).bits) {
            8, 16, 32, 64, 128 => return true,
            else => return false,
        },
        .Fn => {
            if (position != .other) return false;
            return switch (ty.fnCallingConvention()) {
                // For now we want to authorize PTX kernel to use zig objects, even if we end up exposing the ABI.
                // The goal is to experiment with more integrated CPU/GPU code.
                .PtxKernel => true,
                else => !Type.fnCallingConventionAllowsZigTypes(ty.fnCallingConvention()),
            };
        },
        .Enum => {
            var buf: Type.Payload.Bits = undefined;
            return sema.validateExternType(ty.intTagType(&buf), position);
        },
        .Struct, .Union => switch (ty.containerLayout()) {
            .Extern => return true,
            .Packed => {
                const target = sema.mod.getTarget();
                const bit_size = try ty.bitSizeAdvanced(target, sema);
                switch (bit_size) {
                    8, 16, 32, 64, 128 => return true,
                    else => return false,
                }
            },
            .Auto => return false,
        },
        .Array => {
            if (position == .ret_ty or position == .param_ty) return false;
            return sema.validateExternType(ty.elemType2(), .element);
        },
        .Vector => return sema.validateExternType(ty.elemType2(), .element),
        .Optional => return ty.isPtrLikeOptional(),
    }
}

fn explainWhyTypeIsNotExtern(
    sema: *Sema,
    msg: *Module.ErrorMsg,
    src_loc: Module.SrcLoc,
    ty: Type,
    position: ExternPosition,
) CompileError!void {
    const mod = sema.mod;
    switch (ty.zigTypeTag()) {
        .Opaque,
        .Bool,
        .Float,
        .AnyFrame,
        => return,

        .Type,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .Undefined,
        .Null,
        .ErrorUnion,
        .ErrorSet,
        .Frame,
        => return,

        .Pointer => try mod.errNoteNonLazy(src_loc, msg, "slices have no guaranteed in-memory representation", .{}),
        .Void => try mod.errNoteNonLazy(src_loc, msg, "'void' is a zero bit type; for C 'void' use 'anyopaque'", .{}),
        .NoReturn => try mod.errNoteNonLazy(src_loc, msg, "'noreturn' is only allowed as a return type", .{}),
        .Int => if (ty.intInfo(sema.mod.getTarget()).bits > 128) {
            try mod.errNoteNonLazy(src_loc, msg, "only integers with less than 128 bits are extern compatible", .{});
        } else {
            try mod.errNoteNonLazy(src_loc, msg, "only integers with power of two bits are extern compatible", .{});
        },
        .Fn => {
            if (position != .other) {
                try mod.errNoteNonLazy(src_loc, msg, "type has no guaranteed in-memory representation", .{});
                try mod.errNoteNonLazy(src_loc, msg, "use '*const ' to make a function pointer type", .{});
                return;
            }
            switch (ty.fnCallingConvention()) {
                .Unspecified => try mod.errNoteNonLazy(src_loc, msg, "extern function must specify calling convention", .{}),
                .Async => try mod.errNoteNonLazy(src_loc, msg, "async function cannot be extern", .{}),
                .Inline => try mod.errNoteNonLazy(src_loc, msg, "inline function cannot be extern", .{}),
                else => return,
            }
        },
        .Enum => {
            var buf: Type.Payload.Bits = undefined;
            const tag_ty = ty.intTagType(&buf);
            try mod.errNoteNonLazy(src_loc, msg, "enum tag type '{}' is not extern compatible", .{tag_ty.fmt(sema.mod)});
            try sema.explainWhyTypeIsNotExtern(msg, src_loc, tag_ty, position);
        },
        .Struct => try mod.errNoteNonLazy(src_loc, msg, "only extern structs and ABI sized packed structs are extern compatible", .{}),
        .Union => try mod.errNoteNonLazy(src_loc, msg, "only extern unions and ABI sized packed unions are extern compatible", .{}),
        .Array => {
            if (position == .ret_ty) {
                return mod.errNoteNonLazy(src_loc, msg, "arrays are not allowed as a return type", .{});
            } else if (position == .param_ty) {
                return mod.errNoteNonLazy(src_loc, msg, "arrays are not allowed as a parameter type", .{});
            }
            try sema.explainWhyTypeIsNotExtern(msg, src_loc, ty.elemType2(), .element);
        },
        .Vector => try sema.explainWhyTypeIsNotExtern(msg, src_loc, ty.elemType2(), .element),
        .Optional => try mod.errNoteNonLazy(src_loc, msg, "only pointer like optionals are extern compatible", .{}),
    }
}

/// Returns true if `ty` is allowed in packed types.
/// Does *NOT* require `ty` to be resolved in any way.
fn validatePackedType(ty: Type) bool {
    switch (ty.zigTypeTag()) {
        .Type,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .Undefined,
        .Null,
        .ErrorUnion,
        .ErrorSet,
        .Frame,
        .NoReturn,
        .Opaque,
        .AnyFrame,
        .Fn,
        .Array,
        => return false,
        .Optional => return ty.isPtrLikeOptional(),
        .Void,
        .Bool,
        .Float,
        .Int,
        .Vector,
        .Enum,
        => return true,
        .Pointer => return !ty.isSlice(),
        .Struct, .Union => return ty.containerLayout() == .Packed,
    }
}

fn explainWhyTypeIsNotPacked(
    sema: *Sema,
    msg: *Module.ErrorMsg,
    src_loc: Module.SrcLoc,
    ty: Type,
) CompileError!void {
    const mod = sema.mod;
    switch (ty.zigTypeTag()) {
        .Void,
        .Bool,
        .Float,
        .Int,
        .Vector,
        .Enum,
        => return,
        .Type,
        .ComptimeFloat,
        .ComptimeInt,
        .EnumLiteral,
        .Undefined,
        .Null,
        .Frame,
        .NoReturn,
        .Opaque,
        .ErrorUnion,
        .ErrorSet,
        .AnyFrame,
        .Optional,
        .Array,
        => try mod.errNoteNonLazy(src_loc, msg, "type has no guaranteed in-memory representation", .{}),
        .Pointer => try mod.errNoteNonLazy(src_loc, msg, "slices have no guaranteed in-memory representation", .{}),
        .Fn => {
            try mod.errNoteNonLazy(src_loc, msg, "type has no guaranteed in-memory representation", .{});
            try mod.errNoteNonLazy(src_loc, msg, "use '*const ' to make a function pointer type", .{});
        },
        .Struct => try mod.errNoteNonLazy(src_loc, msg, "only packed structs layout are allowed in packed types", .{}),
        .Union => try mod.errNoteNonLazy(src_loc, msg, "only packed unions layout are allowed in packed types", .{}),
    }
}

pub const PanicId = enum {
    unreach,
    unwrap_null,
    cast_to_null,
    incorrect_alignment,
    invalid_error_code,
    cast_truncated_data,
    negative_to_unsigned,
    integer_overflow,
    shl_overflow,
    shr_overflow,
    divide_by_zero,
    exact_division_remainder,
    inactive_union_field,
    integer_part_out_of_bounds,
    corrupt_switch,
    shift_rhs_too_big,
    invalid_enum_value,
    sentinel_mismatch,
    unwrap_error,
    index_out_of_bounds,
    start_index_greater_than_end,
    for_len_mismatch,
};

fn addSafetyCheck(
    sema: *Sema,
    parent_block: *Block,
    ok: Air.Inst.Ref,
    panic_id: PanicId,
) !void {
    const gpa = sema.gpa;
    assert(!parent_block.is_comptime);

    var fail_block: Block = .{
        .parent = parent_block,
        .sema = sema,
        .src_decl = parent_block.src_decl,
        .namespace = parent_block.namespace,
        .wip_capture_scope = parent_block.wip_capture_scope,
        .instructions = .{},
        .inlining = parent_block.inlining,
        .is_comptime = false,
    };

    defer fail_block.instructions.deinit(gpa);

    try sema.safetyPanic(&fail_block, panic_id);
    try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
}

fn addSafetyCheckExtra(
    sema: *Sema,
    parent_block: *Block,
    ok: Air.Inst.Ref,
    fail_block: *Block,
) !void {
    const gpa = sema.gpa;

    try parent_block.instructions.ensureUnusedCapacity(gpa, 1);

    try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
        1 + // The main block only needs space for the cond_br.
        @typeInfo(Air.CondBr).Struct.fields.len +
        1 + // The ok branch of the cond_br only needs space for the br.
        fail_block.instructions.items.len);

    try sema.air_instructions.ensureUnusedCapacity(gpa, 3);
    const block_inst = @intCast(Air.Inst.Index, sema.air_instructions.len);
    const cond_br_inst = block_inst + 1;
    const br_inst = cond_br_inst + 1;
    sema.air_instructions.appendAssumeCapacity(.{
        .tag = .block,
        .data = .{ .ty_pl = .{
            .ty = .void_type,
            .payload = sema.addExtraAssumeCapacity(Air.Block{
                .body_len = 1,
            }),
        } },
    });
    sema.air_extra.appendAssumeCapacity(cond_br_inst);

    sema.air_instructions.appendAssumeCapacity(.{
        .tag = .cond_br,
        .data = .{ .pl_op = .{
            .operand = ok,
            .payload = sema.addExtraAssumeCapacity(Air.CondBr{
                .then_body_len = 1,
                .else_body_len = @intCast(u32, fail_block.instructions.items.len),
            }),
        } },
    });
    sema.air_extra.appendAssumeCapacity(br_inst);
    sema.air_extra.appendSliceAssumeCapacity(fail_block.instructions.items);

    sema.air_instructions.appendAssumeCapacity(.{
        .tag = .br,
        .data = .{ .br = .{
            .block_inst = block_inst,
            .operand = .void_value,
        } },
    });

    parent_block.instructions.appendAssumeCapacity(block_inst);
}

fn panicWithMsg(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    msg_inst: Air.Inst.Ref,
) !void {
    const mod = sema.mod;
    const arena = sema.arena;

    if (!mod.backendSupportsFeature(.panic_fn)) {
        _ = try block.addNoOp(.breakpoint);
        _ = try block.addNoOp(.unreach);
        return;
    }
    const panic_fn = try sema.getBuiltin("panic");
    const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
    const stack_trace_ty = try sema.resolveTypeFields(unresolved_stack_trace_ty);
    const target = mod.getTarget();
    const ptr_stack_trace_ty = try Type.ptr(arena, mod, .{
        .pointee_type = stack_trace_ty,
        .@"addrspace" = target_util.defaultAddressSpace(target, .global_constant), // TODO might need a place that is more dynamic
    });
    const null_stack_trace = try sema.addConstant(
        try Type.optional(arena, ptr_stack_trace_ty),
        Value.null,
    );
    const args: [3]Air.Inst.Ref = .{ msg_inst, null_stack_trace, .null_value };
    _ = try sema.analyzeCall(block, panic_fn, src, src, .auto, false, &args, null);
}

fn panicUnwrapError(
    sema: *Sema,
    parent_block: *Block,
    operand: Air.Inst.Ref,
    unwrap_err_tag: Air.Inst.Tag,
    is_non_err_tag: Air.Inst.Tag,
) !void {
    assert(!parent_block.is_comptime);
    const ok = try parent_block.addUnOp(is_non_err_tag, operand);
    if (!sema.mod.comp.formatted_panics) {
        return sema.addSafetyCheck(parent_block, ok, .unwrap_error);
    }
    const gpa = sema.gpa;

    var fail_block: Block = .{
        .parent = parent_block,
        .sema = sema,
        .src_decl = parent_block.src_decl,
        .namespace = parent_block.namespace,
        .wip_capture_scope = parent_block.wip_capture_scope,
        .instructions = .{},
        .inlining = parent_block.inlining,
        .is_comptime = false,
    };

    defer fail_block.instructions.deinit(gpa);

    {
        if (!sema.mod.backendSupportsFeature(.panic_unwrap_error)) {
            _ = try fail_block.addNoOp(.breakpoint);
            _ = try fail_block.addNoOp(.unreach);
        } else {
            const panic_fn = try sema.getBuiltin("panicUnwrapError");
            const err = try fail_block.addTyOp(unwrap_err_tag, Type.anyerror, operand);
            const err_return_trace = try sema.getErrorReturnTrace(&fail_block);
            const args: [2]Air.Inst.Ref = .{ err_return_trace, err };
            _ = try sema.analyzeCall(&fail_block, panic_fn, sema.src, sema.src, .auto, false, &args, null);
        }
    }
    try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
}

fn panicIndexOutOfBounds(
    sema: *Sema,
    parent_block: *Block,
    index: Air.Inst.Ref,
    len: Air.Inst.Ref,
    cmp_op: Air.Inst.Tag,
) !void {
    assert(!parent_block.is_comptime);
    const ok = try parent_block.addBinOp(cmp_op, index, len);
    if (!sema.mod.comp.formatted_panics) {
        return sema.addSafetyCheck(parent_block, ok, .index_out_of_bounds);
    }
    try sema.safetyCheckFormatted(parent_block, ok, "panicOutOfBounds", &.{ index, len });
}

fn panicStartLargerThanEnd(
    sema: *Sema,
    parent_block: *Block,
    start: Air.Inst.Ref,
    end: Air.Inst.Ref,
) !void {
    assert(!parent_block.is_comptime);
    const ok = try parent_block.addBinOp(.cmp_lte, start, end);
    if (!sema.mod.comp.formatted_panics) {
        return sema.addSafetyCheck(parent_block, ok, .start_index_greater_than_end);
    }
    try sema.safetyCheckFormatted(parent_block, ok, "panicStartGreaterThanEnd", &.{ start, end });
}

fn panicInactiveUnionField(
    sema: *Sema,
    parent_block: *Block,
    active_tag: Air.Inst.Ref,
    wanted_tag: Air.Inst.Ref,
) !void {
    assert(!parent_block.is_comptime);
    const ok = try parent_block.addBinOp(.cmp_eq, active_tag, wanted_tag);
    if (!sema.mod.comp.formatted_panics) {
        return sema.addSafetyCheck(parent_block, ok, .inactive_union_field);
    }
    try sema.safetyCheckFormatted(parent_block, ok, "panicInactiveUnionField", &.{ active_tag, wanted_tag });
}

fn panicSentinelMismatch(
    sema: *Sema,
    parent_block: *Block,
    maybe_sentinel: ?Value,
    sentinel_ty: Type,
    ptr: Air.Inst.Ref,
    sentinel_index: Air.Inst.Ref,
) !void {
    assert(!parent_block.is_comptime);
    const expected_sentinel_val = maybe_sentinel orelse return;
    const expected_sentinel = try sema.addConstant(sentinel_ty, expected_sentinel_val);

    const ptr_ty = sema.typeOf(ptr);
    const actual_sentinel = if (ptr_ty.isSlice())
        try parent_block.addBinOp(.slice_elem_val, ptr, sentinel_index)
    else blk: {
        const elem_ptr_ty = try sema.elemPtrType(ptr_ty, null);
        const sentinel_ptr = try parent_block.addPtrElemPtr(ptr, sentinel_index, elem_ptr_ty);
        break :blk try parent_block.addTyOp(.load, sentinel_ty, sentinel_ptr);
    };

    const ok = if (sentinel_ty.zigTypeTag() == .Vector) ok: {
        const eql =
            try parent_block.addCmpVector(expected_sentinel, actual_sentinel, .eq);
        break :ok try parent_block.addInst(.{
            .tag = .reduce,
            .data = .{ .reduce = .{
                .operand = eql,
                .operation = .And,
            } },
        });
    } else if (sentinel_ty.isSelfComparable(true))
        try parent_block.addBinOp(.cmp_eq, expected_sentinel, actual_sentinel)
    else {
        const panic_fn = try sema.getBuiltin("checkNonScalarSentinel");
        const args: [2]Air.Inst.Ref = .{ expected_sentinel, actual_sentinel };
        _ = try sema.analyzeCall(parent_block, panic_fn, sema.src, sema.src, .auto, false, &args, null);
        return;
    };

    if (!sema.mod.comp.formatted_panics) {
        return sema.addSafetyCheck(parent_block, ok, .sentinel_mismatch);
    }
    try sema.safetyCheckFormatted(parent_block, ok, "panicSentinelMismatch", &.{ expected_sentinel, actual_sentinel });
}

fn safetyCheckFormatted(
    sema: *Sema,
    parent_block: *Block,
    ok: Air.Inst.Ref,
    func: []const u8,
    args: []const Air.Inst.Ref,
) CompileError!void {
    assert(sema.mod.comp.formatted_panics);
    const gpa = sema.gpa;

    var fail_block: Block = .{
        .parent = parent_block,
        .sema = sema,
        .src_decl = parent_block.src_decl,
        .namespace = parent_block.namespace,
        .wip_capture_scope = parent_block.wip_capture_scope,
        .instructions = .{},
        .inlining = parent_block.inlining,
        .is_comptime = false,
    };

    defer fail_block.instructions.deinit(gpa);

    if (!sema.mod.backendSupportsFeature(.safety_check_formatted)) {
        _ = try fail_block.addNoOp(.breakpoint);
        _ = try fail_block.addNoOp(.unreach);
    } else {
        const panic_fn = try sema.getBuiltin(func);
        _ = try sema.analyzeCall(&fail_block, panic_fn, sema.src, sema.src, .auto, false, args, null);
    }
    try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
}

fn safetyPanic(
    sema: *Sema,
    block: *Block,
    panic_id: PanicId,
) CompileError!void {
    const panic_messages_ty = try sema.getBuiltinType("panic_messages");
    const msg_decl_index = (try sema.namespaceLookup(
        block,
        sema.src,
        panic_messages_ty.getNamespace().?,
        @tagName(panic_id),
    )).?;

    const msg_inst = try sema.analyzeDeclVal(block, sema.src, msg_decl_index);
    try sema.panicWithMsg(block, sema.src, msg_inst);
}

fn emitBackwardBranch(sema: *Sema, block: *Block, src: LazySrcLoc) !void {
    sema.branch_count += 1;
    if (sema.branch_count > sema.branch_quota) {
        const msg = try sema.errMsg(
            block,
            src,
            "evaluation exceeded {d} backwards branches",
            .{sema.branch_quota},
        );
        try sema.errNote(
            block,
            src,
            msg,
            "use @setEvalBranchQuota() to raise the branch limit from {d}",
            .{sema.branch_quota},
        );
        return sema.failWithOwnedErrorMsg(msg);
    }
}

fn fieldVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    object: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    // When editing this function, note that there is corresponding logic to be edited
    // in `fieldPtr`. This function takes a value and returns a value.

    const arena = sema.arena;
    const object_src = src; // TODO better source location
    const object_ty = sema.typeOf(object);

    // Zig allows dereferencing a single pointer during field lookup. Note that
    // we don't actually need to generate the dereference some field lookups, like the
    // length of arrays and other comptime operations.
    const is_pointer_to = object_ty.isSinglePointer();

    const inner_ty = if (is_pointer_to)
        object_ty.childType()
    else
        object_ty;

    switch (inner_ty.zigTypeTag()) {
        .Array => {
            if (mem.eql(u8, field_name, "len")) {
                return sema.addConstant(
                    Type.usize,
                    try Value.Tag.int_u64.create(arena, inner_ty.arrayLen()),
                );
            } else {
                return sema.fail(
                    block,
                    field_name_src,
                    "no member named '{s}' in '{}'",
                    .{ field_name, object_ty.fmt(sema.mod) },
                );
            }
        },
        .Pointer => {
            const ptr_info = inner_ty.ptrInfo().data;
            if (ptr_info.size == .Slice) {
                if (mem.eql(u8, field_name, "ptr")) {
                    const slice = if (is_pointer_to)
                        try sema.analyzeLoad(block, src, object, object_src)
                    else
                        object;
                    return sema.analyzeSlicePtr(block, object_src, slice, inner_ty);
                } else if (mem.eql(u8, field_name, "len")) {
                    const slice = if (is_pointer_to)
                        try sema.analyzeLoad(block, src, object, object_src)
                    else
                        object;
                    return sema.analyzeSliceLen(block, src, slice);
                } else {
                    return sema.fail(
                        block,
                        field_name_src,
                        "no member named '{s}' in '{}'",
                        .{ field_name, object_ty.fmt(sema.mod) },
                    );
                }
            } else if (ptr_info.pointee_type.zigTypeTag() == .Array) {
                if (mem.eql(u8, field_name, "len")) {
                    return sema.addConstant(
                        Type.usize,
                        try Value.Tag.int_u64.create(arena, ptr_info.pointee_type.arrayLen()),
                    );
                } else {
                    return sema.fail(
                        block,
                        field_name_src,
                        "no member named '{s}' in '{}'",
                        .{ field_name, ptr_info.pointee_type.fmt(sema.mod) },
                    );
                }
            }
        },
        .Type => {
            const dereffed_type = if (is_pointer_to)
                try sema.analyzeLoad(block, src, object, object_src)
            else
                object;

            const val = (try sema.resolveDefinedValue(block, object_src, dereffed_type)).?;
            var to_type_buffer: Value.ToTypeBuffer = undefined;
            const child_type = val.toType(&to_type_buffer);

            switch (try child_type.zigTypeTagOrPoison()) {
                .ErrorSet => {
                    const name: []const u8 = if (child_type.castTag(.error_set)) |payload| blk: {
                        if (payload.data.names.getEntry(field_name)) |entry| {
                            break :blk entry.key_ptr.*;
                        }
                        const msg = msg: {
                            const msg = try sema.errMsg(block, src, "no error named '{s}' in '{}'", .{
                                field_name, child_type.fmt(sema.mod),
                            });
                            errdefer msg.destroy(sema.gpa);
                            try sema.addDeclaredHereNote(msg, child_type);
                            break :msg msg;
                        };
                        return sema.failWithOwnedErrorMsg(msg);
                    } else (try sema.mod.getErrorValue(field_name)).key;

                    return sema.addConstant(
                        if (!child_type.isAnyError())
                            try child_type.copy(arena)
                        else
                            try Type.Tag.error_set_single.create(arena, name),
                        try Value.Tag.@"error".create(arena, .{ .name = name }),
                    );
                },
                .Union => {
                    if (child_type.getNamespace()) |namespace| {
                        if (try sema.namespaceLookupVal(block, src, namespace, field_name)) |inst| {
                            return inst;
                        }
                    }
                    const union_ty = try sema.resolveTypeFields(child_type);
                    if (union_ty.unionTagType()) |enum_ty| {
                        if (enum_ty.enumFieldIndex(field_name)) |field_index_usize| {
                            const field_index = @intCast(u32, field_index_usize);
                            return sema.addConstant(
                                enum_ty,
                                try Value.Tag.enum_field_index.create(sema.arena, field_index),
                            );
                        }
                    }
                    return sema.failWithBadMemberAccess(block, union_ty, field_name_src, field_name);
                },
                .Enum => {
                    if (child_type.getNamespace()) |namespace| {
                        if (try sema.namespaceLookupVal(block, src, namespace, field_name)) |inst| {
                            return inst;
                        }
                    }
                    const field_index_usize = child_type.enumFieldIndex(field_name) orelse
                        return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
                    const field_index = @intCast(u32, field_index_usize);
                    const enum_val = try Value.Tag.enum_field_index.create(arena, field_index);
                    return sema.addConstant(try child_type.copy(arena), enum_val);
                },
                .Struct, .Opaque => {
                    if (child_type.getNamespace()) |namespace| {
                        if (try sema.namespaceLookupVal(block, src, namespace, field_name)) |inst| {
                            return inst;
                        }
                    }
                    return sema.failWithBadMemberAccess(block, child_type, src, field_name);
                },
                else => {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "type '{}' has no members", .{child_type.fmt(sema.mod)});
                        errdefer msg.destroy(sema.gpa);
                        if (child_type.isSlice()) try sema.errNote(block, src, msg, "slice values have 'len' and 'ptr' members", .{});
                        if (child_type.zigTypeTag() == .Array) try sema.errNote(block, src, msg, "array values have 'len' member", .{});
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                },
            }
        },
        .Struct => if (is_pointer_to) {
            // Avoid loading the entire struct by fetching a pointer and loading that
            const field_ptr = try sema.structFieldPtr(block, src, object, field_name, field_name_src, inner_ty, false);
            return sema.analyzeLoad(block, src, field_ptr, object_src);
        } else {
            return sema.structFieldVal(block, src, object, field_name, field_name_src, inner_ty);
        },
        .Union => if (is_pointer_to) {
            // Avoid loading the entire union by fetching a pointer and loading that
            const field_ptr = try sema.unionFieldPtr(block, src, object, field_name, field_name_src, inner_ty, false);
            return sema.analyzeLoad(block, src, field_ptr, object_src);
        } else {
            return sema.unionFieldVal(block, src, object, field_name, field_name_src, inner_ty);
        },
        else => {},
    }
    return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
}

fn fieldPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    object_ptr: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
    initializing: bool,
) CompileError!Air.Inst.Ref {
    // When editing this function, note that there is corresponding logic to be edited
    // in `fieldVal`. This function takes a pointer and returns a pointer.

    const object_ptr_src = src; // TODO better source location
    const object_ptr_ty = sema.typeOf(object_ptr);
    const object_ty = switch (object_ptr_ty.zigTypeTag()) {
        .Pointer => object_ptr_ty.elemType(),
        else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(sema.mod)}),
    };

    // Zig allows dereferencing a single pointer during field lookup. Note that
    // we don't actually need to generate the dereference some field lookups, like the
    // length of arrays and other comptime operations.
    const is_pointer_to = object_ty.isSinglePointer();

    const inner_ty = if (is_pointer_to)
        object_ty.childType()
    else
        object_ty;

    switch (inner_ty.zigTypeTag()) {
        .Array => {
            if (mem.eql(u8, field_name, "len")) {
                var anon_decl = try block.startAnonDecl();
                defer anon_decl.deinit();
                return sema.analyzeDeclRef(try anon_decl.finish(
                    Type.usize,
                    try Value.Tag.int_u64.create(anon_decl.arena(), inner_ty.arrayLen()),
                    0, // default alignment
                ));
            } else {
                return sema.fail(
                    block,
                    field_name_src,
                    "no member named '{s}' in '{}'",
                    .{ field_name, object_ty.fmt(sema.mod) },
                );
            }
        },
        .Pointer => if (inner_ty.isSlice()) {
            const inner_ptr = if (is_pointer_to)
                try sema.analyzeLoad(block, src, object_ptr, object_ptr_src)
            else
                object_ptr;

            const attr_ptr_ty = if (is_pointer_to) object_ty else object_ptr_ty;

            if (mem.eql(u8, field_name, "ptr")) {
                const buf = try sema.arena.create(Type.SlicePtrFieldTypeBuffer);
                const slice_ptr_ty = inner_ty.slicePtrFieldType(buf);

                const result_ty = try Type.ptr(sema.arena, sema.mod, .{
                    .pointee_type = slice_ptr_ty,
                    .mutable = attr_ptr_ty.ptrIsMutable(),
                    .@"volatile" = attr_ptr_ty.isVolatilePtr(),
                    .@"addrspace" = attr_ptr_ty.ptrAddressSpace(),
                });

                if (try sema.resolveDefinedValue(block, object_ptr_src, inner_ptr)) |val| {
                    return sema.addConstant(
                        result_ty,
                        try Value.Tag.field_ptr.create(sema.arena, .{
                            .container_ptr = val,
                            .container_ty = inner_ty,
                            .field_index = Value.Payload.Slice.ptr_index,
                        }),
                    );
                }
                try sema.requireRuntimeBlock(block, src, null);

                return block.addTyOp(.ptr_slice_ptr_ptr, result_ty, inner_ptr);
            } else if (mem.eql(u8, field_name, "len")) {
                const result_ty = try Type.ptr(sema.arena, sema.mod, .{
                    .pointee_type = Type.usize,
                    .mutable = attr_ptr_ty.ptrIsMutable(),
                    .@"volatile" = attr_ptr_ty.isVolatilePtr(),
                    .@"addrspace" = attr_ptr_ty.ptrAddressSpace(),
                });

                if (try sema.resolveDefinedValue(block, object_ptr_src, inner_ptr)) |val| {
                    return sema.addConstant(
                        result_ty,
                        try Value.Tag.field_ptr.create(sema.arena, .{
                            .container_ptr = val,
                            .container_ty = inner_ty,
                            .field_index = Value.Payload.Slice.len_index,
                        }),
                    );
                }
                try sema.requireRuntimeBlock(block, src, null);

                return block.addTyOp(.ptr_slice_len_ptr, result_ty, inner_ptr);
            } else {
                return sema.fail(
                    block,
                    field_name_src,
                    "no member named '{s}' in '{}'",
                    .{ field_name, object_ty.fmt(sema.mod) },
                );
            }
        },
        .Type => {
            _ = try sema.resolveConstValue(block, .unneeded, object_ptr, "");
            const result = try sema.analyzeLoad(block, src, object_ptr, object_ptr_src);
            const inner = if (is_pointer_to)
                try sema.analyzeLoad(block, src, result, object_ptr_src)
            else
                result;

            const val = (sema.resolveDefinedValue(block, src, inner) catch unreachable).?;
            var to_type_buffer: Value.ToTypeBuffer = undefined;
            const child_type = val.toType(&to_type_buffer);

            switch (child_type.zigTypeTag()) {
                .ErrorSet => {
                    // TODO resolve inferred error sets
                    const name: []const u8 = if (child_type.castTag(.error_set)) |payload| blk: {
                        if (payload.data.names.getEntry(field_name)) |entry| {
                            break :blk entry.key_ptr.*;
                        }
                        return sema.fail(block, src, "no error named '{s}' in '{}'", .{
                            field_name, child_type.fmt(sema.mod),
                        });
                    } else (try sema.mod.getErrorValue(field_name)).key;

                    var anon_decl = try block.startAnonDecl();
                    defer anon_decl.deinit();
                    return sema.analyzeDeclRef(try anon_decl.finish(
                        if (!child_type.isAnyError())
                            try child_type.copy(anon_decl.arena())
                        else
                            try Type.Tag.error_set_single.create(anon_decl.arena(), name),
                        try Value.Tag.@"error".create(anon_decl.arena(), .{ .name = name }),
                        0, // default alignment
                    ));
                },
                .Union => {
                    if (child_type.getNamespace()) |namespace| {
                        if (try sema.namespaceLookupRef(block, src, namespace, field_name)) |inst| {
                            return inst;
                        }
                    }
                    const union_ty = try sema.resolveTypeFields(child_type);
                    if (union_ty.unionTagType()) |enum_ty| {
                        if (enum_ty.enumFieldIndex(field_name)) |field_index| {
                            const field_index_u32 = @intCast(u32, field_index);
                            var anon_decl = try block.startAnonDecl();
                            defer anon_decl.deinit();
                            return sema.analyzeDeclRef(try anon_decl.finish(
                                try enum_ty.copy(anon_decl.arena()),
                                try Value.Tag.enum_field_index.create(anon_decl.arena(), field_index_u32),
                                0, // default alignment
                            ));
                        }
                    }
                    return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
                },
                .Enum => {
                    if (child_type.getNamespace()) |namespace| {
                        if (try sema.namespaceLookupRef(block, src, namespace, field_name)) |inst| {
                            return inst;
                        }
                    }
                    const field_index = child_type.enumFieldIndex(field_name) orelse {
                        return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
                    };
                    const field_index_u32 = @intCast(u32, field_index);
                    var anon_decl = try block.startAnonDecl();
                    defer anon_decl.deinit();
                    return sema.analyzeDeclRef(try anon_decl.finish(
                        try child_type.copy(anon_decl.arena()),
                        try Value.Tag.enum_field_index.create(anon_decl.arena(), field_index_u32),
                        0, // default alignment
                    ));
                },
                .Struct, .Opaque => {
                    if (child_type.getNamespace()) |namespace| {
                        if (try sema.namespaceLookupRef(block, src, namespace, field_name)) |inst| {
                            return inst;
                        }
                    }
                    return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
                },
                else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(sema.mod)}),
            }
        },
        .Struct => {
            const inner_ptr = if (is_pointer_to)
                try sema.analyzeLoad(block, src, object_ptr, object_ptr_src)
            else
                object_ptr;
            return sema.structFieldPtr(block, src, inner_ptr, field_name, field_name_src, inner_ty, initializing);
        },
        .Union => {
            const inner_ptr = if (is_pointer_to)
                try sema.analyzeLoad(block, src, object_ptr, object_ptr_src)
            else
                object_ptr;
            return sema.unionFieldPtr(block, src, inner_ptr, field_name, field_name_src, inner_ty, initializing);
        },
        else => {},
    }
    return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
}

fn fieldCallBind(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    raw_ptr: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    // When editing this function, note that there is corresponding logic to be edited
    // in `fieldVal`. This function takes a pointer and returns a pointer.

    const raw_ptr_src = src; // TODO better source location
    const raw_ptr_ty = sema.typeOf(raw_ptr);
    const inner_ty = if (raw_ptr_ty.zigTypeTag() == .Pointer and (raw_ptr_ty.ptrSize() == .One or raw_ptr_ty.ptrSize() == .C))
        raw_ptr_ty.childType()
    else
        return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(sema.mod)});

    // Optionally dereference a second pointer to get the concrete type.
    const is_double_ptr = inner_ty.zigTypeTag() == .Pointer and inner_ty.ptrSize() == .One;
    const concrete_ty = if (is_double_ptr) inner_ty.childType() else inner_ty;
    const ptr_ty = if (is_double_ptr) inner_ty else raw_ptr_ty;
    const object_ptr = if (is_double_ptr)
        try sema.analyzeLoad(block, src, raw_ptr, src)
    else
        raw_ptr;

    const arena = sema.arena;
    find_field: {
        switch (concrete_ty.zigTypeTag()) {
            .Struct => {
                const struct_ty = try sema.resolveTypeFields(concrete_ty);
                if (struct_ty.castTag(.@"struct")) |struct_obj| {
                    const field_index_usize = struct_obj.data.fields.getIndex(field_name) orelse
                        break :find_field;
                    const field_index = @intCast(u32, field_index_usize);
                    const field = struct_obj.data.fields.values()[field_index];

                    return sema.finishFieldCallBind(block, src, ptr_ty, field.ty, field_index, object_ptr);
                } else if (struct_ty.isTuple()) {
                    if (mem.eql(u8, field_name, "len")) {
                        return sema.addIntUnsigned(Type.usize, struct_ty.structFieldCount());
                    }
                    if (std.fmt.parseUnsigned(u32, field_name, 10)) |field_index| {
                        if (field_index >= struct_ty.structFieldCount()) break :find_field;
                        return sema.finishFieldCallBind(block, src, ptr_ty, struct_ty.structFieldType(field_index), field_index, object_ptr);
                    } else |_| {}
                } else {
                    const max = struct_ty.structFieldCount();
                    var i: u32 = 0;
                    while (i < max) : (i += 1) {
                        if (mem.eql(u8, struct_ty.structFieldName(i), field_name)) {
                            return sema.finishFieldCallBind(block, src, ptr_ty, struct_ty.structFieldType(i), i, object_ptr);
                        }
                    }
                }
            },
            .Union => {
                const union_ty = try sema.resolveTypeFields(concrete_ty);
                const fields = union_ty.unionFields();
                const field_index_usize = fields.getIndex(field_name) orelse break :find_field;
                const field_index = @intCast(u32, field_index_usize);
                const field = fields.values()[field_index];

                return sema.finishFieldCallBind(block, src, ptr_ty, field.ty, field_index, object_ptr);
            },
            .Type => {
                const namespace = try sema.analyzeLoad(block, src, object_ptr, src);
                return sema.fieldVal(block, src, namespace, field_name, field_name_src);
            },
            else => {},
        }
    }

    // If we get here, we need to look for a decl in the struct type instead.
    const found_decl = switch (concrete_ty.zigTypeTag()) {
        .Struct, .Opaque, .Union, .Enum => found_decl: {
            if (concrete_ty.getNamespace()) |namespace| {
                if (try sema.namespaceLookup(block, src, namespace, field_name)) |decl_idx| {
                    try sema.addReferencedBy(block, src, decl_idx);
                    const inst = try sema.analyzeDeclRef(decl_idx);

                    const decl_val = try sema.analyzeLoad(block, src, inst, src);
                    const decl_type = sema.typeOf(decl_val);
                    if (decl_type.zigTypeTag() == .Fn and
                        decl_type.fnParamLen() >= 1)
                    {
                        const first_param_type = decl_type.fnParamType(0);
                        const first_param_tag = first_param_type.tag();
                        var opt_buf: Type.Payload.ElemType = undefined;
                        // zig fmt: off
                        if (first_param_tag == .var_args_param or
                            first_param_tag == .generic_poison or (
                                first_param_type.zigTypeTag() == .Pointer and
                                (first_param_type.ptrSize() == .One or
                                first_param_type.ptrSize() == .C) and
                                first_param_type.childType().eql(concrete_ty, sema.mod)))
                        {
                        // zig fmt: on
                            // TODO: bound fn calls on rvalues should probably
                            // generate a by-value argument somehow.
                            const ty = Type.Tag.bound_fn.init();
                            const value = try Value.Tag.bound_fn.create(arena, .{
                                .func_inst = decl_val,
                                .arg0_inst = object_ptr,
                            });
                            return sema.addConstant(ty, value);
                        } else if (first_param_type.eql(concrete_ty, sema.mod)) {
                            const deref = try sema.analyzeLoad(block, src, object_ptr, src);
                            const ty = Type.Tag.bound_fn.init();
                            const value = try Value.Tag.bound_fn.create(arena, .{
                                .func_inst = decl_val,
                                .arg0_inst = deref,
                            });
                            return sema.addConstant(ty, value);
                        } else if (first_param_tag != .generic_poison and first_param_type.zigTypeTag() == .Optional and
                            first_param_type.optionalChild(&opt_buf).eql(concrete_ty, sema.mod))
                        {
                            const deref = try sema.analyzeLoad(block, src, object_ptr, src);
                            const ty = Type.Tag.bound_fn.init();
                            const value = try Value.Tag.bound_fn.create(arena, .{
                                .func_inst = decl_val,
                                .arg0_inst = deref,
                            });
                            return sema.addConstant(ty, value);
                        } else if (first_param_tag != .generic_poison and first_param_type.zigTypeTag() == .ErrorUnion and
                            first_param_type.errorUnionPayload().eql(concrete_ty, sema.mod))
                        {
                            const deref = try sema.analyzeLoad(block, src, object_ptr, src);
                            const ty = Type.Tag.bound_fn.init();
                            const value = try Value.Tag.bound_fn.create(arena, .{
                                .func_inst = decl_val,
                                .arg0_inst = deref,
                            });
                            return sema.addConstant(ty, value);
                        }
                    }
                    break :found_decl decl_idx;
                }
            }
            break :found_decl null;
        },
        else => null,
    };

    const msg = msg: {
        const msg = try sema.errMsg(block, src, "no field or member function named '{s}' in '{}'", .{ field_name, concrete_ty.fmt(sema.mod) });
        errdefer msg.destroy(sema.gpa);
        try sema.addDeclaredHereNote(msg, concrete_ty);
        if (found_decl) |decl_idx| {
            const decl = sema.mod.declPtr(decl_idx);
            try sema.mod.errNoteNonLazy(decl.srcLoc(), msg, "'{s}' is not a member function", .{field_name});
        }
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn finishFieldCallBind(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr_ty: Type,
    field_ty: Type,
    field_index: u32,
    object_ptr: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const arena = sema.arena;
    const ptr_field_ty = try Type.ptr(arena, sema.mod, .{
        .pointee_type = field_ty,
        .mutable = ptr_ty.ptrIsMutable(),
        .@"addrspace" = ptr_ty.ptrAddressSpace(),
    });

    const container_ty = ptr_ty.childType();
    if (container_ty.zigTypeTag() == .Struct) {
        if (container_ty.structFieldValueComptime(field_index)) |default_val| {
            return sema.addConstant(field_ty, default_val);
        }
    }

    if (try sema.resolveDefinedValue(block, src, object_ptr)) |struct_ptr_val| {
        const pointer = try sema.addConstant(
            ptr_field_ty,
            try Value.Tag.field_ptr.create(arena, .{
                .container_ptr = struct_ptr_val,
                .container_ty = container_ty,
                .field_index = field_index,
            }),
        );
        return sema.analyzeLoad(block, src, pointer, src);
    }

    try sema.requireRuntimeBlock(block, src, null);
    const ptr_inst = try block.addStructFieldPtr(object_ptr, field_index, ptr_field_ty);
    return sema.analyzeLoad(block, src, ptr_inst, src);
}

fn namespaceLookup(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    namespace: *Namespace,
    decl_name: []const u8,
) CompileError!?Decl.Index {
    const gpa = sema.gpa;
    if (try sema.lookupInNamespace(block, src, namespace, decl_name, true)) |decl_index| {
        const decl = sema.mod.declPtr(decl_index);
        if (!decl.is_pub and decl.getFileScope() != block.getFileScope()) {
            const msg = msg: {
                const msg = try sema.errMsg(block, src, "'{s}' is not marked 'pub'", .{
                    decl_name,
                });
                errdefer msg.destroy(gpa);
                try sema.mod.errNoteNonLazy(decl.srcLoc(), msg, "declared here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        return decl_index;
    }
    return null;
}

fn namespaceLookupRef(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    namespace: *Namespace,
    decl_name: []const u8,
) CompileError!?Air.Inst.Ref {
    const decl = (try sema.namespaceLookup(block, src, namespace, decl_name)) orelse return null;
    try sema.addReferencedBy(block, src, decl);
    return try sema.analyzeDeclRef(decl);
}

fn namespaceLookupVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    namespace: *Namespace,
    decl_name: []const u8,
) CompileError!?Air.Inst.Ref {
    const decl = (try sema.namespaceLookup(block, src, namespace, decl_name)) orelse return null;
    return try sema.analyzeDeclVal(block, src, decl);
}

fn structFieldPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    struct_ptr: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
    unresolved_struct_ty: Type,
    initializing: bool,
) CompileError!Air.Inst.Ref {
    assert(unresolved_struct_ty.zigTypeTag() == .Struct);

    const struct_ty = try sema.resolveTypeFields(unresolved_struct_ty);
    try sema.resolveStructLayout(struct_ty);

    if (struct_ty.isTuple()) {
        if (mem.eql(u8, field_name, "len")) {
            const len_inst = try sema.addIntUnsigned(Type.usize, struct_ty.structFieldCount());
            return sema.analyzeRef(block, src, len_inst);
        }
        const field_index = try sema.tupleFieldIndex(block, struct_ty, field_name, field_name_src);
        return sema.tupleFieldPtr(block, src, struct_ptr, field_name_src, field_index, initializing);
    } else if (struct_ty.isAnonStruct()) {
        const field_index = try sema.anonStructFieldIndex(block, struct_ty, field_name, field_name_src);
        return sema.tupleFieldPtr(block, src, struct_ptr, field_name_src, field_index, initializing);
    }

    const struct_obj = struct_ty.castTag(.@"struct").?.data;

    const field_index_big = struct_obj.fields.getIndex(field_name) orelse
        return sema.failWithBadStructFieldAccess(block, struct_obj, field_name_src, field_name);
    const field_index = @intCast(u32, field_index_big);

    return sema.structFieldPtrByIndex(block, src, struct_ptr, field_index, field_name_src, struct_ty, initializing);
}

fn structFieldPtrByIndex(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    struct_ptr: Air.Inst.Ref,
    field_index: u32,
    field_src: LazySrcLoc,
    struct_ty: Type,
    initializing: bool,
) CompileError!Air.Inst.Ref {
    if (struct_ty.isAnonStruct()) {
        return sema.tupleFieldPtr(block, src, struct_ptr, field_src, field_index, initializing);
    }

    const struct_obj = struct_ty.castTag(.@"struct").?.data;
    const field = struct_obj.fields.values()[field_index];
    const struct_ptr_ty = sema.typeOf(struct_ptr);
    const struct_ptr_ty_info = struct_ptr_ty.ptrInfo().data;

    var ptr_ty_data: Type.Payload.Pointer.Data = .{
        .pointee_type = field.ty,
        .mutable = struct_ptr_ty_info.mutable,
        .@"volatile" = struct_ptr_ty_info.@"volatile",
        .@"addrspace" = struct_ptr_ty_info.@"addrspace",
    };

    const target = sema.mod.getTarget();

    if (struct_obj.layout == .Packed) {
        comptime assert(Type.packed_struct_layout_version == 2);

        var running_bits: u16 = 0;
        for (struct_obj.fields.values(), 0..) |f, i| {
            if (!(try sema.typeHasRuntimeBits(f.ty))) continue;

            if (i == field_index) {
                ptr_ty_data.bit_offset = running_bits;
            }
            running_bits += @intCast(u16, f.ty.bitSize(target));
        }
        ptr_ty_data.host_size = (running_bits + 7) / 8;

        // If this is a packed struct embedded in another one, we need to offset
        // the bits against each other.
        if (struct_ptr_ty_info.host_size != 0) {
            ptr_ty_data.host_size = struct_ptr_ty_info.host_size;
            ptr_ty_data.bit_offset += struct_ptr_ty_info.bit_offset;
        }

        const parent_align = if (struct_ptr_ty_info.@"align" != 0)
            struct_ptr_ty_info.@"align"
        else
            struct_ptr_ty_info.pointee_type.abiAlignment(target);
        ptr_ty_data.@"align" = parent_align;

        // If the field happens to be byte-aligned, simplify the pointer type.
        // The pointee type bit size must match its ABI byte size so that loads and stores
        // do not interfere with the surrounding packed bits.
        // We do not attempt this with big-endian targets yet because of nested
        // structs and floats. I need to double-check the desired behavior for big endian
        // targets before adding the necessary complications to this code. This will not
        // cause miscompilations; it only means the field pointer uses bit masking when it
        // might not be strictly necessary.
        if (parent_align != 0 and ptr_ty_data.bit_offset % 8 == 0 and
            target.cpu.arch.endian() == .Little)
        {
            const elem_size_bytes = ptr_ty_data.pointee_type.abiSize(target);
            const elem_size_bits = ptr_ty_data.pointee_type.bitSize(target);
            if (elem_size_bytes * 8 == elem_size_bits) {
                const byte_offset = ptr_ty_data.bit_offset / 8;
                const new_align = @as(u32, 1) << @intCast(u5, @ctz(byte_offset | parent_align));
                ptr_ty_data.bit_offset = 0;
                ptr_ty_data.host_size = 0;
                ptr_ty_data.@"align" = new_align;
            }
        }
    } else {
        ptr_ty_data.@"align" = field.abi_align;
    }

    const ptr_field_ty = try Type.ptr(sema.arena, sema.mod, ptr_ty_data);

    if (field.is_comptime) {
        const val = try Value.Tag.comptime_field_ptr.create(sema.arena, .{
            .field_ty = try field.ty.copy(sema.arena),
            .field_val = try field.default_val.copy(sema.arena),
        });
        return sema.addConstant(ptr_field_ty, val);
    }

    if (try sema.resolveDefinedValue(block, src, struct_ptr)) |struct_ptr_val| {
        return sema.addConstant(
            ptr_field_ty,
            try Value.Tag.field_ptr.create(sema.arena, .{
                .container_ptr = struct_ptr_val,
                .container_ty = struct_ptr_ty.childType(),
                .field_index = field_index,
            }),
        );
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addStructFieldPtr(struct_ptr, field_index, ptr_field_ty);
}

fn structFieldVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    struct_byval: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
    unresolved_struct_ty: Type,
) CompileError!Air.Inst.Ref {
    assert(unresolved_struct_ty.zigTypeTag() == .Struct);

    const struct_ty = try sema.resolveTypeFields(unresolved_struct_ty);
    switch (struct_ty.tag()) {
        .tuple, .empty_struct_literal => return sema.tupleFieldVal(block, src, struct_byval, field_name, field_name_src, struct_ty),
        .anon_struct => {
            const field_index = try sema.anonStructFieldIndex(block, struct_ty, field_name, field_name_src);
            return sema.tupleFieldValByIndex(block, src, struct_byval, field_index, struct_ty);
        },
        .@"struct" => {
            const struct_obj = struct_ty.castTag(.@"struct").?.data;
            if (struct_obj.is_tuple) return sema.tupleFieldVal(block, src, struct_byval, field_name, field_name_src, struct_ty);

            const field_index_usize = struct_obj.fields.getIndex(field_name) orelse
                return sema.failWithBadStructFieldAccess(block, struct_obj, field_name_src, field_name);
            const field_index = @intCast(u32, field_index_usize);
            const field = struct_obj.fields.values()[field_index];

            if (field.is_comptime) {
                return sema.addConstant(field.ty, field.default_val);
            }

            if (try sema.resolveMaybeUndefVal(struct_byval)) |struct_val| {
                if (struct_val.isUndef()) return sema.addConstUndef(field.ty);
                if ((try sema.typeHasOnePossibleValue(field.ty))) |opv| {
                    return sema.addConstant(field.ty, opv);
                }

                const field_values = struct_val.castTag(.aggregate).?.data;
                return sema.addConstant(field.ty, field_values[field_index]);
            }

            try sema.requireRuntimeBlock(block, src, null);
            return block.addStructFieldVal(struct_byval, field_index, field.ty);
        },
        else => unreachable,
    }
}

fn tupleFieldVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    tuple_byval: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
    tuple_ty: Type,
) CompileError!Air.Inst.Ref {
    if (mem.eql(u8, field_name, "len")) {
        return sema.addIntUnsigned(Type.usize, tuple_ty.structFieldCount());
    }
    const field_index = try sema.tupleFieldIndex(block, tuple_ty, field_name, field_name_src);
    return sema.tupleFieldValByIndex(block, src, tuple_byval, field_index, tuple_ty);
}

/// Asserts that `field_name` is not "len".
fn tupleFieldIndex(
    sema: *Sema,
    block: *Block,
    tuple_ty: Type,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
) CompileError!u32 {
    assert(!std.mem.eql(u8, field_name, "len"));
    if (std.fmt.parseUnsigned(u32, field_name, 10)) |field_index| {
        if (field_index < tuple_ty.structFieldCount()) return field_index;
        return sema.fail(block, field_name_src, "index '{s}' out of bounds of tuple '{}'", .{
            field_name, tuple_ty.fmt(sema.mod),
        });
    } else |_| {}

    return sema.fail(block, field_name_src, "no field named '{s}' in tuple '{}'", .{
        field_name, tuple_ty.fmt(sema.mod),
    });
}

fn tupleFieldValByIndex(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    tuple_byval: Air.Inst.Ref,
    field_index: u32,
    tuple_ty: Type,
) CompileError!Air.Inst.Ref {
    const field_ty = tuple_ty.structFieldType(field_index);

    if (tuple_ty.structFieldValueComptime(field_index)) |default_value| {
        return sema.addConstant(field_ty, default_value);
    }

    if (try sema.resolveMaybeUndefVal(tuple_byval)) |tuple_val| {
        if (tuple_val.isUndef()) return sema.addConstUndef(field_ty);
        if ((try sema.typeHasOnePossibleValue(field_ty))) |opv| {
            return sema.addConstant(field_ty, opv);
        }
        const field_values = tuple_val.castTag(.aggregate).?.data;
        return sema.addConstant(field_ty, field_values[field_index]);
    }

    if (tuple_ty.structFieldValueComptime(field_index)) |default_val| {
        return sema.addConstant(field_ty, default_val);
    }

    try sema.requireRuntimeBlock(block, src, null);
    return block.addStructFieldVal(tuple_byval, field_index, field_ty);
}

fn unionFieldPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    union_ptr: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
    unresolved_union_ty: Type,
    initializing: bool,
) CompileError!Air.Inst.Ref {
    const arena = sema.arena;
    assert(unresolved_union_ty.zigTypeTag() == .Union);

    const union_ptr_ty = sema.typeOf(union_ptr);
    const union_ty = try sema.resolveTypeFields(unresolved_union_ty);
    const union_obj = union_ty.cast(Type.Payload.Union).?.data;
    const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
    const field = union_obj.fields.values()[field_index];
    const ptr_field_ty = try Type.ptr(arena, sema.mod, .{
        .pointee_type = field.ty,
        .mutable = union_ptr_ty.ptrIsMutable(),
        .@"volatile" = union_ptr_ty.isVolatilePtr(),
        .@"addrspace" = union_ptr_ty.ptrAddressSpace(),
    });
    const enum_field_index = @intCast(u32, union_obj.tag_ty.enumFieldIndex(field_name).?);

    if (initializing and field.ty.zigTypeTag() == .NoReturn) {
        const msg = msg: {
            const msg = try sema.errMsg(block, src, "cannot initialize 'noreturn' field of union", .{});
            errdefer msg.destroy(sema.gpa);

            try sema.addFieldErrNote(union_ty, field_index, msg, "field '{s}' declared here", .{field_name});
            try sema.addDeclaredHereNote(msg, union_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| ct: {
        switch (union_obj.layout) {
            .Auto => if (!initializing) {
                const union_val = (try sema.pointerDeref(block, src, union_ptr_val, union_ptr_ty)) orelse
                    break :ct;
                if (union_val.isUndef()) {
                    return sema.failWithUseOfUndef(block, src);
                }
                const tag_and_val = union_val.castTag(.@"union").?.data;
                var field_tag_buf: Value.Payload.U32 = .{
                    .base = .{ .tag = .enum_field_index },
                    .data = enum_field_index,
                };
                const field_tag = Value.initPayload(&field_tag_buf.base);
                const tag_matches = tag_and_val.tag.eql(field_tag, union_obj.tag_ty, sema.mod);
                if (!tag_matches) {
                    const msg = msg: {
                        const active_index = tag_and_val.tag.castTag(.enum_field_index).?.data;
                        const active_field_name = union_obj.tag_ty.enumFieldName(active_index);
                        const msg = try sema.errMsg(block, src, "access of union field '{s}' while field '{s}' is active", .{ field_name, active_field_name });
                        errdefer msg.destroy(sema.gpa);
                        try sema.addDeclaredHereNote(msg, union_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            },
            .Packed, .Extern => {},
        }
        return sema.addConstant(
            ptr_field_ty,
            try Value.Tag.field_ptr.create(arena, .{
                .container_ptr = union_ptr_val,
                .container_ty = union_ty,
                .field_index = field_index,
            }),
        );
    }

    try sema.requireRuntimeBlock(block, src, null);
    if (!initializing and union_obj.layout == .Auto and block.wantSafety() and
        union_ty.unionTagTypeSafety() != null and union_obj.fields.count() > 1)
    {
        const wanted_tag_val = try Value.Tag.enum_field_index.create(sema.arena, enum_field_index);
        const wanted_tag = try sema.addConstant(union_obj.tag_ty, wanted_tag_val);
        // TODO would it be better if get_union_tag supported pointers to unions?
        const union_val = try block.addTyOp(.load, union_ty, union_ptr);
        const active_tag = try block.addTyOp(.get_union_tag, union_obj.tag_ty, union_val);
        try sema.panicInactiveUnionField(block, active_tag, wanted_tag);
    }
    if (field.ty.zigTypeTag() == .NoReturn) {
        _ = try block.addNoOp(.unreach);
        return Air.Inst.Ref.unreachable_value;
    }
    return block.addStructFieldPtr(union_ptr, field_index, ptr_field_ty);
}

fn unionFieldVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    union_byval: Air.Inst.Ref,
    field_name: []const u8,
    field_name_src: LazySrcLoc,
    unresolved_union_ty: Type,
) CompileError!Air.Inst.Ref {
    assert(unresolved_union_ty.zigTypeTag() == .Union);

    const union_ty = try sema.resolveTypeFields(unresolved_union_ty);
    const union_obj = union_ty.cast(Type.Payload.Union).?.data;
    const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
    const field = union_obj.fields.values()[field_index];
    const enum_field_index = @intCast(u32, union_obj.tag_ty.enumFieldIndex(field_name).?);

    if (try sema.resolveMaybeUndefVal(union_byval)) |union_val| {
        if (union_val.isUndef()) return sema.addConstUndef(field.ty);

        const tag_and_val = union_val.castTag(.@"union").?.data;
        var field_tag_buf: Value.Payload.U32 = .{
            .base = .{ .tag = .enum_field_index },
            .data = enum_field_index,
        };
        const field_tag = Value.initPayload(&field_tag_buf.base);
        const tag_matches = tag_and_val.tag.eql(field_tag, union_obj.tag_ty, sema.mod);
        switch (union_obj.layout) {
            .Auto => {
                if (tag_matches) {
                    return sema.addConstant(field.ty, tag_and_val.val);
                } else {
                    const msg = msg: {
                        const active_index = tag_and_val.tag.castTag(.enum_field_index).?.data;
                        const active_field_name = union_obj.tag_ty.enumFieldName(active_index);
                        const msg = try sema.errMsg(block, src, "access of union field '{s}' while field '{s}' is active", .{ field_name, active_field_name });
                        errdefer msg.destroy(sema.gpa);
                        try sema.addDeclaredHereNote(msg, union_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            },
            .Packed, .Extern => {
                if (tag_matches) {
                    return sema.addConstant(field.ty, tag_and_val.val);
                } else {
                    const old_ty = union_ty.unionFieldType(tag_and_val.tag, sema.mod);
                    if (try sema.bitCastVal(block, src, tag_and_val.val, old_ty, field.ty, 0)) |new_val| {
                        return sema.addConstant(field.ty, new_val);
                    }
                }
            },
        }
    }

    try sema.requireRuntimeBlock(block, src, null);
    if (union_obj.layout == .Auto and block.wantSafety() and
        union_ty.unionTagTypeSafety() != null and union_obj.fields.count() > 1)
    {
        const wanted_tag_val = try Value.Tag.enum_field_index.create(sema.arena, enum_field_index);
        const wanted_tag = try sema.addConstant(union_obj.tag_ty, wanted_tag_val);
        const active_tag = try block.addTyOp(.get_union_tag, union_obj.tag_ty, union_byval);
        try sema.panicInactiveUnionField(block, active_tag, wanted_tag);
    }
    if (field.ty.zigTypeTag() == .NoReturn) {
        _ = try block.addNoOp(.unreach);
        return Air.Inst.Ref.unreachable_value;
    }
    return block.addStructFieldVal(union_byval, field_index, field.ty);
}

fn elemPtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    indexable_ptr: Air.Inst.Ref,
    elem_index: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    init: bool,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const indexable_ptr_src = src; // TODO better source location
    const indexable_ptr_ty = sema.typeOf(indexable_ptr);
    const target = sema.mod.getTarget();
    const indexable_ty = switch (indexable_ptr_ty.zigTypeTag()) {
        .Pointer => indexable_ptr_ty.elemType(),
        else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(sema.mod)}),
    };
    switch (indexable_ty.zigTypeTag()) {
        .Array, .Vector => return sema.elemPtrArray(block, src, indexable_ptr_src, indexable_ptr, elem_index_src, elem_index, init, oob_safety),
        .Struct => {
            // Tuple field access.
            const index_val = try sema.resolveConstValue(block, elem_index_src, elem_index, "tuple field access index must be comptime-known");
            const index = @intCast(u32, index_val.toUnsignedInt(target));
            return sema.tupleFieldPtr(block, src, indexable_ptr, elem_index_src, index, init);
        },
        else => {
            const indexable = try sema.analyzeLoad(block, indexable_ptr_src, indexable_ptr, indexable_ptr_src);
            return elemPtrOneLayerOnly(sema, block, src, indexable, elem_index, elem_index_src, init, oob_safety);
        },
    }
}

/// Asserts that the type of indexable is pointer.
fn elemPtrOneLayerOnly(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    indexable: Air.Inst.Ref,
    elem_index: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    init: bool,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const indexable_src = src; // TODO better source location
    const indexable_ty = sema.typeOf(indexable);
    if (!indexable_ty.isIndexable()) {
        return sema.fail(block, src, "element access of non-indexable type '{}'", .{indexable_ty.fmt(sema.mod)});
    }
    const target = sema.mod.getTarget();

    switch (indexable_ty.ptrSize()) {
        .Slice => return sema.elemPtrSlice(block, src, indexable_src, indexable, elem_index_src, elem_index, oob_safety),
        .Many, .C => {
            const maybe_ptr_val = try sema.resolveDefinedValue(block, indexable_src, indexable);
            const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
            const runtime_src = rs: {
                const ptr_val = maybe_ptr_val orelse break :rs indexable_src;
                const index_val = maybe_index_val orelse break :rs elem_index_src;
                const index = @intCast(usize, index_val.toUnsignedInt(target));
                const elem_ptr = try ptr_val.elemPtr(indexable_ty, sema.arena, index, sema.mod);
                const result_ty = try sema.elemPtrType(indexable_ty, index);
                return sema.addConstant(result_ty, elem_ptr);
            };
            const result_ty = try sema.elemPtrType(indexable_ty, null);

            try sema.requireRuntimeBlock(block, src, runtime_src);
            return block.addPtrElemPtr(indexable, elem_index, result_ty);
        },
        .One => {
            assert(indexable_ty.childType().zigTypeTag() == .Array); // Guaranteed by isIndexable
            return sema.elemPtrArray(block, src, indexable_src, indexable, elem_index_src, elem_index, init, oob_safety);
        },
    }
}

fn elemVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    indexable: Air.Inst.Ref,
    elem_index_uncasted: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const indexable_src = src; // TODO better source location
    const indexable_ty = sema.typeOf(indexable);
    const target = sema.mod.getTarget();

    if (!indexable_ty.isIndexable()) {
        return sema.fail(block, src, "element access of non-indexable type '{}'", .{indexable_ty.fmt(sema.mod)});
    }

    // TODO in case of a vector of pointers, we need to detect whether the element
    // index is a scalar or vector instead of unconditionally casting to usize.
    const elem_index = try sema.coerce(block, Type.usize, elem_index_uncasted, elem_index_src);

    switch (indexable_ty.zigTypeTag()) {
        .Pointer => switch (indexable_ty.ptrSize()) {
            .Slice => return sema.elemValSlice(block, src, indexable_src, indexable, elem_index_src, elem_index, oob_safety),
            .Many, .C => {
                const maybe_indexable_val = try sema.resolveDefinedValue(block, indexable_src, indexable);
                const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);

                const runtime_src = rs: {
                    const indexable_val = maybe_indexable_val orelse break :rs indexable_src;
                    const index_val = maybe_index_val orelse break :rs elem_index_src;
                    const index = @intCast(usize, index_val.toUnsignedInt(target));
                    const elem_ptr_val = try indexable_val.elemPtr(indexable_ty, sema.arena, index, sema.mod);
                    if (try sema.pointerDeref(block, indexable_src, elem_ptr_val, indexable_ty)) |elem_val| {
                        return sema.addConstant(indexable_ty.elemType2(), elem_val);
                    }
                    break :rs indexable_src;
                };

                try sema.requireRuntimeBlock(block, src, runtime_src);
                return block.addBinOp(.ptr_elem_val, indexable, elem_index);
            },
            .One => {
                assert(indexable_ty.childType().zigTypeTag() == .Array); // Guaranteed by isIndexable
                const elem_ptr = try sema.elemPtr(block, indexable_src, indexable, elem_index, elem_index_src, false, oob_safety);
                return sema.analyzeLoad(block, indexable_src, elem_ptr, elem_index_src);
            },
        },
        .Array => return sema.elemValArray(block, src, indexable_src, indexable, elem_index_src, elem_index, oob_safety),
        .Vector => {
            // TODO: If the index is a vector, the result should be a vector.
            return sema.elemValArray(block, src, indexable_src, indexable, elem_index_src, elem_index, oob_safety);
        },
        .Struct => {
            // Tuple field access.
            const index_val = try sema.resolveConstValue(block, elem_index_src, elem_index, "tuple field access index must be comptime-known");
            const index = @intCast(u32, index_val.toUnsignedInt(target));
            return sema.tupleField(block, indexable_src, indexable, elem_index_src, index);
        },
        else => unreachable,
    }
}

fn validateRuntimeElemAccess(
    sema: *Sema,
    block: *Block,
    elem_index_src: LazySrcLoc,
    elem_ty: Type,
    parent_ty: Type,
    parent_src: LazySrcLoc,
) CompileError!void {
    const valid_rt = try sema.validateRunTimeType(elem_ty, false);
    if (!valid_rt) {
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                elem_index_src,
                "values of type '{}' must be comptime-known, but index value is runtime-known",
                .{parent_ty.fmt(sema.mod)},
            );
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsComptime(block, elem_index_src, msg, parent_src.toSrcLoc(src_decl), parent_ty);

            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
}

fn tupleFieldPtr(
    sema: *Sema,
    block: *Block,
    tuple_ptr_src: LazySrcLoc,
    tuple_ptr: Air.Inst.Ref,
    field_index_src: LazySrcLoc,
    field_index: u32,
    init: bool,
) CompileError!Air.Inst.Ref {
    const tuple_ptr_ty = sema.typeOf(tuple_ptr);
    const tuple_ty = tuple_ptr_ty.childType();
    _ = try sema.resolveTypeFields(tuple_ty);
    const field_count = tuple_ty.structFieldCount();

    if (field_count == 0) {
        return sema.fail(block, tuple_ptr_src, "indexing into empty tuple is not allowed", .{});
    }

    if (field_index >= field_count) {
        return sema.fail(block, field_index_src, "index {d} outside tuple of length {d}", .{
            field_index, field_count,
        });
    }

    const field_ty = tuple_ty.structFieldType(field_index);
    const ptr_field_ty = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = field_ty,
        .mutable = tuple_ptr_ty.ptrIsMutable(),
        .@"volatile" = tuple_ptr_ty.isVolatilePtr(),
        .@"addrspace" = tuple_ptr_ty.ptrAddressSpace(),
    });

    if (tuple_ty.structFieldValueComptime(field_index)) |default_val| {
        const val = try Value.Tag.comptime_field_ptr.create(sema.arena, .{
            .field_ty = field_ty,
            .field_val = default_val,
        });
        return sema.addConstant(ptr_field_ty, val);
    }

    if (try sema.resolveMaybeUndefVal(tuple_ptr)) |tuple_ptr_val| {
        return sema.addConstant(
            ptr_field_ty,
            try Value.Tag.field_ptr.create(sema.arena, .{
                .container_ptr = tuple_ptr_val,
                .container_ty = tuple_ty,
                .field_index = field_index,
            }),
        );
    }

    if (!init) {
        try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_ptr_src);
    }

    try sema.requireRuntimeBlock(block, tuple_ptr_src, null);
    return block.addStructFieldPtr(tuple_ptr, field_index, ptr_field_ty);
}

fn tupleField(
    sema: *Sema,
    block: *Block,
    tuple_src: LazySrcLoc,
    tuple: Air.Inst.Ref,
    field_index_src: LazySrcLoc,
    field_index: u32,
) CompileError!Air.Inst.Ref {
    const tuple_ty = try sema.resolveTypeFields(sema.typeOf(tuple));
    const field_count = tuple_ty.structFieldCount();

    if (field_count == 0) {
        return sema.fail(block, tuple_src, "indexing into empty tuple is not allowed", .{});
    }

    if (field_index >= field_count) {
        return sema.fail(block, field_index_src, "index {d} outside tuple of length {d}", .{
            field_index, field_count,
        });
    }

    const field_ty = tuple_ty.structFieldType(field_index);

    if (tuple_ty.structFieldValueComptime(field_index)) |default_value| {
        return sema.addConstant(field_ty, default_value); // comptime field
    }

    if (try sema.resolveMaybeUndefVal(tuple)) |tuple_val| {
        if (tuple_val.isUndef()) return sema.addConstUndef(field_ty);
        return sema.addConstant(field_ty, tuple_val.fieldValue(tuple_ty, field_index));
    }

    try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_src);

    try sema.requireRuntimeBlock(block, tuple_src, null);
    return block.addStructFieldVal(tuple, field_index, field_ty);
}

fn elemValArray(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    array_src: LazySrcLoc,
    array: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    elem_index: Air.Inst.Ref,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const array_ty = sema.typeOf(array);
    const array_sent = array_ty.sentinel();
    const array_len = array_ty.arrayLen();
    const array_len_s = array_len + @boolToInt(array_sent != null);
    const elem_ty = array_ty.childType();

    if (array_len_s == 0) {
        return sema.fail(block, array_src, "indexing into empty array is not allowed", .{});
    }

    const maybe_undef_array_val = try sema.resolveMaybeUndefVal(array);
    // index must be defined since it can access out of bounds
    const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
    const target = sema.mod.getTarget();

    if (maybe_index_val) |index_val| {
        const index = @intCast(usize, index_val.toUnsignedInt(target));
        if (array_sent) |s| {
            if (index == array_len) {
                return sema.addConstant(elem_ty, s);
            }
        }
        if (index >= array_len_s) {
            const sentinel_label: []const u8 = if (array_sent != null) " +1 (sentinel)" else "";
            return sema.fail(block, elem_index_src, "index {d} outside array of length {d}{s}", .{ index, array_len, sentinel_label });
        }
    }
    if (maybe_undef_array_val) |array_val| {
        if (array_val.isUndef()) {
            return sema.addConstUndef(elem_ty);
        }
        if (maybe_index_val) |index_val| {
            const index = @intCast(usize, index_val.toUnsignedInt(target));
            const elem_val = try array_val.elemValue(sema.mod, sema.arena, index);
            return sema.addConstant(elem_ty, elem_val);
        }
    }

    try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ty, array_ty, array_src);

    const runtime_src = if (maybe_undef_array_val != null) elem_index_src else array_src;
    try sema.requireRuntimeBlock(block, src, runtime_src);
    if (oob_safety and block.wantSafety()) {
        // Runtime check is only needed if unable to comptime check
        if (maybe_index_val == null) {
            const len_inst = try sema.addIntUnsigned(Type.usize, array_len);
            const cmp_op: Air.Inst.Tag = if (array_sent != null) .cmp_lte else .cmp_lt;
            try sema.panicIndexOutOfBounds(block, elem_index, len_inst, cmp_op);
        }
    }
    return block.addBinOp(.array_elem_val, array, elem_index);
}

fn elemPtrArray(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    array_ptr_src: LazySrcLoc,
    array_ptr: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    elem_index: Air.Inst.Ref,
    init: bool,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const target = sema.mod.getTarget();
    const array_ptr_ty = sema.typeOf(array_ptr);
    const array_ty = array_ptr_ty.childType();
    const array_sent = array_ty.sentinel() != null;
    const array_len = array_ty.arrayLen();
    const array_len_s = array_len + @boolToInt(array_sent);

    if (array_len_s == 0) {
        return sema.fail(block, array_ptr_src, "indexing into empty array is not allowed", .{});
    }

    const maybe_undef_array_ptr_val = try sema.resolveMaybeUndefVal(array_ptr);
    // The index must not be undefined since it can be out of bounds.
    const offset: ?usize = if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| o: {
        const index = try sema.usizeCast(block, elem_index_src, index_val.toUnsignedInt(target));
        if (index >= array_len_s) {
            const sentinel_label: []const u8 = if (array_sent) " +1 (sentinel)" else "";
            return sema.fail(block, elem_index_src, "index {d} outside array of length {d}{s}", .{ index, array_len, sentinel_label });
        }
        break :o index;
    } else null;

    const elem_ptr_ty = try sema.elemPtrType(array_ptr_ty, offset);

    if (maybe_undef_array_ptr_val) |array_ptr_val| {
        if (array_ptr_val.isUndef()) {
            return sema.addConstUndef(elem_ptr_ty);
        }
        if (offset) |index| {
            const elem_ptr = try array_ptr_val.elemPtr(array_ptr_ty, sema.arena, index, sema.mod);
            return sema.addConstant(elem_ptr_ty, elem_ptr);
        }
    }

    if (!init) {
        try sema.validateRuntimeElemAccess(block, elem_index_src, array_ty.elemType2(), array_ty, array_ptr_src);
    }

    const runtime_src = if (maybe_undef_array_ptr_val != null) elem_index_src else array_ptr_src;
    try sema.requireRuntimeBlock(block, src, runtime_src);

    // Runtime check is only needed if unable to comptime check.
    if (oob_safety and block.wantSafety() and offset == null) {
        const len_inst = try sema.addIntUnsigned(Type.usize, array_len);
        const cmp_op: Air.Inst.Tag = if (array_sent) .cmp_lte else .cmp_lt;
        try sema.panicIndexOutOfBounds(block, elem_index, len_inst, cmp_op);
    }

    return block.addPtrElemPtr(array_ptr, elem_index, elem_ptr_ty);
}

fn elemValSlice(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    slice_src: LazySrcLoc,
    slice: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    elem_index: Air.Inst.Ref,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const slice_ty = sema.typeOf(slice);
    const slice_sent = slice_ty.sentinel() != null;
    const elem_ty = slice_ty.elemType2();
    var runtime_src = slice_src;

    // slice must be defined since it can dereferenced as null
    const maybe_slice_val = try sema.resolveDefinedValue(block, slice_src, slice);
    // index must be defined since it can index out of bounds
    const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
    const target = sema.mod.getTarget();

    if (maybe_slice_val) |slice_val| {
        runtime_src = elem_index_src;
        const slice_len = slice_val.sliceLen(sema.mod);
        const slice_len_s = slice_len + @boolToInt(slice_sent);
        if (slice_len_s == 0) {
            return sema.fail(block, slice_src, "indexing into empty slice is not allowed", .{});
        }
        if (maybe_index_val) |index_val| {
            const index = @intCast(usize, index_val.toUnsignedInt(target));
            if (index >= slice_len_s) {
                const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
                return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
            }
            const elem_ptr_val = try slice_val.elemPtr(slice_ty, sema.arena, index, sema.mod);
            if (try sema.pointerDeref(block, slice_src, elem_ptr_val, slice_ty)) |elem_val| {
                return sema.addConstant(elem_ty, elem_val);
            }
            runtime_src = slice_src;
        }
    }

    try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ty, slice_ty, slice_src);

    try sema.requireRuntimeBlock(block, src, runtime_src);
    if (oob_safety and block.wantSafety()) {
        const len_inst = if (maybe_slice_val) |slice_val|
            try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(sema.mod))
        else
            try block.addTyOp(.slice_len, Type.usize, slice);
        const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
        try sema.panicIndexOutOfBounds(block, elem_index, len_inst, cmp_op);
    }
    try sema.queueFullTypeResolution(sema.typeOf(slice));
    return block.addBinOp(.slice_elem_val, slice, elem_index);
}

fn elemPtrSlice(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    slice_src: LazySrcLoc,
    slice: Air.Inst.Ref,
    elem_index_src: LazySrcLoc,
    elem_index: Air.Inst.Ref,
    oob_safety: bool,
) CompileError!Air.Inst.Ref {
    const target = sema.mod.getTarget();
    const slice_ty = sema.typeOf(slice);
    const slice_sent = slice_ty.sentinel() != null;

    const maybe_undef_slice_val = try sema.resolveMaybeUndefVal(slice);
    // The index must not be undefined since it can be out of bounds.
    const offset: ?usize = if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| o: {
        const index = try sema.usizeCast(block, elem_index_src, index_val.toUnsignedInt(target));
        break :o index;
    } else null;

    const elem_ptr_ty = try sema.elemPtrType(slice_ty, offset);

    if (maybe_undef_slice_val) |slice_val| {
        if (slice_val.isUndef()) {
            return sema.addConstUndef(elem_ptr_ty);
        }
        const slice_len = slice_val.sliceLen(sema.mod);
        const slice_len_s = slice_len + @boolToInt(slice_sent);
        if (slice_len_s == 0) {
            return sema.fail(block, slice_src, "indexing into empty slice is not allowed", .{});
        }
        if (offset) |index| {
            if (index >= slice_len_s) {
                const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
                return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
            }
            const elem_ptr_val = try slice_val.elemPtr(slice_ty, sema.arena, index, sema.mod);
            return sema.addConstant(elem_ptr_ty, elem_ptr_val);
        }
    }

    try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ptr_ty, slice_ty, slice_src);

    const runtime_src = if (maybe_undef_slice_val != null) elem_index_src else slice_src;
    try sema.requireRuntimeBlock(block, src, runtime_src);
    if (oob_safety and block.wantSafety()) {
        const len_inst = len: {
            if (maybe_undef_slice_val) |slice_val|
                if (!slice_val.isUndef())
                    break :len try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(sema.mod));
            break :len try block.addTyOp(.slice_len, Type.usize, slice);
        };
        const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
        try sema.panicIndexOutOfBounds(block, elem_index, len_inst, cmp_op);
    }
    return block.addSliceElemPtr(slice, elem_index, elem_ptr_ty);
}

fn coerce(
    sema: *Sema,
    block: *Block,
    dest_ty_unresolved: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    return sema.coerceExtra(block, dest_ty_unresolved, inst, inst_src, .{}) catch |err| switch (err) {
        error.NotCoercible => unreachable,
        else => |e| return e,
    };
}

const CoersionError = CompileError || error{
    /// When coerce is called recursively, this error should be returned instead of using `fail`
    /// to ensure correct types in compile errors.
    NotCoercible,
};

const CoerceOpts = struct {
    /// Should coerceExtra emit error messages.
    report_err: bool = true,
    /// Ignored if `report_err == false`.
    is_ret: bool = false,
    /// Should coercion to comptime_int ermit an error message.
    no_cast_to_comptime_int: bool = false,

    param_src: struct {
        func_inst: Air.Inst.Ref = .none,
        param_i: u32 = undefined,

        fn get(info: @This(), sema: *Sema) !?Module.SrcLoc {
            if (info.func_inst == .none) return null;
            const fn_decl = (try sema.funcDeclSrc(info.func_inst)) orelse return null;
            const param_src = Module.paramSrc(0, sema.gpa, fn_decl, info.param_i);
            if (param_src == .node_offset_param) {
                return Module.SrcLoc{
                    .file_scope = fn_decl.getFileScope(),
                    .parent_decl_node = fn_decl.src_node,
                    .lazy = LazySrcLoc.nodeOffset(param_src.node_offset_param),
                };
            }
            return param_src.toSrcLoc(fn_decl);
        }
    } = .{},
};

fn coerceExtra(
    sema: *Sema,
    block: *Block,
    dest_ty_unresolved: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
    opts: CoerceOpts,
) CoersionError!Air.Inst.Ref {
    switch (dest_ty_unresolved.tag()) {
        .var_args_param => return sema.coerceVarArgParam(block, inst, inst_src),
        .generic_poison => return inst,
        else => {},
    }
    const dest_ty_src = inst_src; // TODO better source location
    const dest_ty = try sema.resolveTypeFields(dest_ty_unresolved);
    const inst_ty = try sema.resolveTypeFields(sema.typeOf(inst));
    const target = sema.mod.getTarget();
    // If the types are the same, we can return the operand.
    if (dest_ty.eql(inst_ty, sema.mod))
        return inst;

    const arena = sema.arena;
    const maybe_inst_val = try sema.resolveMaybeUndefVal(inst);

    var in_memory_result = try sema.coerceInMemoryAllowed(block, dest_ty, inst_ty, false, target, dest_ty_src, inst_src);
    if (in_memory_result == .ok) {
        if (maybe_inst_val) |val| {
            // Keep the comptime Value representation; take the new type.
            return sema.addConstant(dest_ty, val);
        }
        try sema.requireRuntimeBlock(block, inst_src, null);
        return block.addBitCast(dest_ty, inst);
    }

    const is_undef = inst_ty.zigTypeTag() == .Undefined;

    switch (dest_ty.zigTypeTag()) {
        .Optional => optional: {
            // undefined sets the optional bit also to undefined.
            if (is_undef) {
                return sema.addConstUndef(dest_ty);
            }

            // null to ?T
            if (inst_ty.zigTypeTag() == .Null) {
                return sema.addConstant(dest_ty, Value.null);
            }

            // cast from ?*T and ?[*]T to ?*anyopaque
            // but don't do it if the source type is a double pointer
            if (dest_ty.isPtrLikeOptional() and dest_ty.elemType2().tag() == .anyopaque and
                inst_ty.isPtrAtRuntime())
            anyopaque_check: {
                if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :optional;
                const elem_ty = inst_ty.elemType2();
                if (elem_ty.zigTypeTag() == .Pointer or elem_ty.isPtrLikeOptional()) {
                    in_memory_result = .{ .double_ptr_to_anyopaque = .{
                        .actual = inst_ty,
                        .wanted = dest_ty,
                    } };
                    break :optional;
                }
                // Let the logic below handle wrapping the optional now that
                // it has been checked to correctly coerce.
                if (!inst_ty.isPtrLikeOptional()) break :anyopaque_check;
                return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
            }

            // T to ?T
            const child_type = try dest_ty.optionalChildAlloc(sema.arena);
            const intermediate = sema.coerceExtra(block, child_type, inst, inst_src, .{ .report_err = false }) catch |err| switch (err) {
                error.NotCoercible => {
                    if (in_memory_result == .no_match) {
                        // Try to give more useful notes
                        in_memory_result = try sema.coerceInMemoryAllowed(block, child_type, inst_ty, false, target, dest_ty_src, inst_src);
                    }
                    break :optional;
                },
                else => |e| return e,
            };
            return try sema.wrapOptional(block, dest_ty, intermediate, inst_src);
        },
        .Pointer => pointer: {
            const dest_info = dest_ty.ptrInfo().data;

            // Function body to function pointer.
            if (inst_ty.zigTypeTag() == .Fn) {
                const fn_val = try sema.resolveConstValue(block, .unneeded, inst, "");
                const fn_decl = fn_val.pointerDecl().?;
                const inst_as_ptr = try sema.analyzeDeclRef(fn_decl);
                return sema.coerce(block, dest_ty, inst_as_ptr, inst_src);
            }

            // *T to *[1]T
            single_item: {
                if (dest_info.size != .One) break :single_item;
                if (!inst_ty.isSinglePointer()) break :single_item;
                if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :pointer;
                const ptr_elem_ty = inst_ty.childType();
                const array_ty = dest_info.pointee_type;
                if (array_ty.zigTypeTag() != .Array) break :single_item;
                const array_elem_ty = array_ty.childType();
                if (array_ty.arrayLen() != 1) break :single_item;
                const dest_is_mut = dest_info.mutable;
                switch (try sema.coerceInMemoryAllowed(block, array_elem_ty, ptr_elem_ty, dest_is_mut, target, dest_ty_src, inst_src)) {
                    .ok => {},
                    else => break :single_item,
                }
                return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
            }

            // Coercions where the source is a single pointer to an array.
            src_array_ptr: {
                if (!inst_ty.isSinglePointer()) break :src_array_ptr;
                if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :pointer;
                const array_ty = inst_ty.childType();
                if (array_ty.zigTypeTag() != .Array) break :src_array_ptr;
                const array_elem_type = array_ty.childType();
                const dest_is_mut = dest_info.mutable;

                const dst_elem_type = dest_info.pointee_type;
                const elem_res = try sema.coerceInMemoryAllowed(block, dst_elem_type, array_elem_type, dest_is_mut, target, dest_ty_src, inst_src);
                switch (elem_res) {
                    .ok => {},
                    else => {
                        in_memory_result = .{ .ptr_child = .{
                            .child = try elem_res.dupe(sema.arena),
                            .actual = array_elem_type,
                            .wanted = dst_elem_type,
                        } };
                        break :src_array_ptr;
                    },
                }

                if (dest_info.sentinel) |dest_sent| {
                    if (array_ty.sentinel()) |inst_sent| {
                        if (!dest_sent.eql(inst_sent, dst_elem_type, sema.mod)) {
                            in_memory_result = .{ .ptr_sentinel = .{
                                .actual = inst_sent,
                                .wanted = dest_sent,
                                .ty = dst_elem_type,
                            } };
                            break :src_array_ptr;
                        }
                    } else {
                        in_memory_result = .{ .ptr_sentinel = .{
                            .actual = Value.initTag(.unreachable_value),
                            .wanted = dest_sent,
                            .ty = dst_elem_type,
                        } };
                        break :src_array_ptr;
                    }
                }

                switch (dest_info.size) {
                    .Slice => {
                        // *[N]T to []T
                        return sema.coerceArrayPtrToSlice(block, dest_ty, inst, inst_src);
                    },
                    .C => {
                        // *[N]T to [*c]T
                        return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
                    },
                    .Many => {
                        // *[N]T to [*]T
                        return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
                    },
                    .One => {},
                }
            }

            // coercion from C pointer
            if (inst_ty.isCPtr()) src_c_ptr: {
                if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :src_c_ptr;
                // In this case we must add a safety check because the C pointer
                // could be null.
                const src_elem_ty = inst_ty.childType();
                const dest_is_mut = dest_info.mutable;
                const dst_elem_type = dest_info.pointee_type;
                switch (try sema.coerceInMemoryAllowed(block, dst_elem_type, src_elem_ty, dest_is_mut, target, dest_ty_src, inst_src)) {
                    .ok => {},
                    else => break :src_c_ptr,
                }
                return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
            }

            // cast from *T and [*]T to *anyopaque
            // but don't do it if the source type is a double pointer
            if (dest_info.pointee_type.tag() == .anyopaque and inst_ty.zigTypeTag() == .Pointer) {
                if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :pointer;
                const elem_ty = inst_ty.elemType2();
                if (elem_ty.zigTypeTag() == .Pointer or elem_ty.isPtrLikeOptional()) {
                    in_memory_result = .{ .double_ptr_to_anyopaque = .{
                        .actual = inst_ty,
                        .wanted = dest_ty,
                    } };
                    break :pointer;
                }
                return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
            }

            switch (dest_info.size) {
                // coercion to C pointer
                .C => switch (inst_ty.zigTypeTag()) {
                    .Null => {
                        return sema.addConstant(dest_ty, Value.null);
                    },
                    .ComptimeInt => {
                        const addr = sema.coerceExtra(block, Type.usize, inst, inst_src, .{ .report_err = false }) catch |err| switch (err) {
                            error.NotCoercible => break :pointer,
                            else => |e| return e,
                        };
                        return try sema.coerceCompatiblePtrs(block, dest_ty, addr, inst_src);
                    },
                    .Int => {
                        const ptr_size_ty = switch (inst_ty.intInfo(target).signedness) {
                            .signed => Type.isize,
                            .unsigned => Type.usize,
                        };
                        const addr = sema.coerceExtra(block, ptr_size_ty, inst, inst_src, .{ .report_err = false }) catch |err| switch (err) {
                            error.NotCoercible => {
                                // Try to give more useful notes
                                in_memory_result = try sema.coerceInMemoryAllowed(block, ptr_size_ty, inst_ty, false, target, dest_ty_src, inst_src);
                                break :pointer;
                            },
                            else => |e| return e,
                        };
                        return try sema.coerceCompatiblePtrs(block, dest_ty, addr, inst_src);
                    },
                    .Pointer => p: {
                        if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :p;
                        const inst_info = inst_ty.ptrInfo().data;
                        switch (try sema.coerceInMemoryAllowed(
                            block,
                            dest_info.pointee_type,
                            inst_info.pointee_type,
                            dest_info.mutable,
                            target,
                            dest_ty_src,
                            inst_src,
                        )) {
                            .ok => {},
                            else => break :p,
                        }
                        if (inst_info.size == .Slice) {
                            assert(dest_info.sentinel == null);
                            if (inst_info.sentinel == null or
                                !inst_info.sentinel.?.eql(Value.zero, dest_info.pointee_type, sema.mod))
                                break :p;

                            const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty);
                            return sema.coerceCompatiblePtrs(block, dest_ty, slice_ptr, inst_src);
                        }
                        return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
                    },
                    else => {},
                },
                .One => switch (dest_info.pointee_type.zigTypeTag()) {
                    .Union => {
                        // pointer to anonymous struct to pointer to union
                        if (inst_ty.isSinglePointer() and
                            inst_ty.childType().isAnonStruct() and
                            sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result))
                        {
                            return sema.coerceAnonStructToUnionPtrs(block, dest_ty, dest_ty_src, inst, inst_src);
                        }
                    },
                    .Struct => {
                        // pointer to anonymous struct to pointer to struct
                        if (inst_ty.isSinglePointer() and
                            inst_ty.childType().isAnonStruct() and
                            sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result))
                        {
                            return sema.coerceAnonStructToStructPtrs(block, dest_ty, dest_ty_src, inst, inst_src) catch |err| switch (err) {
                                error.NotCoercible => break :pointer,
                                else => |e| return e,
                            };
                        }
                    },
                    .Array => {
                        // pointer to tuple to pointer to array
                        if (inst_ty.isSinglePointer() and
                            inst_ty.childType().isTuple() and
                            sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result))
                        {
                            return sema.coerceTupleToArrayPtrs(block, dest_ty, dest_ty_src, inst, inst_src);
                        }
                    },
                    else => {},
                },
                .Slice => to_slice: {
                    if (inst_ty.zigTypeTag() == .Array) {
                        return sema.fail(
                            block,
                            inst_src,
                            "array literal requires address-of operator (&) to coerce to slice type '{}'",
                            .{dest_ty.fmt(sema.mod)},
                        );
                    }

                    if (!inst_ty.isSinglePointer()) break :to_slice;
                    const inst_child_ty = inst_ty.childType();
                    if (!inst_child_ty.isTuple()) break :to_slice;

                    // empty tuple to zero-length slice
                    // note that this allows coercing to a mutable slice.
                    if (inst_child_ty.structFieldCount() == 0) {
                        // Optional slice is represented with a null pointer so
                        // we use a dummy pointer value with the required alignment.
                        const slice_val = try Value.Tag.slice.create(sema.arena, .{
                            .ptr = if (dest_info.@"align" != 0)
                                try Value.Tag.int_u64.create(sema.arena, dest_info.@"align")
                            else
                                try inst_child_ty.lazyAbiAlignment(target, sema.arena),
                            .len = Value.zero,
                        });
                        return sema.addConstant(dest_ty, slice_val);
                    }

                    // pointer to tuple to slice
                    if (dest_info.mutable) {
                        const err_msg = err_msg: {
                            const err_msg = try sema.errMsg(block, inst_src, "cannot cast pointer to tuple to '{}'", .{dest_ty.fmt(sema.mod)});
                            errdefer err_msg.deinit(sema.gpa);
                            try sema.errNote(block, dest_ty_src, err_msg, "pointers to tuples can only coerce to constant pointers", .{});
                            break :err_msg err_msg;
                        };
                        return sema.failWithOwnedErrorMsg(err_msg);
                    }
                    return sema.coerceTupleToSlicePtrs(block, dest_ty, dest_ty_src, inst, inst_src);
                },
                .Many => p: {
                    if (!inst_ty.isSlice()) break :p;
                    if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :p;
                    const inst_info = inst_ty.ptrInfo().data;

                    switch (try sema.coerceInMemoryAllowed(
                        block,
                        dest_info.pointee_type,
                        inst_info.pointee_type,
                        dest_info.mutable,
                        target,
                        dest_ty_src,
                        inst_src,
                    )) {
                        .ok => {},
                        else => break :p,
                    }

                    if (dest_info.sentinel == null or inst_info.sentinel == null or
                        !dest_info.sentinel.?.eql(inst_info.sentinel.?, dest_info.pointee_type, sema.mod))
                        break :p;

                    const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty);
                    return sema.coerceCompatiblePtrs(block, dest_ty, slice_ptr, inst_src);
                },
            }
        },
        .Int, .ComptimeInt => switch (inst_ty.zigTypeTag()) {
            .Float, .ComptimeFloat => float: {
                if (is_undef) {
                    return sema.addConstUndef(dest_ty);
                }
                const val = (try sema.resolveMaybeUndefVal(inst)) orelse {
                    if (dest_ty.zigTypeTag() == .ComptimeInt) {
                        if (!opts.report_err) return error.NotCoercible;
                        return sema.failWithNeededComptime(block, inst_src, "value being casted to 'comptime_int' must be comptime-known");
                    }
                    break :float;
                };

                if (val.floatHasFraction()) {
                    return sema.fail(
                        block,
                        inst_src,
                        "fractional component prevents float value '{}' from coercion to type '{}'",
                        .{ val.fmtValue(inst_ty, sema.mod), dest_ty.fmt(sema.mod) },
                    );
                }
                const result_val = try sema.floatToInt(block, inst_src, val, inst_ty, dest_ty);
                return try sema.addConstant(dest_ty, result_val);
            },
            .Int, .ComptimeInt => {
                if (is_undef) {
                    return sema.addConstUndef(dest_ty);
                }
                if (try sema.resolveMaybeUndefVal(inst)) |val| {
                    // comptime-known integer to other number
                    if (!(try sema.intFitsInType(val, dest_ty, null))) {
                        if (!opts.report_err) return error.NotCoercible;
                        return sema.fail(block, inst_src, "type '{}' cannot represent integer value '{}'", .{ dest_ty.fmt(sema.mod), val.fmtValue(inst_ty, sema.mod) });
                    }
                    return try sema.addConstant(dest_ty, val);
                }
                if (dest_ty.zigTypeTag() == .ComptimeInt) {
                    if (!opts.report_err) return error.NotCoercible;
                    if (opts.no_cast_to_comptime_int) return inst;
                    return sema.failWithNeededComptime(block, inst_src, "value being casted to 'comptime_int' must be comptime-known");
                }

                // integer widening
                const dst_info = dest_ty.intInfo(target);
                const src_info = inst_ty.intInfo(target);
                if ((src_info.signedness == dst_info.signedness and dst_info.bits >= src_info.bits) or
                    // small enough unsigned ints can get casted to large enough signed ints
                    (dst_info.signedness == .signed and dst_info.bits > src_info.bits))
                {
                    try sema.requireRuntimeBlock(block, inst_src, null);
                    return block.addTyOp(.intcast, dest_ty, inst);
                }
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => {},
        },
        .Float, .ComptimeFloat => switch (inst_ty.zigTypeTag()) {
            .ComptimeFloat => {
                const val = try sema.resolveConstValue(block, .unneeded, inst, "");
                const result_val = try val.floatCast(sema.arena, dest_ty, target);
                return try sema.addConstant(dest_ty, result_val);
            },
            .Float => {
                if (is_undef) {
                    return sema.addConstUndef(dest_ty);
                }
                if (try sema.resolveMaybeUndefVal(inst)) |val| {
                    const result_val = try val.floatCast(sema.arena, dest_ty, target);
                    if (!val.eql(result_val, inst_ty, sema.mod)) {
                        return sema.fail(
                            block,
                            inst_src,
                            "type '{}' cannot represent float value '{}'",
                            .{ dest_ty.fmt(sema.mod), val.fmtValue(inst_ty, sema.mod) },
                        );
                    }
                    return try sema.addConstant(dest_ty, result_val);
                } else if (dest_ty.zigTypeTag() == .ComptimeFloat) {
                    if (!opts.report_err) return error.NotCoercible;
                    return sema.failWithNeededComptime(block, inst_src, "value being casted to 'comptime_float' must be comptime-known");
                }

                // float widening
                const src_bits = inst_ty.floatBits(target);
                const dst_bits = dest_ty.floatBits(target);
                if (dst_bits >= src_bits) {
                    try sema.requireRuntimeBlock(block, inst_src, null);
                    return block.addTyOp(.fpext, dest_ty, inst);
                }
            },
            .Int, .ComptimeInt => int: {
                if (is_undef) {
                    return sema.addConstUndef(dest_ty);
                }
                const val = (try sema.resolveMaybeUndefVal(inst)) orelse {
                    if (dest_ty.zigTypeTag() == .ComptimeFloat) {
                        if (!opts.report_err) return error.NotCoercible;
                        return sema.failWithNeededComptime(block, inst_src, "value being casted to 'comptime_float' must be comptime-known");
                    }
                    break :int;
                };
                const result_val = try val.intToFloatAdvanced(sema.arena, inst_ty, dest_ty, sema.mod, sema);
                // TODO implement this compile error
                //const int_again_val = try result_val.floatToInt(sema.arena, inst_ty);
                //if (!int_again_val.eql(val, inst_ty, mod)) {
                //    return sema.fail(
                //        block,
                //        inst_src,
                //        "type '{}' cannot represent integer value '{}'",
                //        .{ dest_ty.fmt(sema.mod), val },
                //    );
                //}
                return try sema.addConstant(dest_ty, result_val);
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => {},
        },
        .Enum => switch (inst_ty.zigTypeTag()) {
            .EnumLiteral => {
                // enum literal to enum
                const val = try sema.resolveConstValue(block, .unneeded, inst, "");
                const bytes = val.castTag(.enum_literal).?.data;
                const field_index = dest_ty.enumFieldIndex(bytes) orelse {
                    const msg = msg: {
                        const msg = try sema.errMsg(
                            block,
                            inst_src,
                            "no field named '{s}' in enum '{}'",
                            .{ bytes, dest_ty.fmt(sema.mod) },
                        );
                        errdefer msg.destroy(sema.gpa);
                        try sema.addDeclaredHereNote(msg, dest_ty);
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                };
                return sema.addConstant(
                    dest_ty,
                    try Value.Tag.enum_field_index.create(arena, @intCast(u32, field_index)),
                );
            },
            .Union => blk: {
                // union to its own tag type
                const union_tag_ty = inst_ty.unionTagType() orelse break :blk;
                if (union_tag_ty.eql(dest_ty, sema.mod)) {
                    return sema.unionToTag(block, dest_ty, inst, inst_src);
                }
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => {},
        },
        .ErrorUnion => switch (inst_ty.zigTypeTag()) {
            .ErrorUnion => eu: {
                if (maybe_inst_val) |inst_val| {
                    switch (inst_val.tag()) {
                        .undef => return sema.addConstUndef(dest_ty),
                        .eu_payload => {
                            const payload = try sema.addConstant(
                                inst_ty.errorUnionPayload(),
                                inst_val.castTag(.eu_payload).?.data,
                            );
                            return sema.wrapErrorUnionPayload(block, dest_ty, payload, inst_src) catch |err| switch (err) {
                                error.NotCoercible => break :eu,
                                else => |e| return e,
                            };
                        },
                        else => {
                            const error_set = try sema.addConstant(
                                inst_ty.errorUnionSet(),
                                inst_val,
                            );
                            return sema.wrapErrorUnionSet(block, dest_ty, error_set, inst_src);
                        },
                    }
                }
            },
            .ErrorSet => {
                // E to E!T
                return sema.wrapErrorUnionSet(block, dest_ty, inst, inst_src);
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => eu: {
                // T to E!T
                return sema.wrapErrorUnionPayload(block, dest_ty, inst, inst_src) catch |err| switch (err) {
                    error.NotCoercible => break :eu,
                    else => |e| return e,
                };
            },
        },
        .Union => switch (inst_ty.zigTypeTag()) {
            .Enum, .EnumLiteral => return sema.coerceEnumToUnion(block, dest_ty, dest_ty_src, inst, inst_src),
            .Struct => {
                if (inst_ty.isAnonStruct()) {
                    return sema.coerceAnonStructToUnion(block, dest_ty, dest_ty_src, inst, inst_src);
                }
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => {},
        },
        .Array => switch (inst_ty.zigTypeTag()) {
            .Vector => return sema.coerceArrayLike(block, dest_ty, dest_ty_src, inst, inst_src),
            .Struct => {
                if (inst == .empty_struct) {
                    return sema.arrayInitEmpty(block, inst_src, dest_ty);
                }
                if (inst_ty.isTuple()) {
                    return sema.coerceTupleToArray(block, dest_ty, dest_ty_src, inst, inst_src);
                }
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => {},
        },
        .Vector => switch (inst_ty.zigTypeTag()) {
            .Array, .Vector => return sema.coerceArrayLike(block, dest_ty, dest_ty_src, inst, inst_src),
            .Struct => {
                if (inst_ty.isTuple()) {
                    return sema.coerceTupleToArray(block, dest_ty, dest_ty_src, inst, inst_src);
                }
            },
            .Undefined => {
                return sema.addConstUndef(dest_ty);
            },
            else => {},
        },
        .Struct => blk: {
            if (inst == .empty_struct) {
                return sema.structInitEmpty(block, dest_ty, dest_ty_src, inst_src);
            }
            if (inst_ty.isTupleOrAnonStruct()) {
                return sema.coerceTupleToStruct(block, dest_ty, inst, inst_src) catch |err| switch (err) {
                    error.NotCoercible => break :blk,
                    else => |e| return e,
                };
            }
        },
        else => {},
    }

    // undefined to anything. We do this after the big switch above so that
    // special logic has a chance to run first, such as `*[N]T` to `[]T` which
    // should initialize the length field of the slice.
    if (is_undef) {
        return sema.addConstUndef(dest_ty);
    }

    if (!opts.report_err) return error.NotCoercible;

    if (opts.is_ret and dest_ty.zigTypeTag() == .NoReturn) {
        const msg = msg: {
            const msg = try sema.errMsg(block, inst_src, "function declared 'noreturn' returns", .{});
            errdefer msg.destroy(sema.gpa);

            const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = 0 };
            const src_decl = sema.mod.declPtr(sema.func.?.owner_decl);
            try sema.mod.errNoteNonLazy(ret_ty_src.toSrcLoc(src_decl), msg, "'noreturn' declared here", .{});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const msg = msg: {
        const msg = try sema.errMsg(block, inst_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod) });
        errdefer msg.destroy(sema.gpa);

        // E!T to T
        if (inst_ty.zigTypeTag() == .ErrorUnion and
            (try sema.coerceInMemoryAllowed(block, inst_ty.errorUnionPayload(), dest_ty, false, target, dest_ty_src, inst_src)) == .ok)
        {
            try sema.errNote(block, inst_src, msg, "cannot convert error union to payload type", .{});
            try sema.errNote(block, inst_src, msg, "consider using 'try', 'catch', or 'if'", .{});
        }

        // ?T to T
        var buf: Type.Payload.ElemType = undefined;
        if (inst_ty.zigTypeTag() == .Optional and
            (try sema.coerceInMemoryAllowed(block, inst_ty.optionalChild(&buf), dest_ty, false, target, dest_ty_src, inst_src)) == .ok)
        {
            try sema.errNote(block, inst_src, msg, "cannot convert optional to payload type", .{});
            try sema.errNote(block, inst_src, msg, "consider using '.?', 'orelse', or 'if'", .{});
        }

        try in_memory_result.report(sema, block, inst_src, msg);

        // Add notes about function return type
        if (opts.is_ret and sema.mod.test_functions.get(sema.func.?.owner_decl) == null) {
            const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = 0 };
            const src_decl = sema.mod.declPtr(sema.func.?.owner_decl);
            if (inst_ty.isError() and !dest_ty.isError()) {
                try sema.mod.errNoteNonLazy(ret_ty_src.toSrcLoc(src_decl), msg, "function cannot return an error", .{});
            } else {
                try sema.mod.errNoteNonLazy(ret_ty_src.toSrcLoc(src_decl), msg, "function return type declared here", .{});
            }
        }

        if (try opts.param_src.get(sema)) |param_src| {
            try sema.mod.errNoteNonLazy(param_src, msg, "parameter type declared here", .{});
        }

        // TODO maybe add "cannot store an error in type '{}'" note

        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

const InMemoryCoercionResult = union(enum) {
    ok,
    no_match: Pair,
    int_not_coercible: Int,
    error_union_payload: PairAndChild,
    array_len: IntPair,
    array_sentinel: Sentinel,
    array_elem: PairAndChild,
    vector_len: IntPair,
    vector_elem: PairAndChild,
    optional_shape: Pair,
    optional_child: PairAndChild,
    from_anyerror,
    missing_error: []const []const u8,
    /// true if wanted is var args
    fn_var_args: bool,
    /// true if wanted is generic
    fn_generic: bool,
    fn_param_count: IntPair,
    fn_param_noalias: IntPair,
    fn_param_comptime: ComptimeParam,
    fn_param: Param,
    fn_cc: CC,
    fn_return_type: PairAndChild,
    ptr_child: PairAndChild,
    ptr_addrspace: AddressSpace,
    ptr_sentinel: Sentinel,
    ptr_size: Size,
    ptr_qualifiers: Qualifiers,
    ptr_allowzero: Pair,
    ptr_bit_range: BitRange,
    ptr_alignment: IntPair,
    double_ptr_to_anyopaque: Pair,

    const Pair = struct {
        actual: Type,
        wanted: Type,
    };

    const PairAndChild = struct {
        child: *InMemoryCoercionResult,
        actual: Type,
        wanted: Type,
    };

    const Param = struct {
        child: *InMemoryCoercionResult,
        actual: Type,
        wanted: Type,
        index: u64,
    };

    const ComptimeParam = struct {
        index: u64,
        wanted: bool,
    };

    const Sentinel = struct {
        // unreachable_value indicates no sentinel
        actual: Value,
        wanted: Value,
        ty: Type,
    };

    const Int = struct {
        actual_signedness: std.builtin.Signedness,
        wanted_signedness: std.builtin.Signedness,
        actual_bits: u16,
        wanted_bits: u16,
    };

    const IntPair = struct {
        actual: u64,
        wanted: u64,
    };

    const Size = struct {
        actual: std.builtin.Type.Pointer.Size,
        wanted: std.builtin.Type.Pointer.Size,
    };

    const Qualifiers = struct {
        actual_const: bool,
        wanted_const: bool,
        actual_volatile: bool,
        wanted_volatile: bool,
    };

    const AddressSpace = struct {
        actual: std.builtin.AddressSpace,
        wanted: std.builtin.AddressSpace,
    };

    const CC = struct {
        actual: std.builtin.CallingConvention,
        wanted: std.builtin.CallingConvention,
    };

    const BitRange = struct {
        actual_host: u16,
        wanted_host: u16,
        actual_offset: u16,
        wanted_offset: u16,
    };

    fn dupe(child: *const InMemoryCoercionResult, arena: Allocator) !*InMemoryCoercionResult {
        const res = try arena.create(InMemoryCoercionResult);
        res.* = child.*;
        return res;
    }

    fn report(res: *const InMemoryCoercionResult, sema: *Sema, block: *Block, src: LazySrcLoc, msg: *Module.ErrorMsg) !void {
        var cur = res;
        while (true) switch (cur.*) {
            .ok => unreachable,
            .no_match => |types| {
                try sema.addDeclaredHereNote(msg, types.wanted);
                try sema.addDeclaredHereNote(msg, types.actual);
                break;
            },
            .int_not_coercible => |int| {
                try sema.errNote(block, src, msg, "{s} {d}-bit int cannot represent all possible {s} {d}-bit values", .{
                    @tagName(int.wanted_signedness), int.wanted_bits, @tagName(int.actual_signedness), int.actual_bits,
                });
                break;
            },
            .error_union_payload => |pair| {
                try sema.errNote(block, src, msg, "error union payload '{}' cannot cast into error union payload '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                cur = pair.child;
            },
            .array_len => |lens| {
                try sema.errNote(block, src, msg, "array of length {d} cannot cast into an array of length {d}", .{
                    lens.actual, lens.wanted,
                });
                break;
            },
            .array_sentinel => |sentinel| {
                if (sentinel.actual.tag() != .unreachable_value) {
                    try sema.errNote(block, src, msg, "array sentinel '{}' cannot cast into array sentinel '{}'", .{
                        sentinel.actual.fmtValue(sentinel.ty, sema.mod), sentinel.wanted.fmtValue(sentinel.ty, sema.mod),
                    });
                } else {
                    try sema.errNote(block, src, msg, "destination array requires '{}' sentinel", .{
                        sentinel.wanted.fmtValue(sentinel.ty, sema.mod),
                    });
                }
                break;
            },
            .array_elem => |pair| {
                try sema.errNote(block, src, msg, "array element type '{}' cannot cast into array element type '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                cur = pair.child;
            },
            .vector_len => |lens| {
                try sema.errNote(block, src, msg, "vector of length {d} cannot cast into a vector of length {d}", .{
                    lens.actual, lens.wanted,
                });
                break;
            },
            .vector_elem => |pair| {
                try sema.errNote(block, src, msg, "vector element type '{}' cannot cast into vector element type '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                cur = pair.child;
            },
            .optional_shape => |pair| {
                var buf_actual: Type.Payload.ElemType = undefined;
                var buf_wanted: Type.Payload.ElemType = undefined;
                try sema.errNote(block, src, msg, "optional type child '{}' cannot cast into optional type child '{}'", .{
                    pair.actual.optionalChild(&buf_actual).fmt(sema.mod), pair.wanted.optionalChild(&buf_wanted).fmt(sema.mod),
                });
                break;
            },
            .optional_child => |pair| {
                try sema.errNote(block, src, msg, "optional type child '{}' cannot cast into optional type child '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                cur = pair.child;
            },
            .from_anyerror => {
                try sema.errNote(block, src, msg, "global error set cannot cast into a smaller set", .{});
                break;
            },
            .missing_error => |missing_errors| {
                for (missing_errors) |err| {
                    try sema.errNote(block, src, msg, "'error.{s}' not a member of destination error set", .{err});
                }
                break;
            },
            .fn_var_args => |wanted_var_args| {
                if (wanted_var_args) {
                    try sema.errNote(block, src, msg, "non-variadic function cannot cast into a variadic function", .{});
                } else {
                    try sema.errNote(block, src, msg, "variadic function cannot cast into a non-variadic function", .{});
                }
                break;
            },
            .fn_generic => |wanted_generic| {
                if (wanted_generic) {
                    try sema.errNote(block, src, msg, "non-generic function cannot cast into a generic function", .{});
                } else {
                    try sema.errNote(block, src, msg, "generic function cannot cast into a non-generic function", .{});
                }
                break;
            },
            .fn_param_count => |lens| {
                try sema.errNote(block, src, msg, "function with {d} parameters cannot cast into a function with {d} parameters", .{
                    lens.actual, lens.wanted,
                });
                break;
            },
            .fn_param_noalias => |param| {
                var index: u6 = 0;
                var actual_noalias = false;
                while (true) : (index += 1) {
                    const actual = @truncate(u1, param.actual >> index);
                    const wanted = @truncate(u1, param.wanted >> index);
                    if (actual != wanted) {
                        actual_noalias = actual == 1;
                        break;
                    }
                }
                if (!actual_noalias) {
                    try sema.errNote(block, src, msg, "regular parameter {d} cannot cast into a noalias parameter", .{index});
                } else {
                    try sema.errNote(block, src, msg, "noalias parameter {d} cannot cast into a regular parameter", .{index});
                }
                break;
            },
            .fn_param_comptime => |param| {
                if (param.wanted) {
                    try sema.errNote(block, src, msg, "non-comptime parameter {d} cannot cast into a comptime parameter", .{param.index});
                } else {
                    try sema.errNote(block, src, msg, "comptime parameter {d} cannot cast into a non-comptime parameter", .{param.index});
                }
                break;
            },
            .fn_param => |param| {
                try sema.errNote(block, src, msg, "parameter {d} '{}' cannot cast into '{}'", .{
                    param.index, param.actual.fmt(sema.mod), param.wanted.fmt(sema.mod),
                });
                cur = param.child;
            },
            .fn_cc => |cc| {
                try sema.errNote(block, src, msg, "calling convention '{s}' cannot cast into calling convention '{s}'", .{ @tagName(cc.actual), @tagName(cc.wanted) });
                break;
            },
            .fn_return_type => |pair| {
                try sema.errNote(block, src, msg, "return type '{}' cannot cast into return type '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                cur = pair.child;
            },
            .ptr_child => |pair| {
                try sema.errNote(block, src, msg, "pointer type child '{}' cannot cast into pointer type child '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                cur = pair.child;
            },
            .ptr_addrspace => |@"addrspace"| {
                try sema.errNote(block, src, msg, "address space '{s}' cannot cast into address space '{s}'", .{ @tagName(@"addrspace".actual), @tagName(@"addrspace".wanted) });
                break;
            },
            .ptr_sentinel => |sentinel| {
                if (sentinel.actual.tag() != .unreachable_value) {
                    try sema.errNote(block, src, msg, "pointer sentinel '{}' cannot cast into pointer sentinel '{}'", .{
                        sentinel.actual.fmtValue(sentinel.ty, sema.mod), sentinel.wanted.fmtValue(sentinel.ty, sema.mod),
                    });
                } else {
                    try sema.errNote(block, src, msg, "destination pointer requires '{}' sentinel", .{
                        sentinel.wanted.fmtValue(sentinel.ty, sema.mod),
                    });
                }
                break;
            },
            .ptr_size => |size| {
                try sema.errNote(block, src, msg, "a {s} pointer cannot cast into a {s} pointer", .{ pointerSizeString(size.actual), pointerSizeString(size.wanted) });
                break;
            },
            .ptr_qualifiers => |qualifiers| {
                const ok_const = !qualifiers.actual_const or qualifiers.wanted_const;
                const ok_volatile = !qualifiers.actual_volatile or qualifiers.wanted_volatile;
                if (!ok_const) {
                    try sema.errNote(block, src, msg, "cast discards const qualifier", .{});
                } else if (!ok_volatile) {
                    try sema.errNote(block, src, msg, "cast discards volatile qualifier", .{});
                }
                break;
            },
            .ptr_allowzero => |pair| {
                const wanted_allow_zero = pair.wanted.ptrAllowsZero();
                const actual_allow_zero = pair.actual.ptrAllowsZero();
                if (actual_allow_zero and !wanted_allow_zero) {
                    try sema.errNote(block, src, msg, "'{}' could have null values which are illegal in type '{}'", .{
                        pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                    });
                } else {
                    try sema.errNote(block, src, msg, "mutable '{}' allows illegal null values stored to type '{}'", .{
                        pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                    });
                }
                break;
            },
            .ptr_bit_range => |bit_range| {
                if (bit_range.actual_host != bit_range.wanted_host) {
                    try sema.errNote(block, src, msg, "pointer host size '{}' cannot cast into pointer host size '{}'", .{
                        bit_range.actual_host, bit_range.wanted_host,
                    });
                }
                if (bit_range.actual_offset != bit_range.wanted_offset) {
                    try sema.errNote(block, src, msg, "pointer bit offset '{}' cannot cast into pointer bit offset '{}'", .{
                        bit_range.actual_offset, bit_range.wanted_offset,
                    });
                }
                break;
            },
            .ptr_alignment => |pair| {
                try sema.errNote(block, src, msg, "pointer alignment '{}' cannot cast into pointer alignment '{}'", .{
                    pair.actual, pair.wanted,
                });
                break;
            },
            .double_ptr_to_anyopaque => |pair| {
                try sema.errNote(block, src, msg, "cannot implicitly cast double pointer '{}' to anyopaque pointer '{}'", .{
                    pair.actual.fmt(sema.mod), pair.wanted.fmt(sema.mod),
                });
                break;
            },
        };
    }
};

fn pointerSizeString(size: std.builtin.Type.Pointer.Size) []const u8 {
    return switch (size) {
        .One => "single",
        .Many => "many",
        .C => "C",
        .Slice => unreachable,
    };
}

/// If pointers have the same representation in runtime memory, a bitcast AIR instruction
/// may be used for the coercion.
/// * `const` attribute can be gained
/// * `volatile` attribute can be gained
/// * `allowzero` attribute can be gained (whether from explicit attribute, C pointer, or optional pointer) but only if !dest_is_mut
/// * alignment can be decreased
/// * bit offset attributes must match exactly
/// * `*`/`[*]` must match exactly, but `[*c]` matches either one
/// * sentinel-terminated pointers can coerce into `[*]`
fn coerceInMemoryAllowed(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    src_ty: Type,
    dest_is_mut: bool,
    target: std.Target,
    dest_src: LazySrcLoc,
    src_src: LazySrcLoc,
) CompileError!InMemoryCoercionResult {
    if (dest_ty.eql(src_ty, sema.mod))
        return .ok;

    // Differently-named integers with the same number of bits.
    if (dest_ty.zigTypeTag() == .Int and src_ty.zigTypeTag() == .Int) {
        const dest_info = dest_ty.intInfo(target);
        const src_info = src_ty.intInfo(target);

        if (dest_info.signedness == src_info.signedness and
            dest_info.bits == src_info.bits)
        {
            return .ok;
        }

        if ((src_info.signedness == dest_info.signedness and dest_info.bits < src_info.bits) or
            // small enough unsigned ints can get casted to large enough signed ints
            (dest_info.signedness == .signed and (src_info.signedness == .unsigned or dest_info.bits <= src_info.bits)) or
            (dest_info.signedness == .unsigned and src_info.signedness == .signed))
        {
            return InMemoryCoercionResult{ .int_not_coercible = .{
                .actual_signedness = src_info.signedness,
                .wanted_signedness = dest_info.signedness,
                .actual_bits = src_info.bits,
                .wanted_bits = dest_info.bits,
            } };
        }
    }

    // Differently-named floats with the same number of bits.
    if (dest_ty.zigTypeTag() == .Float and src_ty.zigTypeTag() == .Float) {
        const dest_bits = dest_ty.floatBits(target);
        const src_bits = src_ty.floatBits(target);
        if (dest_bits == src_bits) {
            return .ok;
        }
    }

    // Pointers / Pointer-like Optionals
    var dest_buf: Type.Payload.ElemType = undefined;
    var src_buf: Type.Payload.ElemType = undefined;
    const maybe_dest_ptr_ty = try sema.typePtrOrOptionalPtrTy(dest_ty, &dest_buf);
    const maybe_src_ptr_ty = try sema.typePtrOrOptionalPtrTy(src_ty, &src_buf);
    if (maybe_dest_ptr_ty) |dest_ptr_ty| {
        if (maybe_src_ptr_ty) |src_ptr_ty| {
            return try sema.coerceInMemoryAllowedPtrs(block, dest_ty, src_ty, dest_ptr_ty, src_ptr_ty, dest_is_mut, target, dest_src, src_src);
        }
    }

    // Slices
    if (dest_ty.isSlice() and src_ty.isSlice()) {
        return try sema.coerceInMemoryAllowedPtrs(block, dest_ty, src_ty, dest_ty, src_ty, dest_is_mut, target, dest_src, src_src);
    }

    const dest_tag = dest_ty.zigTypeTag();
    const src_tag = src_ty.zigTypeTag();

    // Functions
    if (dest_tag == .Fn and src_tag == .Fn) {
        return try sema.coerceInMemoryAllowedFns(block, dest_ty, src_ty, target, dest_src, src_src);
    }

    // Error Unions
    if (dest_tag == .ErrorUnion and src_tag == .ErrorUnion) {
        const dest_payload = dest_ty.errorUnionPayload();
        const src_payload = src_ty.errorUnionPayload();
        const child = try sema.coerceInMemoryAllowed(block, dest_payload, src_payload, dest_is_mut, target, dest_src, src_src);
        if (child != .ok) {
            return InMemoryCoercionResult{ .error_union_payload = .{
                .child = try child.dupe(sema.arena),
                .actual = src_payload,
                .wanted = dest_payload,
            } };
        }
        return try sema.coerceInMemoryAllowed(block, dest_ty.errorUnionSet(), src_ty.errorUnionSet(), dest_is_mut, target, dest_src, src_src);
    }

    // Error Sets
    if (dest_tag == .ErrorSet and src_tag == .ErrorSet) {
        return try sema.coerceInMemoryAllowedErrorSets(block, dest_ty, src_ty, dest_src, src_src);
    }

    // Arrays
    if (dest_tag == .Array and src_tag == .Array) {
        const dest_info = dest_ty.arrayInfo();
        const src_info = src_ty.arrayInfo();
        if (dest_info.len != src_info.len) {
            return InMemoryCoercionResult{ .array_len = .{
                .actual = src_info.len,
                .wanted = dest_info.len,
            } };
        }

        const child = try sema.coerceInMemoryAllowed(block, dest_info.elem_type, src_info.elem_type, dest_is_mut, target, dest_src, src_src);
        if (child != .ok) {
            return InMemoryCoercionResult{ .array_elem = .{
                .child = try child.dupe(sema.arena),
                .actual = src_info.elem_type,
                .wanted = dest_info.elem_type,
            } };
        }
        const ok_sent = dest_info.sentinel == null or
            (src_info.sentinel != null and
            dest_info.sentinel.?.eql(src_info.sentinel.?, dest_info.elem_type, sema.mod));
        if (!ok_sent) {
            return InMemoryCoercionResult{ .array_sentinel = .{
                .actual = src_info.sentinel orelse Value.initTag(.unreachable_value),
                .wanted = dest_info.sentinel orelse Value.initTag(.unreachable_value),
                .ty = dest_info.elem_type,
            } };
        }
        return .ok;
    }

    // Vectors
    if (dest_tag == .Vector and src_tag == .Vector) {
        const dest_len = dest_ty.vectorLen();
        const src_len = src_ty.vectorLen();
        if (dest_len != src_len) {
            return InMemoryCoercionResult{ .vector_len = .{
                .actual = src_len,
                .wanted = dest_len,
            } };
        }

        const dest_elem_ty = dest_ty.scalarType();
        const src_elem_ty = src_ty.scalarType();
        const child = try sema.coerceInMemoryAllowed(block, dest_elem_ty, src_elem_ty, dest_is_mut, target, dest_src, src_src);
        if (child != .ok) {
            return InMemoryCoercionResult{ .vector_elem = .{
                .child = try child.dupe(sema.arena),
                .actual = src_elem_ty,
                .wanted = dest_elem_ty,
            } };
        }

        return .ok;
    }

    // Optionals
    if (dest_tag == .Optional and src_tag == .Optional) {
        if ((maybe_dest_ptr_ty != null) != (maybe_src_ptr_ty != null)) {
            return InMemoryCoercionResult{ .optional_shape = .{
                .actual = src_ty,
                .wanted = dest_ty,
            } };
        }
        const dest_child_type = dest_ty.optionalChild(&dest_buf);
        const src_child_type = src_ty.optionalChild(&src_buf);

        const child = try sema.coerceInMemoryAllowed(block, dest_child_type, src_child_type, dest_is_mut, target, dest_src, src_src);
        if (child != .ok) {
            return InMemoryCoercionResult{ .optional_child = .{
                .child = try child.dupe(sema.arena),
                .actual = try src_child_type.copy(sema.arena),
                .wanted = try dest_child_type.copy(sema.arena),
            } };
        }

        return .ok;
    }

    return InMemoryCoercionResult{ .no_match = .{
        .actual = dest_ty,
        .wanted = src_ty,
    } };
}

fn coerceInMemoryAllowedErrorSets(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    src_ty: Type,
    dest_src: LazySrcLoc,
    src_src: LazySrcLoc,
) !InMemoryCoercionResult {
    // Coercion to `anyerror`. Note that this check can return false negatives
    // in case the error sets did not get resolved.
    if (dest_ty.isAnyError()) {
        return .ok;
    }

    if (dest_ty.castTag(.error_set_inferred)) |dst_payload| {
        const dst_ies = dst_payload.data;
        // We will make an effort to return `ok` without resolving either error set, to
        // avoid unnecessary "unable to resolve error set" dependency loop errors.
        switch (src_ty.tag()) {
            .error_set_inferred => {
                // If both are inferred error sets of functions, and
                // the dest includes the source function, the coercion is OK.
                // This check is important because it works without forcing a full resolution
                // of inferred error sets.
                const src_ies = src_ty.castTag(.error_set_inferred).?.data;

                if (dst_ies.inferred_error_sets.contains(src_ies)) {
                    return .ok;
                }
            },
            .error_set_single => {
                const name = src_ty.castTag(.error_set_single).?.data;
                if (dst_ies.errors.contains(name)) return .ok;
            },
            .error_set_merged => {
                const names = src_ty.castTag(.error_set_merged).?.data.keys();
                for (names) |name| {
                    if (!dst_ies.errors.contains(name)) break;
                } else return .ok;
            },
            .error_set => {
                const names = src_ty.castTag(.error_set).?.data.names.keys();
                for (names) |name| {
                    if (!dst_ies.errors.contains(name)) break;
                } else return .ok;
            },
            .anyerror => {},
            else => unreachable,
        }

        if (dst_ies.func == sema.owner_func) {
            // We are trying to coerce an error set to the current function's
            // inferred error set.
            try dst_ies.addErrorSet(sema.gpa, src_ty);
            return .ok;
        }

        try sema.resolveInferredErrorSet(block, dest_src, dst_payload.data);
        // isAnyError might have changed from a false negative to a true positive after resolution.
        if (dest_ty.isAnyError()) {
            return .ok;
        }
    }

    var missing_error_buf = std.ArrayList([]const u8).init(sema.gpa);
    defer missing_error_buf.deinit();

    switch (src_ty.tag()) {
        .error_set_inferred => {
            const src_data = src_ty.castTag(.error_set_inferred).?.data;

            try sema.resolveInferredErrorSet(block, src_src, src_data);
            // src anyerror status might have changed after the resolution.
            if (src_ty.isAnyError()) {
                // dest_ty.isAnyError() == true is already checked for at this point.
                return .from_anyerror;
            }

            for (src_data.errors.keys()) |key| {
                if (!dest_ty.errorSetHasField(key)) {
                    try missing_error_buf.append(key);
                }
            }

            if (missing_error_buf.items.len != 0) {
                return InMemoryCoercionResult{
                    .missing_error = try sema.arena.dupe([]const u8, missing_error_buf.items),
                };
            }

            return .ok;
        },
        .error_set_single => {
            const name = src_ty.castTag(.error_set_single).?.data;
            if (dest_ty.errorSetHasField(name)) {
                return .ok;
            }
            const list = try sema.arena.alloc([]const u8, 1);
            list[0] = name;
            return InMemoryCoercionResult{ .missing_error = list };
        },
        .error_set_merged => {
            const names = src_ty.castTag(.error_set_merged).?.data.keys();
            for (names) |name| {
                if (!dest_ty.errorSetHasField(name)) {
                    try missing_error_buf.append(name);
                }
            }

            if (missing_error_buf.items.len != 0) {
                return InMemoryCoercionResult{
                    .missing_error = try sema.arena.dupe([]const u8, missing_error_buf.items),
                };
            }

            return .ok;
        },
        .error_set => {
            const names = src_ty.castTag(.error_set).?.data.names.keys();
            for (names) |name| {
                if (!dest_ty.errorSetHasField(name)) {
                    try missing_error_buf.append(name);
                }
            }

            if (missing_error_buf.items.len != 0) {
                return InMemoryCoercionResult{
                    .missing_error = try sema.arena.dupe([]const u8, missing_error_buf.items),
                };
            }

            return .ok;
        },
        .anyerror => switch (dest_ty.tag()) {
            .error_set_inferred => unreachable, // Caught by dest_ty.isAnyError() above.
            .error_set_single, .error_set_merged, .error_set => return .from_anyerror,
            .anyerror => unreachable, // Filtered out above.
            else => unreachable,
        },
        else => unreachable,
    }

    unreachable;
}

fn coerceInMemoryAllowedFns(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    src_ty: Type,
    target: std.Target,
    dest_src: LazySrcLoc,
    src_src: LazySrcLoc,
) !InMemoryCoercionResult {
    const dest_info = dest_ty.fnInfo();
    const src_info = src_ty.fnInfo();

    if (dest_info.is_var_args != src_info.is_var_args) {
        return InMemoryCoercionResult{ .fn_var_args = dest_info.is_var_args };
    }

    if (dest_info.is_generic != src_info.is_generic) {
        return InMemoryCoercionResult{ .fn_generic = dest_info.is_generic };
    }

    if (dest_info.cc != src_info.cc) {
        return InMemoryCoercionResult{ .fn_cc = .{
            .actual = src_info.cc,
            .wanted = dest_info.cc,
        } };
    }

    if (!src_info.return_type.isNoReturn()) {
        const rt = try sema.coerceInMemoryAllowed(block, dest_info.return_type, src_info.return_type, false, target, dest_src, src_src);
        if (rt != .ok) {
            return InMemoryCoercionResult{ .fn_return_type = .{
                .child = try rt.dupe(sema.arena),
                .actual = src_info.return_type,
                .wanted = dest_info.return_type,
            } };
        }
    }

    if (dest_info.param_types.len != src_info.param_types.len) {
        return InMemoryCoercionResult{ .fn_param_count = .{
            .actual = src_info.param_types.len,
            .wanted = dest_info.param_types.len,
        } };
    }

    if (dest_info.noalias_bits != src_info.noalias_bits) {
        return InMemoryCoercionResult{ .fn_param_noalias = .{
            .actual = src_info.noalias_bits,
            .wanted = dest_info.noalias_bits,
        } };
    }

    for (dest_info.param_types, 0..) |dest_param_ty, i| {
        const src_param_ty = src_info.param_types[i];

        if (dest_info.comptime_params[i] != src_info.comptime_params[i]) {
            return InMemoryCoercionResult{ .fn_param_comptime = .{
                .index = i,
                .wanted = dest_info.comptime_params[i],
            } };
        }

        // Note: Cast direction is reversed here.
        const param = try sema.coerceInMemoryAllowed(block, src_param_ty, dest_param_ty, false, target, dest_src, src_src);
        if (param != .ok) {
            return InMemoryCoercionResult{ .fn_param = .{
                .child = try param.dupe(sema.arena),
                .actual = src_param_ty,
                .wanted = dest_param_ty,
                .index = i,
            } };
        }
    }

    return .ok;
}

fn coerceInMemoryAllowedPtrs(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    src_ty: Type,
    dest_ptr_ty: Type,
    src_ptr_ty: Type,
    dest_is_mut: bool,
    target: std.Target,
    dest_src: LazySrcLoc,
    src_src: LazySrcLoc,
) !InMemoryCoercionResult {
    const dest_info = dest_ptr_ty.ptrInfo().data;
    const src_info = src_ptr_ty.ptrInfo().data;

    const ok_ptr_size = src_info.size == dest_info.size or
        src_info.size == .C or dest_info.size == .C;
    if (!ok_ptr_size) {
        return InMemoryCoercionResult{ .ptr_size = .{
            .actual = src_info.size,
            .wanted = dest_info.size,
        } };
    }

    const ok_cv_qualifiers =
        (src_info.mutable or !dest_info.mutable) and
        (!src_info.@"volatile" or dest_info.@"volatile");

    if (!ok_cv_qualifiers) {
        return InMemoryCoercionResult{ .ptr_qualifiers = .{
            .actual_const = !src_info.mutable,
            .wanted_const = !dest_info.mutable,
            .actual_volatile = src_info.@"volatile",
            .wanted_volatile = dest_info.@"volatile",
        } };
    }

    if (dest_info.@"addrspace" != src_info.@"addrspace") {
        return InMemoryCoercionResult{ .ptr_addrspace = .{
            .actual = src_info.@"addrspace",
            .wanted = dest_info.@"addrspace",
        } };
    }

    const child = try sema.coerceInMemoryAllowed(block, dest_info.pointee_type, src_info.pointee_type, dest_info.mutable, target, dest_src, src_src);
    if (child != .ok) {
        return InMemoryCoercionResult{ .ptr_child = .{
            .child = try child.dupe(sema.arena),
            .actual = src_info.pointee_type,
            .wanted = dest_info.pointee_type,
        } };
    }

    const dest_allow_zero = dest_ty.ptrAllowsZero();
    const src_allow_zero = src_ty.ptrAllowsZero();

    const ok_allows_zero = (dest_allow_zero and
        (src_allow_zero or !dest_is_mut)) or
        (!dest_allow_zero and !src_allow_zero);
    if (!ok_allows_zero) {
        return InMemoryCoercionResult{ .ptr_allowzero = .{
            .actual = src_ty,
            .wanted = dest_ty,
        } };
    }

    if (src_info.host_size != dest_info.host_size or
        src_info.bit_offset != dest_info.bit_offset)
    {
        return InMemoryCoercionResult{ .ptr_bit_range = .{
            .actual_host = src_info.host_size,
            .wanted_host = dest_info.host_size,
            .actual_offset = src_info.bit_offset,
            .wanted_offset = dest_info.bit_offset,
        } };
    }

    const ok_sent = dest_info.sentinel == null or src_info.size == .C or
        (src_info.sentinel != null and
        dest_info.sentinel.?.eql(src_info.sentinel.?, dest_info.pointee_type, sema.mod));
    if (!ok_sent) {
        return InMemoryCoercionResult{ .ptr_sentinel = .{
            .actual = src_info.sentinel orelse Value.initTag(.unreachable_value),
            .wanted = dest_info.sentinel orelse Value.initTag(.unreachable_value),
            .ty = dest_info.pointee_type,
        } };
    }

    // If both pointers have alignment 0, it means they both want ABI alignment.
    // In this case, if they share the same child type, no need to resolve
    // pointee type alignment. Otherwise both pointee types must have their alignment
    // resolved and we compare the alignment numerically.
    alignment: {
        if (src_info.@"align" == 0 and dest_info.@"align" == 0 and
            dest_info.pointee_type.eql(src_info.pointee_type, sema.mod))
        {
            break :alignment;
        }

        const src_align = if (src_info.@"align" != 0)
            src_info.@"align"
        else
            src_info.pointee_type.abiAlignment(target);

        const dest_align = if (dest_info.@"align" != 0)
            dest_info.@"align"
        else
            dest_info.pointee_type.abiAlignment(target);

        if (dest_align > src_align) {
            return InMemoryCoercionResult{ .ptr_alignment = .{
                .actual = src_align,
                .wanted = dest_align,
            } };
        }

        break :alignment;
    }

    return .ok;
}

fn coerceVarArgParam(
    sema: *Sema,
    block: *Block,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    if (block.is_typeof) return inst;

    const uncasted_ty = sema.typeOf(inst);
    const coerced = switch (uncasted_ty.zigTypeTag()) {
        // TODO consider casting to c_int/f64 if they fit
        .ComptimeInt, .ComptimeFloat => return sema.fail(
            block,
            inst_src,
            "integer and float literals passed variadic function must be casted to a fixed-size number type",
            .{},
        ),
        .Fn => blk: {
            const fn_val = try sema.resolveConstValue(block, .unneeded, inst, "");
            const fn_decl = fn_val.pointerDecl().?;
            break :blk try sema.analyzeDeclRef(fn_decl);
        },
        .Array => return sema.fail(block, inst_src, "arrays must be passed by reference to variadic function", .{}),
        .Float => float: {
            const target = sema.mod.getTarget();
            const double_bits = target.c_type_bit_size(.double);
            const inst_bits = uncasted_ty.floatBits(sema.mod.getTarget());
            if (inst_bits >= double_bits) break :float inst;
            switch (double_bits) {
                32 => break :float try sema.coerce(block, Type.f32, inst, inst_src),
                64 => break :float try sema.coerce(block, Type.f64, inst, inst_src),
                else => unreachable,
            }
        },
        else => inst,
    };

    const coerced_ty = sema.typeOf(coerced);
    if (!try sema.validateExternType(coerced_ty, .param_ty)) {
        const msg = msg: {
            const msg = try sema.errMsg(block, inst_src, "cannot pass '{}' to variadic function", .{coerced_ty.fmt(sema.mod)});
            errdefer msg.destroy(sema.gpa);

            const src_decl = sema.mod.declPtr(block.src_decl);
            try sema.explainWhyTypeIsNotExtern(msg, inst_src.toSrcLoc(src_decl), coerced_ty, .param_ty);

            try sema.addDeclaredHereNote(msg, coerced_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
    return coerced;
}

// TODO migrate callsites to use storePtr2 instead.
fn storePtr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    uncasted_operand: Air.Inst.Ref,
) CompileError!void {
    return sema.storePtr2(block, src, ptr, src, uncasted_operand, src, .store);
}

fn storePtr2(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    ptr_src: LazySrcLoc,
    uncasted_operand: Air.Inst.Ref,
    operand_src: LazySrcLoc,
    air_tag: Air.Inst.Tag,
) CompileError!void {
    const ptr_ty = sema.typeOf(ptr);
    if (ptr_ty.isConstPtr())
        return sema.fail(block, ptr_src, "cannot assign to constant", .{});

    const elem_ty = ptr_ty.childType();

    // To generate better code for tuples, we detect a tuple operand here, and
    // analyze field loads and stores directly. This avoids an extra allocation + memcpy
    // which would occur if we used `coerce`.
    // However, we avoid this mechanism if the destination element type is a tuple,
    // because the regular store will be better for this case.
    // If the destination type is a struct we don't want this mechanism to trigger, because
    // this code does not handle tuple-to-struct coercion which requires dealing with missing
    // fields.
    const operand_ty = sema.typeOf(uncasted_operand);
    if (operand_ty.isTuple() and elem_ty.zigTypeTag() == .Array) {
        const field_count = operand_ty.structFieldCount();
        var i: u32 = 0;
        while (i < field_count) : (i += 1) {
            const elem_src = operand_src; // TODO better source location
            const elem = try sema.tupleField(block, operand_src, uncasted_operand, elem_src, i);
            const elem_index = try sema.addIntUnsigned(Type.usize, i);
            const elem_ptr = try sema.elemPtr(block, ptr_src, ptr, elem_index, elem_src, false, true);
            try sema.storePtr2(block, src, elem_ptr, elem_src, elem, elem_src, .store);
        }
        return;
    }

    // TODO do the same thing for anon structs as for tuples above.
    // However, beware of the need to handle missing/extra fields.

    const is_ret = air_tag == .ret_ptr;

    // Detect if we are storing an array operand to a bitcasted vector pointer.
    // If so, we instead reach through the bitcasted pointer to the vector pointer,
    // bitcast the array operand to a vector, and then lower this as a store of
    // a vector value to a vector pointer. This generally results in better code,
    // as well as working around an LLVM bug:
    // https://github.com/ziglang/zig/issues/11154
    if (sema.obtainBitCastedVectorPtr(ptr)) |vector_ptr| {
        const vector_ty = sema.typeOf(vector_ptr).childType();
        const vector = sema.coerceExtra(block, vector_ty, uncasted_operand, operand_src, .{ .is_ret = is_ret }) catch |err| switch (err) {
            error.NotCoercible => unreachable,
            else => |e| return e,
        };
        try sema.storePtr2(block, src, vector_ptr, ptr_src, vector, operand_src, .store);
        return;
    }

    const operand = sema.coerceExtra(block, elem_ty, uncasted_operand, operand_src, .{ .is_ret = is_ret }) catch |err| switch (err) {
        error.NotCoercible => unreachable,
        else => |e| return e,
    };
    const maybe_operand_val = try sema.resolveMaybeUndefVal(operand);

    const runtime_src = if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| rs: {
        const operand_val = maybe_operand_val orelse {
            try sema.checkPtrIsNotComptimeMutable(block, ptr_val, ptr_src, operand_src);
            break :rs operand_src;
        };
        if (ptr_val.isComptimeMutablePtr()) {
            try sema.storePtrVal(block, src, ptr_val, operand_val, elem_ty);
            return;
        } else break :rs ptr_src;
    } else ptr_src;

    // We do this after the possible comptime store above, for the case of field_ptr stores
    // to unions because we want the comptime tag to be set, even if the field type is void.
    if ((try sema.typeHasOnePossibleValue(elem_ty)) != null)
        return;

    if (air_tag == .bitcast) {
        // `air_tag == .bitcast` is used as a special case for `zirCoerceResultPtr`
        // to avoid calling `requireRuntimeBlock` for the dummy block.
        _ = try block.addBinOp(.store, ptr, operand);
        return;
    }

    try sema.requireRuntimeBlock(block, src, runtime_src);
    try sema.queueFullTypeResolution(elem_ty);

    if (ptr_ty.ptrInfo().data.vector_index == .runtime) {
        const ptr_inst = Air.refToIndex(ptr).?;
        const air_tags = sema.air_instructions.items(.tag);
        if (air_tags[ptr_inst] == .ptr_elem_ptr) {
            const ty_pl = sema.air_instructions.items(.data)[ptr_inst].ty_pl;
            const bin_op = sema.getTmpAir().extraData(Air.Bin, ty_pl.payload).data;
            _ = try block.addInst(.{
                .tag = .vector_store_elem,
                .data = .{ .vector_store_elem = .{
                    .vector_ptr = bin_op.lhs,
                    .payload = try block.sema.addExtra(Air.Bin{
                        .lhs = bin_op.rhs,
                        .rhs = operand,
                    }),
                } },
            });
            return;
        }
        return sema.fail(block, ptr_src, "unable to determine vector element index of type '{}'", .{
            ptr_ty.fmt(sema.mod),
        });
    }

    if (is_ret) {
        _ = try block.addBinOp(.store, ptr, operand);
    } else {
        _ = try block.addBinOp(air_tag, ptr, operand);
    }
}

/// Traverse an arbitrary number of bitcasted pointers and return the underyling vector
/// pointer. Only if the final element type matches the vector element type, and the
/// lengths match.
fn obtainBitCastedVectorPtr(sema: *Sema, ptr: Air.Inst.Ref) ?Air.Inst.Ref {
    const array_ty = sema.typeOf(ptr).childType();
    if (array_ty.zigTypeTag() != .Array) return null;
    var ptr_inst = Air.refToIndex(ptr) orelse return null;
    const air_datas = sema.air_instructions.items(.data);
    const air_tags = sema.air_instructions.items(.tag);
    const prev_ptr = while (air_tags[ptr_inst] == .bitcast) {
        const prev_ptr = air_datas[ptr_inst].ty_op.operand;
        const prev_ptr_ty = sema.typeOf(prev_ptr);
        const prev_ptr_child_ty = switch (prev_ptr_ty.tag()) {
            .single_mut_pointer => prev_ptr_ty.castTag(.single_mut_pointer).?.data,
            .pointer => prev_ptr_ty.castTag(.pointer).?.data.pointee_type,
            else => return null,
        };
        if (prev_ptr_child_ty.zigTypeTag() == .Vector) break prev_ptr;
        ptr_inst = Air.refToIndex(prev_ptr) orelse return null;
    } else return null;

    // We have a pointer-to-array and a pointer-to-vector. If the elements and
    // lengths match, return the result.
    const vector_ty = sema.typeOf(prev_ptr).childType();
    if (array_ty.childType().eql(vector_ty.childType(), sema.mod) and
        array_ty.arrayLen() == vector_ty.vectorLen())
    {
        return prev_ptr;
    } else {
        return null;
    }
}

/// Call when you have Value objects rather than Air instructions, and you want to
/// assert the store must be done at comptime.
fn storePtrVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr_val: Value,
    operand_val: Value,
    operand_ty: Type,
) !void {
    var mut_kit = try sema.beginComptimePtrMutation(block, src, ptr_val, operand_ty);
    try sema.checkComptimeVarStore(block, src, mut_kit.decl_ref_mut);

    switch (mut_kit.pointee) {
        .direct => |val_ptr| {
            if (mut_kit.decl_ref_mut.runtime_index == .comptime_field_ptr) {
                if (!operand_val.eql(val_ptr.*, operand_ty, sema.mod)) {
                    // TODO use failWithInvalidComptimeFieldStore
                    return sema.fail(block, src, "value stored in comptime field does not match the default value of the field", .{});
                }
                return;
            }
            const arena = mut_kit.beginArena(sema.mod);
            defer mut_kit.finishArena(sema.mod);

            val_ptr.* = try operand_val.copy(arena);
        },
        .reinterpret => |reinterpret| {
            const target = sema.mod.getTarget();
            const abi_size = try sema.usizeCast(block, src, mut_kit.ty.abiSize(target));
            const buffer = try sema.gpa.alloc(u8, abi_size);
            defer sema.gpa.free(buffer);
            reinterpret.val_ptr.*.writeToMemory(mut_kit.ty, sema.mod, buffer) catch |err| switch (err) {
                error.ReinterpretDeclRef => unreachable,
            };
            operand_val.writeToMemory(operand_ty, sema.mod, buffer[reinterpret.byte_offset..]) catch |err| switch (err) {
                error.ReinterpretDeclRef => unreachable,
            };

            const arena = mut_kit.beginArena(sema.mod);
            defer mut_kit.finishArena(sema.mod);

            reinterpret.val_ptr.* = try Value.readFromMemory(mut_kit.ty, sema.mod, buffer, arena);
        },
        .bad_decl_ty, .bad_ptr_ty => {
            // TODO show the decl declaration site in a note and explain whether the decl
            // or the pointer is the problematic type
            return sema.fail(block, src, "comptime mutation of a reinterpreted pointer requires type '{}' to have a well-defined memory layout", .{mut_kit.ty.fmt(sema.mod)});
        },
    }
}

const ComptimePtrMutationKit = struct {
    decl_ref_mut: Value.Payload.DeclRefMut.Data,
    pointee: union(enum) {
        /// The pointer type matches the actual comptime Value so a direct
        /// modification is possible.
        direct: *Value,
        /// The largest parent Value containing pointee and having a well-defined memory layout.
        /// This is used for bitcasting, if direct dereferencing failed.
        reinterpret: struct {
            val_ptr: *Value,
            byte_offset: usize,
        },
        /// If the root decl could not be used as parent, this means `ty` is the type that
        /// caused that by not having a well-defined layout.
        /// This one means the Decl that owns the value trying to be modified does not
        /// have a well defined memory layout.
        bad_decl_ty,
        /// If the root decl could not be used as parent, this means `ty` is the type that
        /// caused that by not having a well-defined layout.
        /// This one means the pointer type that is being stored through does not
        /// have a well defined memory layout.
        bad_ptr_ty,
    },
    ty: Type,
    decl_arena: std.heap.ArenaAllocator = undefined,

    fn beginArena(self: *ComptimePtrMutationKit, mod: *Module) Allocator {
        const decl = mod.declPtr(self.decl_ref_mut.decl_index);
        self.decl_arena = decl.value_arena.?.promote(mod.gpa);
        return self.decl_arena.allocator();
    }

    fn finishArena(self: *ComptimePtrMutationKit, mod: *Module) void {
        const decl = mod.declPtr(self.decl_ref_mut.decl_index);
        decl.value_arena.?.* = self.decl_arena.state;
        self.decl_arena = undefined;
    }
};

fn beginComptimePtrMutation(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr_val: Value,
    ptr_elem_ty: Type,
) CompileError!ComptimePtrMutationKit {
    const target = sema.mod.getTarget();
    switch (ptr_val.tag()) {
        .decl_ref_mut => {
            const decl_ref_mut = ptr_val.castTag(.decl_ref_mut).?.data;
            const decl = sema.mod.declPtr(decl_ref_mut.decl_index);
            return sema.beginComptimePtrMutationInner(block, src, decl.ty, &decl.val, ptr_elem_ty, decl_ref_mut);
        },
        .comptime_field_ptr => {
            const payload = ptr_val.castTag(.comptime_field_ptr).?.data;
            const duped = try sema.arena.create(Value);
            duped.* = payload.field_val;
            return sema.beginComptimePtrMutationInner(block, src, payload.field_ty, duped, ptr_elem_ty, .{
                .decl_index = @intToEnum(Module.Decl.Index, 0),
                .runtime_index = .comptime_field_ptr,
            });
        },
        .elem_ptr => {
            const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
            var parent = try sema.beginComptimePtrMutation(block, src, elem_ptr.array_ptr, elem_ptr.elem_ty);
            switch (parent.pointee) {
                .direct => |val_ptr| switch (parent.ty.zigTypeTag()) {
                    .Array, .Vector => {
                        const check_len = parent.ty.arrayLenIncludingSentinel();
                        if (elem_ptr.index >= check_len) {
                            // TODO have the parent include the decl so we can say "declared here"
                            return sema.fail(block, src, "comptime store of index {d} out of bounds of array length {d}", .{
                                elem_ptr.index, check_len,
                            });
                        }
                        const elem_ty = parent.ty.childType();

                        // We might have a pointer to multiple elements of the array (e.g. a pointer
                        // to a sub-array). In this case, we just have to reinterpret the relevant
                        // bytes of the whole array rather than any single element.
                        const elem_abi_size_u64 = try sema.typeAbiSize(elem_ptr.elem_ty);
                        if (elem_abi_size_u64 < try sema.typeAbiSize(ptr_elem_ty)) {
                            const elem_abi_size = try sema.usizeCast(block, src, elem_abi_size_u64);
                            return .{
                                .decl_ref_mut = parent.decl_ref_mut,
                                .pointee = .{ .reinterpret = .{
                                    .val_ptr = val_ptr,
                                    .byte_offset = elem_abi_size * elem_ptr.index,
                                } },
                                .ty = parent.ty,
                            };
                        }

                        switch (val_ptr.tag()) {
                            .undef => {
                                // An array has been initialized to undefined at comptime and now we
                                // are for the first time setting an element. We must change the representation
                                // of the array from `undef` to `array`.
                                const arena = parent.beginArena(sema.mod);
                                defer parent.finishArena(sema.mod);

                                const array_len_including_sentinel =
                                    try sema.usizeCast(block, src, parent.ty.arrayLenIncludingSentinel());
                                const elems = try arena.alloc(Value, array_len_including_sentinel);
                                mem.set(Value, elems, Value.undef);

                                val_ptr.* = try Value.Tag.aggregate.create(arena, elems);

                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    elem_ty,
                                    &elems[elem_ptr.index],
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },
                            .bytes => {
                                // An array is memory-optimized to store a slice of bytes, but we are about
                                // to modify an individual field and the representation has to change.
                                // If we wanted to avoid this, there would need to be special detection
                                // elsewhere to identify when writing a value to an array element that is stored
                                // using the `bytes` tag, and handle it without making a call to this function.
                                const arena = parent.beginArena(sema.mod);
                                defer parent.finishArena(sema.mod);

                                const bytes = val_ptr.castTag(.bytes).?.data;
                                const dest_len = parent.ty.arrayLenIncludingSentinel();
                                // bytes.len may be one greater than dest_len because of the case when
                                // assigning `[N:S]T` to `[N]T`. This is allowed; the sentinel is omitted.
                                assert(bytes.len >= dest_len);
                                const elems = try arena.alloc(Value, @intCast(usize, dest_len));
                                for (elems, 0..) |*elem, i| {
                                    elem.* = try Value.Tag.int_u64.create(arena, bytes[i]);
                                }

                                val_ptr.* = try Value.Tag.aggregate.create(arena, elems);

                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    elem_ty,
                                    &elems[elem_ptr.index],
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },
                            .str_lit => {
                                // An array is memory-optimized to store a slice of bytes, but we are about
                                // to modify an individual field and the representation has to change.
                                // If we wanted to avoid this, there would need to be special detection
                                // elsewhere to identify when writing a value to an array element that is stored
                                // using the `str_lit` tag, and handle it without making a call to this function.
                                const arena = parent.beginArena(sema.mod);
                                defer parent.finishArena(sema.mod);

                                const str_lit = val_ptr.castTag(.str_lit).?.data;
                                const dest_len = parent.ty.arrayLenIncludingSentinel();
                                const bytes = sema.mod.string_literal_bytes.items[str_lit.index..][0..str_lit.len];
                                const elems = try arena.alloc(Value, @intCast(usize, dest_len));
                                for (bytes, 0..) |byte, i| {
                                    elems[i] = try Value.Tag.int_u64.create(arena, byte);
                                }
                                if (parent.ty.sentinel()) |sent_val| {
                                    assert(elems.len == bytes.len + 1);
                                    elems[bytes.len] = sent_val;
                                }

                                val_ptr.* = try Value.Tag.aggregate.create(arena, elems);

                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    elem_ty,
                                    &elems[elem_ptr.index],
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },
                            .repeated => {
                                // An array is memory-optimized to store only a single element value, and
                                // that value is understood to be the same for the entire length of the array.
                                // However, now we want to modify an individual field and so the
                                // representation has to change.  If we wanted to avoid this, there would
                                // need to be special detection elsewhere to identify when writing a value to an
                                // array element that is stored using the `repeated` tag, and handle it
                                // without making a call to this function.
                                const arena = parent.beginArena(sema.mod);
                                defer parent.finishArena(sema.mod);

                                const repeated_val = try val_ptr.castTag(.repeated).?.data.copy(arena);
                                const array_len_including_sentinel =
                                    try sema.usizeCast(block, src, parent.ty.arrayLenIncludingSentinel());
                                const elems = try arena.alloc(Value, array_len_including_sentinel);
                                if (elems.len > 0) elems[0] = repeated_val;
                                for (elems[1..]) |*elem| {
                                    elem.* = try repeated_val.copy(arena);
                                }

                                val_ptr.* = try Value.Tag.aggregate.create(arena, elems);

                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    elem_ty,
                                    &elems[elem_ptr.index],
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },

                            .aggregate => return beginComptimePtrMutationInner(
                                sema,
                                block,
                                src,
                                elem_ty,
                                &val_ptr.castTag(.aggregate).?.data[elem_ptr.index],
                                ptr_elem_ty,
                                parent.decl_ref_mut,
                            ),

                            .the_only_possible_value => {
                                const duped = try sema.arena.create(Value);
                                duped.* = Value.initTag(.the_only_possible_value);
                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    elem_ty,
                                    duped,
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },

                            else => unreachable,
                        }
                    },
                    else => {
                        if (elem_ptr.index != 0) {
                            // TODO include a "declared here" note for the decl
                            return sema.fail(block, src, "out of bounds comptime store of index {d}", .{
                                elem_ptr.index,
                            });
                        }
                        return beginComptimePtrMutationInner(
                            sema,
                            block,
                            src,
                            parent.ty,
                            val_ptr,
                            ptr_elem_ty,
                            parent.decl_ref_mut,
                        );
                    },
                },
                .reinterpret => |reinterpret| {
                    if (!elem_ptr.elem_ty.hasWellDefinedLayout()) {
                        // Even though the parent value type has well-defined memory layout, our
                        // pointer type does not.
                        return ComptimePtrMutationKit{
                            .decl_ref_mut = parent.decl_ref_mut,
                            .pointee = .bad_ptr_ty,
                            .ty = elem_ptr.elem_ty,
                        };
                    }

                    const elem_abi_size_u64 = try sema.typeAbiSize(elem_ptr.elem_ty);
                    const elem_abi_size = try sema.usizeCast(block, src, elem_abi_size_u64);
                    return ComptimePtrMutationKit{
                        .decl_ref_mut = parent.decl_ref_mut,
                        .pointee = .{ .reinterpret = .{
                            .val_ptr = reinterpret.val_ptr,
                            .byte_offset = reinterpret.byte_offset + elem_abi_size * elem_ptr.index,
                        } },
                        .ty = parent.ty,
                    };
                },
                .bad_decl_ty, .bad_ptr_ty => return parent,
            }
        },
        .field_ptr => {
            const field_ptr = ptr_val.castTag(.field_ptr).?.data;
            const field_index = @intCast(u32, field_ptr.field_index);

            var parent = try sema.beginComptimePtrMutation(block, src, field_ptr.container_ptr, field_ptr.container_ty);
            switch (parent.pointee) {
                .direct => |val_ptr| switch (val_ptr.tag()) {
                    .undef => {
                        // A struct or union has been initialized to undefined at comptime and now we
                        // are for the first time setting a field. We must change the representation
                        // of the struct/union from `undef` to `struct`/`union`.
                        const arena = parent.beginArena(sema.mod);
                        defer parent.finishArena(sema.mod);

                        switch (parent.ty.zigTypeTag()) {
                            .Struct => {
                                const fields = try arena.alloc(Value, parent.ty.structFieldCount());
                                mem.set(Value, fields, Value.undef);

                                val_ptr.* = try Value.Tag.aggregate.create(arena, fields);

                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    parent.ty.structFieldType(field_index),
                                    &fields[field_index],
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },
                            .Union => {
                                const payload = try arena.create(Value.Payload.Union);
                                payload.* = .{ .data = .{
                                    .tag = try Value.Tag.enum_field_index.create(arena, field_index),
                                    .val = Value.undef,
                                } };

                                val_ptr.* = Value.initPayload(&payload.base);

                                return beginComptimePtrMutationInner(
                                    sema,
                                    block,
                                    src,
                                    parent.ty.structFieldType(field_index),
                                    &payload.data.val,
                                    ptr_elem_ty,
                                    parent.decl_ref_mut,
                                );
                            },
                            .Pointer => {
                                assert(parent.ty.isSlice());
                                val_ptr.* = try Value.Tag.slice.create(arena, .{
                                    .ptr = Value.undef,
                                    .len = Value.undef,
                                });

                                switch (field_index) {
                                    Value.Payload.Slice.ptr_index => return beginComptimePtrMutationInner(
                                        sema,
                                        block,
                                        src,
                                        parent.ty.slicePtrFieldType(try sema.arena.create(Type.SlicePtrFieldTypeBuffer)),
                                        &val_ptr.castTag(.slice).?.data.ptr,
                                        ptr_elem_ty,
                                        parent.decl_ref_mut,
                                    ),
                                    Value.Payload.Slice.len_index => return beginComptimePtrMutationInner(
                                        sema,
                                        block,
                                        src,
                                        Type.usize,
                                        &val_ptr.castTag(.slice).?.data.len,
                                        ptr_elem_ty,
                                        parent.decl_ref_mut,
                                    ),

                                    else => unreachable,
                                }
                            },
                            else => unreachable,
                        }
                    },
                    .aggregate => return beginComptimePtrMutationInner(
                        sema,
                        block,
                        src,
                        parent.ty.structFieldType(field_index),
                        &val_ptr.castTag(.aggregate).?.data[field_index],
                        ptr_elem_ty,
                        parent.decl_ref_mut,
                    ),

                    .@"union" => {
                        // We need to set the active field of the union.
                        const arena = parent.beginArena(sema.mod);
                        defer parent.finishArena(sema.mod);

                        const payload = &val_ptr.castTag(.@"union").?.data;
                        payload.tag = try Value.Tag.enum_field_index.create(arena, field_index);

                        return beginComptimePtrMutationInner(
                            sema,
                            block,
                            src,
                            parent.ty.structFieldType(field_index),
                            &payload.val,
                            ptr_elem_ty,
                            parent.decl_ref_mut,
                        );
                    },
                    .slice => switch (field_index) {
                        Value.Payload.Slice.ptr_index => return beginComptimePtrMutationInner(
                            sema,
                            block,
                            src,
                            parent.ty.slicePtrFieldType(try sema.arena.create(Type.SlicePtrFieldTypeBuffer)),
                            &val_ptr.castTag(.slice).?.data.ptr,
                            ptr_elem_ty,
                            parent.decl_ref_mut,
                        ),

                        Value.Payload.Slice.len_index => return beginComptimePtrMutationInner(
                            sema,
                            block,
                            src,
                            Type.usize,
                            &val_ptr.castTag(.slice).?.data.len,
                            ptr_elem_ty,
                            parent.decl_ref_mut,
                        ),

                        else => unreachable,
                    },

                    .empty_struct_value => {
                        const duped = try sema.arena.create(Value);
                        duped.* = Value.initTag(.the_only_possible_value);
                        return beginComptimePtrMutationInner(
                            sema,
                            block,
                            src,
                            parent.ty.structFieldType(field_index),
                            duped,
                            ptr_elem_ty,
                            parent.decl_ref_mut,
                        );
                    },

                    else => unreachable,
                },
                .reinterpret => |reinterpret| {
                    const field_offset_u64 = field_ptr.container_ty.structFieldOffset(field_index, target);
                    const field_offset = try sema.usizeCast(block, src, field_offset_u64);
                    return ComptimePtrMutationKit{
                        .decl_ref_mut = parent.decl_ref_mut,
                        .pointee = .{ .reinterpret = .{
                            .val_ptr = reinterpret.val_ptr,
                            .byte_offset = reinterpret.byte_offset + field_offset,
                        } },
                        .ty = parent.ty,
                    };
                },
                .bad_decl_ty, .bad_ptr_ty => return parent,
            }
        },
        .eu_payload_ptr => {
            const eu_ptr = ptr_val.castTag(.eu_payload_ptr).?.data;
            var parent = try sema.beginComptimePtrMutation(block, src, eu_ptr.container_ptr, eu_ptr.container_ty);
            switch (parent.pointee) {
                .direct => |val_ptr| {
                    const payload_ty = parent.ty.errorUnionPayload();
                    switch (val_ptr.tag()) {
                        else => {
                            // An error union has been initialized to undefined at comptime and now we
                            // are for the first time setting the payload. We must change the
                            // representation of the error union from `undef` to `opt_payload`.
                            const arena = parent.beginArena(sema.mod);
                            defer parent.finishArena(sema.mod);

                            const payload = try arena.create(Value.Payload.SubValue);
                            payload.* = .{
                                .base = .{ .tag = .eu_payload },
                                .data = Value.undef,
                            };

                            val_ptr.* = Value.initPayload(&payload.base);

                            return ComptimePtrMutationKit{
                                .decl_ref_mut = parent.decl_ref_mut,
                                .pointee = .{ .direct = &payload.data },
                                .ty = payload_ty,
                            };
                        },
                        .eu_payload => return ComptimePtrMutationKit{
                            .decl_ref_mut = parent.decl_ref_mut,
                            .pointee = .{ .direct = &val_ptr.castTag(.eu_payload).?.data },
                            .ty = payload_ty,
                        },
                    }
                },
                .bad_decl_ty, .bad_ptr_ty => return parent,
                // Even though the parent value type has well-defined memory layout, our
                // pointer type does not.
                .reinterpret => return ComptimePtrMutationKit{
                    .decl_ref_mut = parent.decl_ref_mut,
                    .pointee = .bad_ptr_ty,
                    .ty = eu_ptr.container_ty,
                },
            }
        },
        .opt_payload_ptr => {
            const opt_ptr = if (ptr_val.castTag(.opt_payload_ptr)) |some| some.data else {
                return sema.beginComptimePtrMutation(block, src, ptr_val, try ptr_elem_ty.optionalChildAlloc(sema.arena));
            };
            var parent = try sema.beginComptimePtrMutation(block, src, opt_ptr.container_ptr, opt_ptr.container_ty);
            switch (parent.pointee) {
                .direct => |val_ptr| {
                    const payload_ty = try parent.ty.optionalChildAlloc(sema.arena);
                    switch (val_ptr.tag()) {
                        .undef, .null_value => {
                            // An optional has been initialized to undefined at comptime and now we
                            // are for the first time setting the payload. We must change the
                            // representation of the optional from `undef` to `opt_payload`.
                            const arena = parent.beginArena(sema.mod);
                            defer parent.finishArena(sema.mod);

                            const payload = try arena.create(Value.Payload.SubValue);
                            payload.* = .{
                                .base = .{ .tag = .opt_payload },
                                .data = Value.undef,
                            };

                            val_ptr.* = Value.initPayload(&payload.base);

                            return ComptimePtrMutationKit{
                                .decl_ref_mut = parent.decl_ref_mut,
                                .pointee = .{ .direct = &payload.data },
                                .ty = payload_ty,
                            };
                        },
                        .opt_payload => return ComptimePtrMutationKit{
                            .decl_ref_mut = parent.decl_ref_mut,
                            .pointee = .{ .direct = &val_ptr.castTag(.opt_payload).?.data },
                            .ty = payload_ty,
                        },

                        else => return ComptimePtrMutationKit{
                            .decl_ref_mut = parent.decl_ref_mut,
                            .pointee = .{ .direct = val_ptr },
                            .ty = payload_ty,
                        },
                    }
                },
                .bad_decl_ty, .bad_ptr_ty => return parent,
                // Even though the parent value type has well-defined memory layout, our
                // pointer type does not.
                .reinterpret => return ComptimePtrMutationKit{
                    .decl_ref_mut = parent.decl_ref_mut,
                    .pointee = .bad_ptr_ty,
                    .ty = opt_ptr.container_ty,
                },
            }
        },
        .decl_ref => unreachable, // isComptimeMutablePtr() has been checked already
        else => unreachable,
    }
}

fn beginComptimePtrMutationInner(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    decl_ty: Type,
    decl_val: *Value,
    ptr_elem_ty: Type,
    decl_ref_mut: Value.Payload.DeclRefMut.Data,
) CompileError!ComptimePtrMutationKit {
    const target = sema.mod.getTarget();
    const coerce_ok = (try sema.coerceInMemoryAllowed(block, ptr_elem_ty, decl_ty, true, target, src, src)) == .ok;
    if (coerce_ok) {
        return ComptimePtrMutationKit{
            .decl_ref_mut = decl_ref_mut,
            .pointee = .{ .direct = decl_val },
            .ty = decl_ty,
        };
    }

    // Handle the case that the decl is an array and we're actually trying to point to an element.
    if (decl_ty.isArrayOrVector()) {
        const decl_elem_ty = decl_ty.childType();
        if ((try sema.coerceInMemoryAllowed(block, ptr_elem_ty, decl_elem_ty, true, target, src, src)) == .ok) {
            return ComptimePtrMutationKit{
                .decl_ref_mut = decl_ref_mut,
                .pointee = .{ .direct = decl_val },
                .ty = decl_ty,
            };
        }
    }

    if (!decl_ty.hasWellDefinedLayout()) {
        return ComptimePtrMutationKit{
            .decl_ref_mut = decl_ref_mut,
            .pointee = .{ .bad_decl_ty = {} },
            .ty = decl_ty,
        };
    }
    if (!ptr_elem_ty.hasWellDefinedLayout()) {
        return ComptimePtrMutationKit{
            .decl_ref_mut = decl_ref_mut,
            .pointee = .{ .bad_ptr_ty = {} },
            .ty = ptr_elem_ty,
        };
    }
    return ComptimePtrMutationKit{
        .decl_ref_mut = decl_ref_mut,
        .pointee = .{ .reinterpret = .{
            .val_ptr = decl_val,
            .byte_offset = 0,
        } },
        .ty = decl_ty,
    };
}

const TypedValueAndOffset = struct {
    tv: TypedValue,
    byte_offset: usize,
};

const ComptimePtrLoadKit = struct {
    /// The Value and Type corresponding to the pointee of the provided pointer.
    /// If a direct dereference is not possible, this is null.
    pointee: ?TypedValue,
    /// The largest parent Value containing `pointee` and having a well-defined memory layout.
    /// This is used for bitcasting, if direct dereferencing failed (i.e. `pointee` is null).
    parent: ?TypedValueAndOffset,
    /// Whether the `pointee` could be mutated by further
    /// semantic analysis and a copy must be performed.
    is_mutable: bool,
    /// If the root decl could not be used as `parent`, this is the type that
    /// caused that by not having a well-defined layout
    ty_without_well_defined_layout: ?Type,
};

const ComptimePtrLoadError = CompileError || error{
    RuntimeLoad,
};

/// If `maybe_array_ty` is provided, it will be used to directly dereference an
/// .elem_ptr of type T to a value of [N]T, if necessary.
fn beginComptimePtrLoad(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr_val: Value,
    maybe_array_ty: ?Type,
) ComptimePtrLoadError!ComptimePtrLoadKit {
    const target = sema.mod.getTarget();
    var deref: ComptimePtrLoadKit = switch (ptr_val.tag()) {
        .decl_ref,
        .decl_ref_mut,
        => blk: {
            const decl_index = switch (ptr_val.tag()) {
                .decl_ref => ptr_val.castTag(.decl_ref).?.data,
                .decl_ref_mut => ptr_val.castTag(.decl_ref_mut).?.data.decl_index,
                else => unreachable,
            };
            const is_mutable = ptr_val.tag() == .decl_ref_mut;
            const decl = sema.mod.declPtr(decl_index);
            const decl_tv = try decl.typedValue();
            if (decl_tv.val.tag() == .variable) return error.RuntimeLoad;

            const layout_defined = decl.ty.hasWellDefinedLayout();
            break :blk ComptimePtrLoadKit{
                .parent = if (layout_defined) .{ .tv = decl_tv, .byte_offset = 0 } else null,
                .pointee = decl_tv,
                .is_mutable = is_mutable,
                .ty_without_well_defined_layout = if (!layout_defined) decl.ty else null,
            };
        },

        .elem_ptr => blk: {
            const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
            const elem_ty = elem_ptr.elem_ty;
            var deref = try sema.beginComptimePtrLoad(block, src, elem_ptr.array_ptr, null);

            // This code assumes that elem_ptrs have been "flattened" in order for direct dereference
            // to succeed, meaning that elem ptrs of the same elem_ty are coalesced. Here we check that
            // our parent is not an elem_ptr with the same elem_ty, since that would be "unflattened"
            if (elem_ptr.array_ptr.castTag(.elem_ptr)) |parent_elem_ptr| {
                assert(!(parent_elem_ptr.data.elem_ty.eql(elem_ty, sema.mod)));
            }

            if (elem_ptr.index != 0) {
                if (elem_ty.hasWellDefinedLayout()) {
                    if (deref.parent) |*parent| {
                        // Update the byte offset (in-place)
                        const elem_size = try sema.typeAbiSize(elem_ty);
                        const offset = parent.byte_offset + elem_size * elem_ptr.index;
                        parent.byte_offset = try sema.usizeCast(block, src, offset);
                    }
                } else {
                    deref.parent = null;
                    deref.ty_without_well_defined_layout = elem_ty;
                }
            }

            // If we're loading an elem_ptr that was derived from a different type
            // than the true type of the underlying decl, we cannot deref directly
            const ty_matches = if (deref.pointee != null and deref.pointee.?.ty.isArrayOrVector()) x: {
                const deref_elem_ty = deref.pointee.?.ty.childType();
                break :x (try sema.coerceInMemoryAllowed(block, deref_elem_ty, elem_ty, false, target, src, src)) == .ok or
                    (try sema.coerceInMemoryAllowed(block, elem_ty, deref_elem_ty, false, target, src, src)) == .ok;
            } else false;
            if (!ty_matches) {
                deref.pointee = null;
                break :blk deref;
            }

            var array_tv = deref.pointee.?;
            const check_len = array_tv.ty.arrayLenIncludingSentinel();
            if (maybe_array_ty) |load_ty| {
                // It's possible that we're loading a [N]T, in which case we'd like to slice
                // the pointee array directly from our parent array.
                if (load_ty.isArrayOrVector() and load_ty.childType().eql(elem_ty, sema.mod)) {
                    const N = try sema.usizeCast(block, src, load_ty.arrayLenIncludingSentinel());
                    deref.pointee = if (elem_ptr.index + N <= check_len) TypedValue{
                        .ty = try Type.array(sema.arena, N, null, elem_ty, sema.mod),
                        .val = try array_tv.val.sliceArray(sema.mod, sema.arena, elem_ptr.index, elem_ptr.index + N),
                    } else null;
                    break :blk deref;
                }
            }

            if (elem_ptr.index >= check_len) {
                deref.pointee = null;
                break :blk deref;
            }
            if (elem_ptr.index == check_len - 1) {
                if (array_tv.ty.sentinel()) |sent| {
                    deref.pointee = TypedValue{
                        .ty = elem_ty,
                        .val = sent,
                    };
                    break :blk deref;
                }
            }
            deref.pointee = TypedValue{
                .ty = elem_ty,
                .val = try array_tv.val.elemValue(sema.mod, sema.arena, elem_ptr.index),
            };
            break :blk deref;
        },

        .slice => blk: {
            const slice = ptr_val.castTag(.slice).?.data;
            break :blk try sema.beginComptimePtrLoad(block, src, slice.ptr, null);
        },

        .field_ptr => blk: {
            const field_ptr = ptr_val.castTag(.field_ptr).?.data;
            const field_index = @intCast(u32, field_ptr.field_index);
            var deref = try sema.beginComptimePtrLoad(block, src, field_ptr.container_ptr, field_ptr.container_ty);

            if (field_ptr.container_ty.hasWellDefinedLayout()) {
                const struct_ty = field_ptr.container_ty.castTag(.@"struct");
                if (struct_ty != null and struct_ty.?.data.layout == .Packed) {
                    // packed structs are not byte addressable
                    deref.parent = null;
                } else if (deref.parent) |*parent| {
                    // Update the byte offset (in-place)
                    try sema.resolveTypeLayout(field_ptr.container_ty);
                    const field_offset = field_ptr.container_ty.structFieldOffset(field_index, target);
                    parent.byte_offset = try sema.usizeCast(block, src, parent.byte_offset + field_offset);
                }
            } else {
                deref.parent = null;
                deref.ty_without_well_defined_layout = field_ptr.container_ty;
            }

            const tv = deref.pointee orelse {
                deref.pointee = null;
                break :blk deref;
            };
            const coerce_in_mem_ok =
                (try sema.coerceInMemoryAllowed(block, field_ptr.container_ty, tv.ty, false, target, src, src)) == .ok or
                (try sema.coerceInMemoryAllowed(block, tv.ty, field_ptr.container_ty, false, target, src, src)) == .ok;
            if (!coerce_in_mem_ok) {
                deref.pointee = null;
                break :blk deref;
            }

            if (field_ptr.container_ty.isSlice()) {
                const slice_val = tv.val.castTag(.slice).?.data;
                deref.pointee = switch (field_index) {
                    Value.Payload.Slice.ptr_index => TypedValue{
                        .ty = field_ptr.container_ty.slicePtrFieldType(try sema.arena.create(Type.SlicePtrFieldTypeBuffer)),
                        .val = slice_val.ptr,
                    },
                    Value.Payload.Slice.len_index => TypedValue{
                        .ty = Type.usize,
                        .val = slice_val.len,
                    },
                    else => unreachable,
                };
            } else {
                const field_ty = field_ptr.container_ty.structFieldType(field_index);
                deref.pointee = TypedValue{
                    .ty = field_ty,
                    .val = tv.val.fieldValue(tv.ty, field_index),
                };
            }
            break :blk deref;
        },

        .comptime_field_ptr => blk: {
            const comptime_field_ptr = ptr_val.castTag(.comptime_field_ptr).?.data;
            break :blk ComptimePtrLoadKit{
                .parent = null,
                .pointee = .{ .ty = comptime_field_ptr.field_ty, .val = comptime_field_ptr.field_val },
                .is_mutable = false,
                .ty_without_well_defined_layout = comptime_field_ptr.field_ty,
            };
        },

        .opt_payload_ptr,
        .eu_payload_ptr,
        => blk: {
            const payload_ptr = ptr_val.cast(Value.Payload.PayloadPtr).?.data;
            const payload_ty = switch (ptr_val.tag()) {
                .eu_payload_ptr => payload_ptr.container_ty.errorUnionPayload(),
                .opt_payload_ptr => try payload_ptr.container_ty.optionalChildAlloc(sema.arena),
                else => unreachable,
            };
            var deref = try sema.beginComptimePtrLoad(block, src, payload_ptr.container_ptr, payload_ptr.container_ty);

            // eu_payload_ptr and opt_payload_ptr never have a well-defined layout
            if (deref.parent != null) {
                deref.parent = null;
                deref.ty_without_well_defined_layout = payload_ptr.container_ty;
            }

            if (deref.pointee) |*tv| {
                const coerce_in_mem_ok =
                    (try sema.coerceInMemoryAllowed(block, payload_ptr.container_ty, tv.ty, false, target, src, src)) == .ok or
                    (try sema.coerceInMemoryAllowed(block, tv.ty, payload_ptr.container_ty, false, target, src, src)) == .ok;
                if (coerce_in_mem_ok) {
                    const payload_val = switch (ptr_val.tag()) {
                        .eu_payload_ptr => if (tv.val.castTag(.eu_payload)) |some| some.data else {
                            return sema.fail(block, src, "attempt to unwrap error: {s}", .{tv.val.castTag(.@"error").?.data.name});
                        },
                        .opt_payload_ptr => if (tv.val.castTag(.opt_payload)) |some| some.data else opt: {
                            if (tv.val.isNull()) return sema.fail(block, src, "attempt to use null value", .{});
                            break :opt tv.val;
                        },
                        else => unreachable,
                    };
                    tv.* = TypedValue{ .ty = payload_ty, .val = payload_val };
                    break :blk deref;
                }
            }
            deref.pointee = null;
            break :blk deref;
        },
        .null_value => {
            return sema.fail(block, src, "attempt to use null value", .{});
        },
        .opt_payload => blk: {
            const opt_payload = ptr_val.castTag(.opt_payload).?.data;
            break :blk try sema.beginComptimePtrLoad(block, src, opt_payload, null);
        },

        .zero,
        .one,
        .int_u64,
        .int_i64,
        .int_big_positive,
        .int_big_negative,
        .variable,
        .extern_fn,
        .function,
        => return error.RuntimeLoad,

        else => unreachable,
    };

    if (deref.pointee) |tv| {
        if (deref.parent == null and tv.ty.hasWellDefinedLayout()) {
            deref.parent = .{ .tv = tv, .byte_offset = 0 };
        }
    }
    return deref;
}

fn bitCast(
    sema: *Sema,
    block: *Block,
    dest_ty_unresolved: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
    operand_src: ?LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const dest_ty = try sema.resolveTypeFields(dest_ty_unresolved);
    try sema.resolveTypeLayout(dest_ty);

    const old_ty = try sema.resolveTypeFields(sema.typeOf(inst));
    try sema.resolveTypeLayout(old_ty);

    const target = sema.mod.getTarget();
    const dest_bits = dest_ty.bitSize(target);
    const old_bits = old_ty.bitSize(target);

    if (old_bits != dest_bits) {
        return sema.fail(block, inst_src, "@bitCast size mismatch: destination type '{}' has {d} bits but source type '{}' has {d} bits", .{
            dest_ty.fmt(sema.mod),
            dest_bits,
            old_ty.fmt(sema.mod),
            old_bits,
        });
    }

    if (try sema.resolveMaybeUndefVal(inst)) |val| {
        if (try sema.bitCastVal(block, inst_src, val, old_ty, dest_ty, 0)) |result_val| {
            return sema.addConstant(dest_ty, result_val);
        }
    }
    try sema.requireRuntimeBlock(block, inst_src, operand_src);
    return block.addBitCast(dest_ty, inst);
}

fn bitCastVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    val: Value,
    old_ty: Type,
    new_ty: Type,
    buffer_offset: usize,
) !?Value {
    const target = sema.mod.getTarget();
    if (old_ty.eql(new_ty, sema.mod)) return val;

    // For types with well-defined memory layouts, we serialize them a byte buffer,
    // then deserialize to the new type.
    const abi_size = try sema.usizeCast(block, src, old_ty.abiSize(target));
    const buffer = try sema.gpa.alloc(u8, abi_size);
    defer sema.gpa.free(buffer);
    val.writeToMemory(old_ty, sema.mod, buffer) catch |err| switch (err) {
        error.ReinterpretDeclRef => return null,
    };
    return try Value.readFromMemory(new_ty, sema.mod, buffer[buffer_offset..], sema.arena);
}

fn coerceArrayPtrToSlice(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    if (try sema.resolveMaybeUndefVal(inst)) |val| {
        const ptr_array_ty = sema.typeOf(inst);
        const array_ty = ptr_array_ty.childType();
        const slice_val = try Value.Tag.slice.create(sema.arena, .{
            .ptr = val,
            .len = try Value.Tag.int_u64.create(sema.arena, array_ty.arrayLen()),
        });
        return sema.addConstant(dest_ty, slice_val);
    }
    try sema.requireRuntimeBlock(block, inst_src, null);
    return block.addTyOp(.array_to_slice, dest_ty, inst);
}

fn checkPtrAttributes(sema: *Sema, dest_ty: Type, inst_ty: Type, in_memory_result: *InMemoryCoercionResult) bool {
    const dest_info = dest_ty.ptrInfo().data;
    const inst_info = inst_ty.ptrInfo().data;
    const len0 = (inst_info.pointee_type.zigTypeTag() == .Array and (inst_info.pointee_type.arrayLenIncludingSentinel() == 0 or
        (inst_info.pointee_type.arrayLen() == 0 and dest_info.sentinel == null and dest_info.size != .C and dest_info.size != .Many))) or
        (inst_info.pointee_type.isTuple() and inst_info.pointee_type.structFieldCount() == 0);

    const ok_cv_qualifiers =
        ((inst_info.mutable or !dest_info.mutable) or len0) and
        (!inst_info.@"volatile" or dest_info.@"volatile");

    if (!ok_cv_qualifiers) {
        in_memory_result.* = .{ .ptr_qualifiers = .{
            .actual_const = !inst_info.mutable,
            .wanted_const = !dest_info.mutable,
            .actual_volatile = inst_info.@"volatile",
            .wanted_volatile = dest_info.@"volatile",
        } };
        return false;
    }
    if (dest_info.@"addrspace" != inst_info.@"addrspace") {
        in_memory_result.* = .{ .ptr_addrspace = .{
            .actual = inst_info.@"addrspace",
            .wanted = dest_info.@"addrspace",
        } };
        return false;
    }
    if (inst_info.@"align" == 0 and dest_info.@"align" == 0) return true;
    if (len0) return true;
    const target = sema.mod.getTarget();

    const inst_align = if (inst_info.@"align" != 0)
        inst_info.@"align"
    else
        inst_info.pointee_type.abiAlignment(target);

    const dest_align = if (dest_info.@"align" != 0)
        dest_info.@"align"
    else
        dest_info.pointee_type.abiAlignment(target);

    if (dest_align > inst_align) {
        in_memory_result.* = .{ .ptr_alignment = .{
            .actual = inst_align,
            .wanted = dest_align,
        } };
        return false;
    }
    return true;
}

fn coerceCompatiblePtrs(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const inst_ty = sema.typeOf(inst);
    if (try sema.resolveMaybeUndefVal(inst)) |val| {
        if (!val.isUndef() and val.isNull() and !dest_ty.isAllowzeroPtr()) {
            return sema.fail(block, inst_src, "null pointer casted to type '{}'", .{dest_ty.fmt(sema.mod)});
        }
        // The comptime Value representation is compatible with both types.
        return sema.addConstant(dest_ty, val);
    }
    try sema.requireRuntimeBlock(block, inst_src, null);
    const inst_allows_zero = inst_ty.zigTypeTag() != .Pointer or inst_ty.ptrAllowsZero();
    if (block.wantSafety() and inst_allows_zero and !dest_ty.ptrAllowsZero() and
        try sema.typeHasRuntimeBits(dest_ty.elemType2()))
    {
        const actual_ptr = if (inst_ty.isSlice())
            try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty)
        else
            inst;
        const ptr_int = try block.addUnOp(.ptrtoint, actual_ptr);
        const is_non_zero = try block.addBinOp(.cmp_neq, ptr_int, .zero_usize);
        const ok = if (inst_ty.isSlice()) ok: {
            const len = try sema.analyzeSliceLen(block, inst_src, inst);
            const len_zero = try block.addBinOp(.cmp_eq, len, .zero_usize);
            break :ok try block.addBinOp(.bit_or, len_zero, is_non_zero);
        } else is_non_zero;
        try sema.addSafetyCheck(block, ok, .cast_to_null);
    }
    return sema.bitCast(block, dest_ty, inst, inst_src, null);
}

fn coerceEnumToUnion(
    sema: *Sema,
    block: *Block,
    union_ty: Type,
    union_ty_src: LazySrcLoc,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const inst_ty = sema.typeOf(inst);

    const tag_ty = union_ty.unionTagType() orelse {
        const msg = msg: {
            const msg = try sema.errMsg(block, inst_src, "expected type '{}', found '{}'", .{
                union_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, union_ty_src, msg, "cannot coerce enum to untagged union", .{});
            try sema.addDeclaredHereNote(msg, union_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    };

    const enum_tag = try sema.coerce(block, tag_ty, inst, inst_src);
    if (try sema.resolveDefinedValue(block, inst_src, enum_tag)) |val| {
        const field_index = union_ty.unionTagFieldIndex(val, sema.mod) orelse {
            const msg = msg: {
                const msg = try sema.errMsg(block, inst_src, "union '{}' has no tag with value '{}'", .{
                    union_ty.fmt(sema.mod), val.fmtValue(tag_ty, sema.mod),
                });
                errdefer msg.destroy(sema.gpa);
                try sema.addDeclaredHereNote(msg, union_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        };

        const union_obj = union_ty.cast(Type.Payload.Union).?.data;
        const field = union_obj.fields.values()[field_index];
        const field_ty = try sema.resolveTypeFields(field.ty);
        if (field_ty.zigTypeTag() == .NoReturn) {
            const msg = msg: {
                const msg = try sema.errMsg(block, inst_src, "cannot initialize 'noreturn' field of union", .{});
                errdefer msg.destroy(sema.gpa);

                const field_name = union_obj.fields.keys()[field_index];
                try sema.addFieldErrNote(union_ty, field_index, msg, "field '{s}' declared here", .{field_name});
                try sema.addDeclaredHereNote(msg, union_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        const opv = (try sema.typeHasOnePossibleValue(field_ty)) orelse {
            const msg = msg: {
                const field_name = union_obj.fields.keys()[field_index];
                const msg = try sema.errMsg(block, inst_src, "coercion from enum '{}' to union '{}' must initialize '{}' field '{s}'", .{
                    inst_ty.fmt(sema.mod), union_ty.fmt(sema.mod), field_ty.fmt(sema.mod), field_name,
                });
                errdefer msg.destroy(sema.gpa);

                try sema.addFieldErrNote(union_ty, field_index, msg, "field '{s}' declared here", .{field_name});
                try sema.addDeclaredHereNote(msg, union_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        };

        return sema.addConstant(union_ty, try Value.Tag.@"union".create(sema.arena, .{
            .tag = val,
            .val = opv,
        }));
    }

    try sema.requireRuntimeBlock(block, inst_src, null);

    if (tag_ty.isNonexhaustiveEnum()) {
        const msg = msg: {
            const msg = try sema.errMsg(block, inst_src, "runtime coercion to union '{}' from non-exhaustive enum", .{
                union_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.addDeclaredHereNote(msg, tag_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const union_obj = union_ty.cast(Type.Payload.Union).?.data;
    {
        var msg: ?*Module.ErrorMsg = null;
        errdefer if (msg) |some| some.destroy(sema.gpa);

        for (union_obj.fields.values(), 0..) |field, i| {
            if (field.ty.zigTypeTag() == .NoReturn) {
                const err_msg = msg orelse try sema.errMsg(
                    block,
                    inst_src,
                    "runtime coercion from enum '{}' to union '{}' which has a 'noreturn' field",
                    .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
                );
                msg = err_msg;

                try sema.addFieldErrNote(union_ty, i, err_msg, "'noreturn' field here", .{});
            }
        }
        if (msg) |some| {
            msg = null;
            try sema.addDeclaredHereNote(some, union_ty);
            return sema.failWithOwnedErrorMsg(some);
        }
    }

    // If the union has all fields 0 bits, the union value is just the enum value.
    if (union_ty.unionHasAllZeroBitFieldTypes()) {
        return block.addBitCast(union_ty, enum_tag);
    }

    const msg = msg: {
        const msg = try sema.errMsg(
            block,
            inst_src,
            "runtime coercion from enum '{}' to union '{}' which has non-void fields",
            .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
        );
        errdefer msg.destroy(sema.gpa);

        var it = union_obj.fields.iterator();
        var field_index: usize = 0;
        while (it.next()) |field| : (field_index += 1) {
            const field_name = field.key_ptr.*;
            const field_ty = field.value_ptr.ty;
            if (!field_ty.hasRuntimeBits()) continue;
            try sema.addFieldErrNote(union_ty, field_index, msg, "field '{s}' has type '{}'", .{ field_name, field_ty.fmt(sema.mod) });
        }
        try sema.addDeclaredHereNote(msg, union_ty);
        break :msg msg;
    };
    return sema.failWithOwnedErrorMsg(msg);
}

fn coerceAnonStructToUnion(
    sema: *Sema,
    block: *Block,
    union_ty: Type,
    union_ty_src: LazySrcLoc,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const inst_ty = sema.typeOf(inst);
    const field_count = inst_ty.structFieldCount();
    if (field_count != 1) {
        const msg = msg: {
            const msg = if (field_count > 1) try sema.errMsg(
                block,
                inst_src,
                "cannot initialize multiple union fields at once, unions can only have one active field",
                .{},
            ) else try sema.errMsg(
                block,
                inst_src,
                "union initializer must initialize one field",
                .{},
            );
            errdefer msg.destroy(sema.gpa);

            // TODO add notes for where the anon struct was created to point out
            // the extra fields.

            try sema.addDeclaredHereNote(msg, union_ty);
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const anon_struct = inst_ty.castTag(.anon_struct).?.data;
    const field_name = anon_struct.names[0];
    const init = try sema.structFieldVal(block, inst_src, inst, field_name, inst_src, inst_ty);
    return sema.unionInit(block, init, inst_src, union_ty, union_ty_src, field_name, inst_src);
}

fn coerceAnonStructToUnionPtrs(
    sema: *Sema,
    block: *Block,
    ptr_union_ty: Type,
    union_ty_src: LazySrcLoc,
    ptr_anon_struct: Air.Inst.Ref,
    anon_struct_src: LazySrcLoc,
) !Air.Inst.Ref {
    const union_ty = ptr_union_ty.childType();
    const anon_struct = try sema.analyzeLoad(block, anon_struct_src, ptr_anon_struct, anon_struct_src);
    const union_inst = try sema.coerceAnonStructToUnion(block, union_ty, union_ty_src, anon_struct, anon_struct_src);
    return sema.analyzeRef(block, union_ty_src, union_inst);
}

fn coerceAnonStructToStructPtrs(
    sema: *Sema,
    block: *Block,
    ptr_struct_ty: Type,
    struct_ty_src: LazySrcLoc,
    ptr_anon_struct: Air.Inst.Ref,
    anon_struct_src: LazySrcLoc,
) !Air.Inst.Ref {
    const struct_ty = ptr_struct_ty.childType();
    const anon_struct = try sema.analyzeLoad(block, anon_struct_src, ptr_anon_struct, anon_struct_src);
    const struct_inst = try sema.coerceTupleToStruct(block, struct_ty, anon_struct, anon_struct_src);
    return sema.analyzeRef(block, struct_ty_src, struct_inst);
}

/// If the lengths match, coerces element-wise.
fn coerceArrayLike(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    dest_ty_src: LazySrcLoc,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const inst_ty = sema.typeOf(inst);
    const inst_len = inst_ty.arrayLen();
    const dest_len = try sema.usizeCast(block, dest_ty_src, dest_ty.arrayLen());
    const target = sema.mod.getTarget();

    if (dest_len != inst_len) {
        const msg = msg: {
            const msg = try sema.errMsg(block, inst_src, "expected type '{}', found '{}'", .{
                dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, dest_ty_src, msg, "destination has length {d}", .{dest_len});
            try sema.errNote(block, inst_src, msg, "source has length {d}", .{inst_len});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const dest_elem_ty = dest_ty.childType();
    const inst_elem_ty = inst_ty.childType();
    const in_memory_result = try sema.coerceInMemoryAllowed(block, dest_elem_ty, inst_elem_ty, false, target, dest_ty_src, inst_src);
    if (in_memory_result == .ok) {
        if (try sema.resolveMaybeUndefVal(inst)) |inst_val| {
            // These types share the same comptime value representation.
            return sema.addConstant(dest_ty, inst_val);
        }
        try sema.requireRuntimeBlock(block, inst_src, null);
        return block.addBitCast(dest_ty, inst);
    }

    const element_vals = try sema.arena.alloc(Value, dest_len);
    const element_refs = try sema.arena.alloc(Air.Inst.Ref, dest_len);
    var runtime_src: ?LazySrcLoc = null;

    for (element_vals, 0..) |*elem, i| {
        const index_ref = try sema.addConstant(
            Type.usize,
            try Value.Tag.int_u64.create(sema.arena, i),
        );
        const src = inst_src; // TODO better source location
        const elem_src = inst_src; // TODO better source location
        const elem_ref = try sema.elemValArray(block, src, inst_src, inst, elem_src, index_ref, true);
        const coerced = try sema.coerce(block, dest_elem_ty, elem_ref, elem_src);
        element_refs[i] = coerced;
        if (runtime_src == null) {
            if (try sema.resolveMaybeUndefVal(coerced)) |elem_val| {
                elem.* = elem_val;
            } else {
                runtime_src = elem_src;
            }
        }
    }

    if (runtime_src) |rs| {
        try sema.requireRuntimeBlock(block, inst_src, rs);
        return block.addAggregateInit(dest_ty, element_refs);
    }

    return sema.addConstant(
        dest_ty,
        try Value.Tag.aggregate.create(sema.arena, element_vals),
    );
}

/// If the lengths match, coerces element-wise.
fn coerceTupleToArray(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    dest_ty_src: LazySrcLoc,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const inst_ty = sema.typeOf(inst);
    const inst_len = inst_ty.arrayLen();
    const dest_len = dest_ty.arrayLen();

    if (dest_len != inst_len) {
        const msg = msg: {
            const msg = try sema.errMsg(block, inst_src, "expected type '{}', found '{}'", .{
                dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(block, dest_ty_src, msg, "destination has length {d}", .{dest_len});
            try sema.errNote(block, inst_src, msg, "source has length {d}", .{inst_len});
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const dest_elems = try sema.usizeCast(block, dest_ty_src, dest_ty.arrayLenIncludingSentinel());
    const element_vals = try sema.arena.alloc(Value, dest_elems);
    const element_refs = try sema.arena.alloc(Air.Inst.Ref, dest_elems);
    const dest_elem_ty = dest_ty.childType();

    var runtime_src: ?LazySrcLoc = null;
    for (element_vals, 0..) |*elem, i_usize| {
        const i = @intCast(u32, i_usize);
        if (i_usize == inst_len) {
            elem.* = dest_ty.sentinel().?;
            element_refs[i] = try sema.addConstant(dest_elem_ty, elem.*);
            break;
        }
        const elem_src = inst_src; // TODO better source location
        const elem_ref = try sema.tupleField(block, inst_src, inst, elem_src, i);
        const coerced = try sema.coerce(block, dest_elem_ty, elem_ref, elem_src);
        element_refs[i] = coerced;
        if (runtime_src == null) {
            if (try sema.resolveMaybeUndefVal(coerced)) |elem_val| {
                elem.* = elem_val;
            } else {
                runtime_src = elem_src;
            }
        }
    }

    if (runtime_src) |rs| {
        try sema.requireRuntimeBlock(block, inst_src, rs);
        return block.addAggregateInit(dest_ty, element_refs);
    }

    return sema.addConstant(
        dest_ty,
        try Value.Tag.aggregate.create(sema.arena, element_vals),
    );
}

/// If the lengths match, coerces element-wise.
fn coerceTupleToSlicePtrs(
    sema: *Sema,
    block: *Block,
    slice_ty: Type,
    slice_ty_src: LazySrcLoc,
    ptr_tuple: Air.Inst.Ref,
    tuple_src: LazySrcLoc,
) !Air.Inst.Ref {
    const tuple_ty = sema.typeOf(ptr_tuple).childType();
    const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
    const slice_info = slice_ty.ptrInfo().data;
    const array_ty = try Type.array(sema.arena, tuple_ty.structFieldCount(), slice_info.sentinel, slice_info.pointee_type, sema.mod);
    const array_inst = try sema.coerceTupleToArray(block, array_ty, slice_ty_src, tuple, tuple_src);
    if (slice_info.@"align" != 0) {
        return sema.fail(block, slice_ty_src, "TODO: override the alignment of the array decl we create here", .{});
    }
    const ptr_array = try sema.analyzeRef(block, slice_ty_src, array_inst);
    return sema.coerceArrayPtrToSlice(block, slice_ty, ptr_array, slice_ty_src);
}

/// If the lengths match, coerces element-wise.
fn coerceTupleToArrayPtrs(
    sema: *Sema,
    block: *Block,
    ptr_array_ty: Type,
    array_ty_src: LazySrcLoc,
    ptr_tuple: Air.Inst.Ref,
    tuple_src: LazySrcLoc,
) !Air.Inst.Ref {
    const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
    const ptr_info = ptr_array_ty.ptrInfo().data;
    const array_ty = ptr_info.pointee_type;
    const array_inst = try sema.coerceTupleToArray(block, array_ty, array_ty_src, tuple, tuple_src);
    if (ptr_info.@"align" != 0) {
        return sema.fail(block, array_ty_src, "TODO: override the alignment of the array decl we create here", .{});
    }
    const ptr_array = try sema.analyzeRef(block, array_ty_src, array_inst);
    return ptr_array;
}

/// Handles both tuples and anon struct literals. Coerces field-wise. Reports
/// errors for both extra fields and missing fields.
fn coerceTupleToStruct(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const struct_ty = try sema.resolveTypeFields(dest_ty);

    if (struct_ty.isTupleOrAnonStruct()) {
        return sema.coerceTupleToTuple(block, struct_ty, inst, inst_src);
    }

    const fields = struct_ty.structFields();
    const field_vals = try sema.arena.alloc(Value, fields.count());
    const field_refs = try sema.arena.alloc(Air.Inst.Ref, field_vals.len);
    mem.set(Air.Inst.Ref, field_refs, .none);

    const inst_ty = sema.typeOf(inst);
    var runtime_src: ?LazySrcLoc = null;
    const field_count = inst_ty.structFieldCount();
    var field_i: u32 = 0;
    while (field_i < field_count) : (field_i += 1) {
        const field_src = inst_src; // TODO better source location
        const field_name = if (inst_ty.castTag(.anon_struct)) |payload|
            payload.data.names[field_i]
        else
            try std.fmt.allocPrint(sema.arena, "{d}", .{field_i});
        const field_index = try sema.structFieldIndex(block, struct_ty, field_name, field_src);
        const field = fields.values()[field_index];
        const elem_ref = try sema.tupleField(block, inst_src, inst, field_src, field_i);
        const coerced = try sema.coerce(block, field.ty, elem_ref, field_src);
        field_refs[field_index] = coerced;
        if (field.is_comptime) {
            const init_val = (try sema.resolveMaybeUndefVal(coerced)) orelse {
                return sema.failWithNeededComptime(block, field_src, "value stored in comptime field must be comptime-known");
            };

            if (!init_val.eql(field.default_val, field.ty, sema.mod)) {
                return sema.failWithInvalidComptimeFieldStore(block, field_src, inst_ty, field_i);
            }
        }
        if (runtime_src == null) {
            if (try sema.resolveMaybeUndefVal(coerced)) |field_val| {
                field_vals[field_index] = field_val;
            } else {
                runtime_src = field_src;
            }
        }
    }

    // Populate default field values and report errors for missing fields.
    var root_msg: ?*Module.ErrorMsg = null;
    errdefer if (root_msg) |msg| msg.destroy(sema.gpa);

    for (field_refs, 0..) |*field_ref, i| {
        if (field_ref.* != .none) continue;

        const field_name = fields.keys()[i];
        const field = fields.values()[i];
        const field_src = inst_src; // TODO better source location
        if (field.default_val.tag() == .unreachable_value) {
            const template = "missing struct field: {s}";
            const args = .{field_name};
            if (root_msg) |msg| {
                try sema.errNote(block, field_src, msg, template, args);
            } else {
                root_msg = try sema.errMsg(block, field_src, template, args);
            }
            continue;
        }
        if (runtime_src == null) {
            field_vals[i] = field.default_val;
        } else {
            field_ref.* = try sema.addConstant(field.ty, field.default_val);
        }
    }

    if (root_msg) |msg| {
        try sema.addDeclaredHereNote(msg, struct_ty);
        root_msg = null;
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (runtime_src) |rs| {
        try sema.requireRuntimeBlock(block, inst_src, rs);
        return block.addAggregateInit(struct_ty, field_refs);
    }

    return sema.addConstant(
        struct_ty,
        try Value.Tag.aggregate.create(sema.arena, field_vals),
    );
}

fn coerceTupleToTuple(
    sema: *Sema,
    block: *Block,
    tuple_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const dest_field_count = tuple_ty.structFieldCount();
    const field_vals = try sema.arena.alloc(Value, dest_field_count);
    const field_refs = try sema.arena.alloc(Air.Inst.Ref, field_vals.len);
    mem.set(Air.Inst.Ref, field_refs, .none);

    const inst_ty = sema.typeOf(inst);
    const inst_field_count = inst_ty.structFieldCount();
    if (inst_field_count > dest_field_count) return error.NotCoercible;

    var runtime_src: ?LazySrcLoc = null;
    var field_i: u32 = 0;
    while (field_i < inst_field_count) : (field_i += 1) {
        const field_src = inst_src; // TODO better source location
        const field_name = if (inst_ty.castTag(.anon_struct)) |payload|
            payload.data.names[field_i]
        else
            try std.fmt.allocPrint(sema.arena, "{d}", .{field_i});

        if (mem.eql(u8, field_name, "len")) {
            return sema.fail(block, field_src, "cannot assign to 'len' field of tuple", .{});
        }

        const field_index = try sema.tupleFieldIndex(block, tuple_ty, field_name, field_src);

        const field_ty = tuple_ty.structFieldType(field_i);
        const default_val = tuple_ty.structFieldDefaultValue(field_i);
        const elem_ref = try sema.tupleField(block, inst_src, inst, field_src, field_i);
        const coerced = try sema.coerce(block, field_ty, elem_ref, field_src);
        field_refs[field_index] = coerced;
        if (default_val.tag() != .unreachable_value) {
            const init_val = (try sema.resolveMaybeUndefVal(coerced)) orelse {
                return sema.failWithNeededComptime(block, field_src, "value stored in comptime field must be comptime-known");
            };

            if (!init_val.eql(default_val, field_ty, sema.mod)) {
                return sema.failWithInvalidComptimeFieldStore(block, field_src, inst_ty, field_i);
            }
        }
        if (runtime_src == null) {
            if (try sema.resolveMaybeUndefVal(coerced)) |field_val| {
                field_vals[field_index] = field_val;
            } else {
                runtime_src = field_src;
            }
        }
    }

    // Populate default field values and report errors for missing fields.
    var root_msg: ?*Module.ErrorMsg = null;
    errdefer if (root_msg) |msg| msg.destroy(sema.gpa);

    for (field_refs, 0..) |*field_ref, i| {
        if (field_ref.* != .none) continue;

        const default_val = tuple_ty.structFieldDefaultValue(i);
        const field_ty = tuple_ty.structFieldType(i);

        const field_src = inst_src; // TODO better source location
        if (default_val.tag() == .unreachable_value) {
            if (tuple_ty.isTuple()) {
                const template = "missing tuple field: {d}";
                if (root_msg) |msg| {
                    try sema.errNote(block, field_src, msg, template, .{i});
                } else {
                    root_msg = try sema.errMsg(block, field_src, template, .{i});
                }
                continue;
            }
            const template = "missing struct field: {s}";
            const args = .{tuple_ty.structFieldName(i)};
            if (root_msg) |msg| {
                try sema.errNote(block, field_src, msg, template, args);
            } else {
                root_msg = try sema.errMsg(block, field_src, template, args);
            }
            continue;
        }
        if (runtime_src == null) {
            field_vals[i] = default_val;
        } else {
            field_ref.* = try sema.addConstant(field_ty, default_val);
        }
    }

    if (root_msg) |msg| {
        try sema.addDeclaredHereNote(msg, tuple_ty);
        root_msg = null;
        return sema.failWithOwnedErrorMsg(msg);
    }

    if (runtime_src) |rs| {
        try sema.requireRuntimeBlock(block, inst_src, rs);
        return block.addAggregateInit(tuple_ty, field_refs);
    }

    return sema.addConstant(
        tuple_ty,
        try Value.Tag.aggregate.create(sema.arena, field_vals),
    );
}

fn analyzeDeclVal(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    decl_index: Decl.Index,
) CompileError!Air.Inst.Ref {
    try sema.addReferencedBy(block, src, decl_index);
    if (sema.decl_val_table.get(decl_index)) |result| {
        return result;
    }
    const decl_ref = try sema.analyzeDeclRef(decl_index);
    const result = try sema.analyzeLoad(block, src, decl_ref, src);
    if (Air.refToIndex(result)) |index| {
        if (sema.air_instructions.items(.tag)[index] == .constant and !block.is_typeof) {
            try sema.decl_val_table.put(sema.gpa, decl_index, result);
        }
    }
    return result;
}

fn addReferencedBy(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    decl_index: Decl.Index,
) !void {
    if (sema.mod.comp.reference_trace == @as(u32, 0)) return;
    try sema.mod.reference_table.put(sema.gpa, decl_index, .{
        .referencer = block.src_decl,
        .src = src,
    });
}

fn ensureDeclAnalyzed(sema: *Sema, decl_index: Decl.Index) CompileError!void {
    const decl = sema.mod.declPtr(decl_index);
    if (decl.analysis == .in_progress) {
        const msg = try Module.ErrorMsg.create(sema.gpa, decl.srcLoc(), "dependency loop detected", .{});
        return sema.failWithOwnedErrorMsg(msg);
    }

    sema.mod.ensureDeclAnalyzed(decl_index) catch |err| {
        if (sema.owner_func) |owner_func| {
            owner_func.state = .dependency_failure;
        } else {
            sema.owner_decl.analysis = .dependency_failure;
        }
        return err;
    };
}

fn ensureFuncBodyAnalyzed(sema: *Sema, func: *Module.Fn) CompileError!void {
    sema.mod.ensureFuncBodyAnalyzed(func) catch |err| {
        if (sema.owner_func) |owner_func| {
            owner_func.state = .dependency_failure;
        } else {
            sema.owner_decl.analysis = .dependency_failure;
        }
        return err;
    };
}

fn refValue(sema: *Sema, block: *Block, ty: Type, val: Value) !Value {
    var anon_decl = try block.startAnonDecl();
    defer anon_decl.deinit();
    const decl = try anon_decl.finish(
        try ty.copy(anon_decl.arena()),
        try val.copy(anon_decl.arena()),
        0, // default alignment
    );
    try sema.mod.declareDeclDependency(sema.owner_decl_index, decl);
    return try Value.Tag.decl_ref.create(sema.arena, decl);
}

fn optRefValue(sema: *Sema, block: *Block, ty: Type, opt_val: ?Value) !Value {
    const val = opt_val orelse return Value.null;
    const ptr_val = try sema.refValue(block, ty, val);
    const result = try Value.Tag.opt_payload.create(sema.arena, ptr_val);
    return result;
}

fn analyzeDeclRef(sema: *Sema, decl_index: Decl.Index) CompileError!Air.Inst.Ref {
    try sema.mod.declareDeclDependency(sema.owner_decl_index, decl_index);
    try sema.ensureDeclAnalyzed(decl_index);

    const decl = sema.mod.declPtr(decl_index);
    const decl_tv = try decl.typedValue();
    if (decl_tv.val.castTag(.variable)) |payload| {
        const variable = payload.data;
        const ty = try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = decl_tv.ty,
            .mutable = variable.is_mutable,
            .@"addrspace" = decl.@"addrspace",
            .@"align" = decl.@"align",
        });
        return sema.addConstant(ty, try Value.Tag.decl_ref.create(sema.arena, decl_index));
    }
    return sema.addConstant(
        try Type.ptr(sema.arena, sema.mod, .{
            .pointee_type = decl_tv.ty,
            .mutable = false,
            .@"addrspace" = decl.@"addrspace",
            .@"align" = decl.@"align",
        }),
        try Value.Tag.decl_ref.create(sema.arena, decl_index),
    );
}

fn analyzeRef(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const operand_ty = sema.typeOf(operand);

    if (try sema.resolveMaybeUndefVal(operand)) |val| {
        switch (val.tag()) {
            .extern_fn, .function => {
                const decl_index = val.pointerDecl().?;
                return sema.analyzeDeclRef(decl_index);
            },
            else => {},
        }
        var anon_decl = try block.startAnonDecl();
        defer anon_decl.deinit();
        return sema.analyzeDeclRef(try anon_decl.finish(
            try operand_ty.copy(anon_decl.arena()),
            try val.copy(anon_decl.arena()),
            0, // default alignment
        ));
    }

    try sema.requireRuntimeBlock(block, src, null);
    const address_space = target_util.defaultAddressSpace(sema.mod.getTarget(), .local);
    const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = operand_ty,
        .mutable = false,
        .@"addrspace" = address_space,
    });
    const mut_ptr_type = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = operand_ty,
        .@"addrspace" = address_space,
    });
    const alloc = try block.addTy(.alloc, mut_ptr_type);
    try sema.storePtr(block, src, alloc, operand);

    // TODO: Replace with sema.coerce when that supports adding pointer constness.
    return sema.bitCast(block, ptr_type, alloc, src, null);
}

fn analyzeLoad(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr: Air.Inst.Ref,
    ptr_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const ptr_ty = sema.typeOf(ptr);
    const elem_ty = switch (ptr_ty.zigTypeTag()) {
        .Pointer => ptr_ty.childType(),
        else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)}),
    };

    if (try sema.typeHasOnePossibleValue(elem_ty)) |opv| {
        return sema.addConstant(elem_ty, opv);
    }

    if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| {
        if (try sema.pointerDeref(block, src, ptr_val, ptr_ty)) |elem_val| {
            return sema.addConstant(elem_ty, elem_val);
        }
    }

    if (ptr_ty.ptrInfo().data.vector_index == .runtime) {
        const ptr_inst = Air.refToIndex(ptr).?;
        const air_tags = sema.air_instructions.items(.tag);
        if (air_tags[ptr_inst] == .ptr_elem_ptr) {
            const ty_pl = sema.air_instructions.items(.data)[ptr_inst].ty_pl;
            const bin_op = sema.getTmpAir().extraData(Air.Bin, ty_pl.payload).data;
            return block.addBinOp(.ptr_elem_val, bin_op.lhs, bin_op.rhs);
        }
        return sema.fail(block, ptr_src, "unable to determine vector element index of type '{}'", .{
            ptr_ty.fmt(sema.mod),
        });
    }

    return block.addTyOp(.load, elem_ty, ptr);
}

fn analyzeSlicePtr(
    sema: *Sema,
    block: *Block,
    slice_src: LazySrcLoc,
    slice: Air.Inst.Ref,
    slice_ty: Type,
) CompileError!Air.Inst.Ref {
    const buf = try sema.arena.create(Type.SlicePtrFieldTypeBuffer);
    const result_ty = slice_ty.slicePtrFieldType(buf);
    if (try sema.resolveMaybeUndefVal(slice)) |val| {
        if (val.isUndef()) return sema.addConstUndef(result_ty);
        return sema.addConstant(result_ty, val.slicePtr());
    }
    try sema.requireRuntimeBlock(block, slice_src, null);
    return block.addTyOp(.slice_ptr, result_ty, slice);
}

fn analyzeSliceLen(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    slice_inst: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    if (try sema.resolveMaybeUndefVal(slice_inst)) |slice_val| {
        if (slice_val.isUndef()) {
            return sema.addConstUndef(Type.usize);
        }
        return sema.addIntUnsigned(Type.usize, slice_val.sliceLen(sema.mod));
    }
    try sema.requireRuntimeBlock(block, src, null);
    return block.addTyOp(.slice_len, Type.usize, slice_inst);
}

fn analyzeIsNull(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
    invert_logic: bool,
) CompileError!Air.Inst.Ref {
    const result_ty = Type.bool;
    if (try sema.resolveMaybeUndefVal(operand)) |opt_val| {
        if (opt_val.isUndef()) {
            return sema.addConstUndef(result_ty);
        }
        const is_null = opt_val.isNull();
        const bool_value = if (invert_logic) !is_null else is_null;
        if (bool_value) {
            return Air.Inst.Ref.bool_true;
        } else {
            return Air.Inst.Ref.bool_false;
        }
    }

    const inverted_non_null_res = if (invert_logic) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false;
    const operand_ty = sema.typeOf(operand);
    var buf: Type.Payload.ElemType = undefined;
    if (operand_ty.zigTypeTag() == .Optional and operand_ty.optionalChild(&buf).zigTypeTag() == .NoReturn) {
        return inverted_non_null_res;
    }
    if (operand_ty.zigTypeTag() != .Optional and !operand_ty.isPtrLikeOptional()) {
        return inverted_non_null_res;
    }
    try sema.requireRuntimeBlock(block, src, null);
    const air_tag: Air.Inst.Tag = if (invert_logic) .is_non_null else .is_null;
    return block.addUnOp(air_tag, operand);
}

fn analyzePtrIsNonErrComptimeOnly(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const ptr_ty = sema.typeOf(operand);
    assert(ptr_ty.zigTypeTag() == .Pointer);
    const child_ty = ptr_ty.childType();

    const child_tag = child_ty.zigTypeTag();
    if (child_tag != .ErrorSet and child_tag != .ErrorUnion) return Air.Inst.Ref.bool_true;
    if (child_tag == .ErrorSet) return Air.Inst.Ref.bool_false;
    assert(child_tag == .ErrorUnion);

    _ = block;
    _ = src;

    return Air.Inst.Ref.none;
}

fn analyzeIsNonErrComptimeOnly(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const operand_ty = sema.typeOf(operand);
    const ot = operand_ty.zigTypeTag();
    if (ot != .ErrorSet and ot != .ErrorUnion) return Air.Inst.Ref.bool_true;
    if (ot == .ErrorSet) return Air.Inst.Ref.bool_false;
    assert(ot == .ErrorUnion);

    const payload_ty = operand_ty.errorUnionPayload();
    if (payload_ty.zigTypeTag() == .NoReturn) {
        return Air.Inst.Ref.bool_false;
    }

    if (Air.refToIndex(operand)) |operand_inst| {
        switch (sema.air_instructions.items(.tag)[operand_inst]) {
            .wrap_errunion_payload => return Air.Inst.Ref.bool_true,
            .wrap_errunion_err => return Air.Inst.Ref.bool_false,
            else => {},
        }
    } else if (operand == .undef) {
        return sema.addConstUndef(Type.bool);
    } else {
        // None of the ref tags can be errors.
        return Air.Inst.Ref.bool_true;
    }

    const maybe_operand_val = try sema.resolveMaybeUndefVal(operand);

    // exception if the error union error set is known to be empty,
    // we allow the comparison but always make it comptime-known.
    const set_ty = operand_ty.errorUnionSet();
    switch (set_ty.tag()) {
        .anyerror => {},
        .error_set_inferred => blk: {
            // If the error set is empty, we must return a comptime true or false.
            // However we want to avoid unnecessarily resolving an inferred error set
            // in case it is already non-empty.
            const ies = set_ty.castTag(.error_set_inferred).?.data;
            if (ies.is_anyerror) break :blk;
            if (ies.errors.count() != 0) break :blk;
            if (maybe_operand_val == null) {
                // Try to avoid resolving inferred error set if possible.
                if (ies.errors.count() != 0) break :blk;
                if (ies.is_anyerror) break :blk;
                for (ies.inferred_error_sets.keys()) |other_ies| {
                    if (ies == other_ies) continue;
                    try sema.resolveInferredErrorSet(block, src, other_ies);
                    if (other_ies.is_anyerror) {
                        ies.is_anyerror = true;
                        ies.is_resolved = true;
                        break :blk;
                    }

                    if (other_ies.errors.count() != 0) break :blk;
                }
                if (ies.func == sema.owner_func) {
                    // We're checking the inferred errorset of the current function and none of
                    // its child inferred error sets contained any errors meaning that any value
                    // so far with this type can't contain errors either.
                    return Air.Inst.Ref.bool_true;
                }
                try sema.resolveInferredErrorSet(block, src, ies);
                if (ies.is_anyerror) break :blk;
                if (ies.errors.count() == 0) return Air.Inst.Ref.bool_true;
            }
        },
        else => if (set_ty.errorSetNames().len == 0) return Air.Inst.Ref.bool_true,
    }

    if (maybe_operand_val) |err_union| {
        if (err_union.isUndef()) {
            return sema.addConstUndef(Type.bool);
        }
        if (err_union.getError() == null) {
            return Air.Inst.Ref.bool_true;
        } else {
            return Air.Inst.Ref.bool_false;
        }
    }
    return Air.Inst.Ref.none;
}

fn analyzeIsNonErr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const result = try sema.analyzeIsNonErrComptimeOnly(block, src, operand);
    if (result == .none) {
        try sema.requireRuntimeBlock(block, src, null);
        return block.addUnOp(.is_non_err, operand);
    } else {
        return result;
    }
}

fn analyzePtrIsNonErr(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    operand: Air.Inst.Ref,
) CompileError!Air.Inst.Ref {
    const result = try sema.analyzePtrIsNonErrComptimeOnly(block, src, operand);
    if (result == .none) {
        try sema.requireRuntimeBlock(block, src, null);
        return block.addUnOp(.is_non_err_ptr, operand);
    } else {
        return result;
    }
}

fn analyzeSlice(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ptr_ptr: Air.Inst.Ref,
    uncasted_start: Air.Inst.Ref,
    uncasted_end_opt: Air.Inst.Ref,
    sentinel_opt: Air.Inst.Ref,
    sentinel_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const ptr_src: LazySrcLoc = .{ .node_offset_slice_ptr = src.node_offset.x };
    const start_src: LazySrcLoc = .{ .node_offset_slice_start = src.node_offset.x };
    const end_src: LazySrcLoc = .{ .node_offset_slice_end = src.node_offset.x };
    // Slice expressions can operate on a variable whose type is an array. This requires
    // the slice operand to be a pointer. In the case of a non-array, it will be a double pointer.
    const ptr_ptr_ty = sema.typeOf(ptr_ptr);
    const target = sema.mod.getTarget();
    const ptr_ptr_child_ty = switch (ptr_ptr_ty.zigTypeTag()) {
        .Pointer => ptr_ptr_ty.elemType(),
        else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(sema.mod)}),
    };
    const mod = sema.mod;

    var array_ty = ptr_ptr_child_ty;
    var slice_ty = ptr_ptr_ty;
    var ptr_or_slice = ptr_ptr;
    var elem_ty: Type = undefined;
    var ptr_sentinel: ?Value = null;
    switch (ptr_ptr_child_ty.zigTypeTag()) {
        .Array => {
            ptr_sentinel = ptr_ptr_child_ty.sentinel();
            elem_ty = ptr_ptr_child_ty.childType();
        },
        .Pointer => switch (ptr_ptr_child_ty.ptrSize()) {
            .One => {
                const double_child_ty = ptr_ptr_child_ty.childType();
                if (double_child_ty.zigTypeTag() == .Array) {
                    ptr_sentinel = double_child_ty.sentinel();
                    ptr_or_slice = try sema.analyzeLoad(block, src, ptr_ptr, ptr_src);
                    slice_ty = ptr_ptr_child_ty;
                    array_ty = double_child_ty;
                    elem_ty = double_child_ty.childType();
                } else {
                    return sema.fail(block, src, "slice of single-item pointer", .{});
                }
            },
            .Many, .C => {
                ptr_sentinel = ptr_ptr_child_ty.sentinel();
                ptr_or_slice = try sema.analyzeLoad(block, src, ptr_ptr, ptr_src);
                slice_ty = ptr_ptr_child_ty;
                array_ty = ptr_ptr_child_ty;
                elem_ty = ptr_ptr_child_ty.childType();

                if (ptr_ptr_child_ty.ptrSize() == .C) {
                    if (try sema.resolveDefinedValue(block, ptr_src, ptr_or_slice)) |ptr_val| {
                        if (ptr_val.isNull()) {
                            return sema.fail(block, src, "slice of null pointer", .{});
                        }
                    }
                }
            },
            .Slice => {
                ptr_sentinel = ptr_ptr_child_ty.sentinel();
                ptr_or_slice = try sema.analyzeLoad(block, src, ptr_ptr, ptr_src);
                slice_ty = ptr_ptr_child_ty;
                array_ty = ptr_ptr_child_ty;
                elem_ty = ptr_ptr_child_ty.childType();
            },
        },
        else => return sema.fail(block, src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(mod)}),
    }

    const ptr = if (slice_ty.isSlice())
        try sema.analyzeSlicePtr(block, ptr_src, ptr_or_slice, slice_ty)
    else
        ptr_or_slice;

    const start = try sema.coerce(block, Type.usize, uncasted_start, start_src);
    const new_ptr = try sema.analyzePtrArithmetic(block, src, ptr, start, .ptr_add, ptr_src, start_src);

    // true if and only if the end index of the slice, implicitly or explicitly, equals
    // the length of the underlying object being sliced. we might learn the length of the
    // underlying object because it is an array (which has the length in the type), or
    // we might learn of the length because it is a comptime-known slice value.
    var end_is_len = uncasted_end_opt == .none;
    const end = e: {
        if (array_ty.zigTypeTag() == .Array) {
            const len_val = try Value.Tag.int_u64.create(sema.arena, array_ty.arrayLen());

            if (!end_is_len) {
                const end = try sema.coerce(block, Type.usize, uncasted_end_opt, end_src);
                if (try sema.resolveMaybeUndefVal(end)) |end_val| {
                    const len_s_val = try Value.Tag.int_u64.create(
                        sema.arena,
                        array_ty.arrayLenIncludingSentinel(),
                    );
                    if (!(try sema.compareAll(end_val, .lte, len_s_val, Type.usize))) {
                        const sentinel_label: []const u8 = if (array_ty.sentinel() != null)
                            " +1 (sentinel)"
                        else
                            "";

                        return sema.fail(
                            block,
                            end_src,
                            "end index {} out of bounds for array of length {}{s}",
                            .{
                                end_val.fmtValue(Type.usize, mod),
                                len_val.fmtValue(Type.usize, mod),
                                sentinel_label,
                            },
                        );
                    }

                    // end_is_len is only true if we are NOT using the sentinel
                    // length. For sentinel-length, we don't want the type to
                    // contain the sentinel.
                    if (end_val.eql(len_val, Type.usize, mod)) {
                        end_is_len = true;
                    }
                }
                break :e end;
            }

            break :e try sema.addConstant(Type.usize, len_val);
        } else if (slice_ty.isSlice()) {
            if (!end_is_len) {
                const end = try sema.coerce(block, Type.usize, uncasted_end_opt, end_src);
                if (try sema.resolveDefinedValue(block, end_src, end)) |end_val| {
                    if (try sema.resolveMaybeUndefVal(ptr_or_slice)) |slice_val| {
                        if (slice_val.isUndef()) {
                            return sema.fail(block, src, "slice of undefined", .{});
                        }
                        const has_sentinel = slice_ty.sentinel() != null;
                        var int_payload: Value.Payload.U64 = .{
                            .base = .{ .tag = .int_u64 },
                            .data = slice_val.sliceLen(mod) + @boolToInt(has_sentinel),
                        };
                        const slice_len_val = Value.initPayload(&int_payload.base);
                        if (!(try sema.compareAll(end_val, .lte, slice_len_val, Type.usize))) {
                            const sentinel_label: []const u8 = if (has_sentinel)
                                " +1 (sentinel)"
                            else
                                "";

                            return sema.fail(
                                block,
                                end_src,
                                "end index {} out of bounds for slice of length {d}{s}",
                                .{
                                    end_val.fmtValue(Type.usize, mod),
                                    slice_val.sliceLen(mod),
                                    sentinel_label,
                                },
                            );
                        }

                        // If the slice has a sentinel, we subtract one so that
                        // end_is_len is only true if it equals the length WITHOUT
                        // the sentinel, so we don't add a sentinel type.
                        if (has_sentinel) {
                            int_payload.data -= 1;
                        }

                        if (end_val.eql(slice_len_val, Type.usize, mod)) {
                            end_is_len = true;
                        }
                    }
                }
                break :e end;
            }
            break :e try sema.analyzeSliceLen(block, src, ptr_or_slice);
        }
        if (!end_is_len) {
            break :e try sema.coerce(block, Type.usize, uncasted_end_opt, end_src);
        }
        return sema.fail(block, src, "slice of pointer must include end value", .{});
    };

    const sentinel = s: {
        if (sentinel_opt != .none) {
            const casted = try sema.coerce(block, elem_ty, sentinel_opt, sentinel_src);
            break :s try sema.resolveConstValue(block, sentinel_src, casted, "slice sentinel must be comptime-known");
        }
        // If we are slicing to the end of something that is sentinel-terminated
        // then the resulting slice type is also sentinel-terminated.
        if (end_is_len) {
            if (ptr_sentinel) |sent| {
                break :s sent;
            }
        }
        break :s null;
    };
    const slice_sentinel = if (sentinel_opt != .none) sentinel else null;

    // requirement: start <= end
    if (try sema.resolveDefinedValue(block, end_src, end)) |end_val| {
        if (try sema.resolveDefinedValue(block, start_src, start)) |start_val| {
            if (!(try sema.compareAll(start_val, .lte, end_val, Type.usize))) {
                return sema.fail(
                    block,
                    start_src,
                    "start index {} is larger than end index {}",
                    .{
                        start_val.fmtValue(Type.usize, mod),
                        end_val.fmtValue(Type.usize, mod),
                    },
                );
            }
            if (try sema.resolveMaybeUndefVal(new_ptr)) |ptr_val| sentinel_check: {
                const expected_sentinel = sentinel orelse break :sentinel_check;
                const start_int = start_val.getUnsignedInt(sema.mod.getTarget()).?;
                const end_int = end_val.getUnsignedInt(sema.mod.getTarget()).?;
                const sentinel_index = try sema.usizeCast(block, end_src, end_int - start_int);

                const elem_ptr = try ptr_val.elemPtr(sema.typeOf(new_ptr), sema.arena, sentinel_index, sema.mod);
                const res = try sema.pointerDerefExtra(block, src, elem_ptr, elem_ty, false);
                const actual_sentinel = switch (res) {
                    .runtime_load => break :sentinel_check,
                    .val => |v| v,
                    .needed_well_defined => |ty| return sema.fail(
                        block,
                        src,
                        "comptime dereference requires '{}' to have a well-defined layout, but it does not.",
                        .{ty.fmt(sema.mod)},
                    ),
                    .out_of_bounds => |ty| return sema.fail(
                        block,
                        end_src,
                        "slice end index {d} exceeds bounds of containing decl of type '{}'",
                        .{ end_int, ty.fmt(sema.mod) },
                    ),
                };

                if (!actual_sentinel.eql(expected_sentinel, elem_ty, sema.mod)) {
                    const msg = msg: {
                        const msg = try sema.errMsg(block, src, "value in memory does not match slice sentinel", .{});
                        errdefer msg.destroy(sema.gpa);
                        try sema.errNote(block, src, msg, "expected '{}', found '{}'", .{
                            expected_sentinel.fmtValue(elem_ty, sema.mod),
                            actual_sentinel.fmtValue(elem_ty, sema.mod),
                        });

                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            }
        }
    }

    if (block.wantSafety() and !block.is_comptime) {
        // requirement: start <= end
        try sema.panicStartLargerThanEnd(block, start, end);
    }
    const new_len = try sema.analyzeArithmetic(block, .sub, end, start, src, end_src, start_src, false);
    const opt_new_len_val = try sema.resolveDefinedValue(block, src, new_len);

    const new_ptr_ty_info = sema.typeOf(new_ptr).ptrInfo().data;
    const new_allowzero = new_ptr_ty_info.@"allowzero" and sema.typeOf(ptr).ptrSize() != .C;

    if (opt_new_len_val) |new_len_val| {
        const new_len_int = new_len_val.toUnsignedInt(target);

        const return_ty = try Type.ptr(sema.arena, mod, .{
            .pointee_type = try Type.array(sema.arena, new_len_int, sentinel, elem_ty, mod),
            .sentinel = null,
            .@"align" = new_ptr_ty_info.@"align",
            .@"addrspace" = new_ptr_ty_info.@"addrspace",
            .mutable = new_ptr_ty_info.mutable,
            .@"allowzero" = new_allowzero,
            .@"volatile" = new_ptr_ty_info.@"volatile",
            .size = .One,
        });

        const opt_new_ptr_val = try sema.resolveMaybeUndefVal(new_ptr);
        const new_ptr_val = opt_new_ptr_val orelse {
            const result = try block.addBitCast(return_ty, new_ptr);
            if (block.wantSafety()) {
                // requirement: slicing C ptr is non-null
                if (ptr_ptr_child_ty.isCPtr()) {
                    const is_non_null = try sema.analyzeIsNull(block, ptr_src, ptr, true);
                    try sema.addSafetyCheck(block, is_non_null, .unwrap_null);
                }

                if (slice_ty.isSlice()) {
                    const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
                    const actual_len = if (slice_ty.sentinel() == null)
                        slice_len_inst
                    else
                        try sema.analyzeArithmetic(block, .add, slice_len_inst, .one, src, end_src, end_src, true);

                    const actual_end = if (slice_sentinel != null)
                        try sema.analyzeArithmetic(block, .add, end, .one, src, end_src, end_src, true)
                    else
                        end;

                    try sema.panicIndexOutOfBounds(block, actual_end, actual_len, .cmp_lte);
                }

                // requirement: result[new_len] == slice_sentinel
                try sema.panicSentinelMismatch(block, slice_sentinel, elem_ty, result, new_len);
            }
            return result;
        };

        if (!new_ptr_val.isUndef()) {
            return sema.addConstant(return_ty, new_ptr_val);
        }

        // Special case: @as([]i32, undefined)[x..x]
        if (new_len_int == 0) {
            return sema.addConstUndef(return_ty);
        }

        return sema.fail(block, src, "non-zero length slice of undefined pointer", .{});
    }

    const return_ty = try Type.ptr(sema.arena, mod, .{
        .pointee_type = elem_ty,
        .sentinel = sentinel,
        .@"align" = new_ptr_ty_info.@"align",
        .@"addrspace" = new_ptr_ty_info.@"addrspace",
        .mutable = new_ptr_ty_info.mutable,
        .@"allowzero" = new_allowzero,
        .@"volatile" = new_ptr_ty_info.@"volatile",
        .size = .Slice,
    });

    const runtime_src = if ((try sema.resolveMaybeUndefVal(ptr_or_slice)) == null)
        ptr_src
    else if ((try sema.resolveMaybeUndefVal(start)) == null)
        start_src
    else
        end_src;

    try sema.requireRuntimeBlock(block, src, runtime_src);
    if (block.wantSafety()) {
        // requirement: slicing C ptr is non-null
        if (ptr_ptr_child_ty.isCPtr()) {
            const is_non_null = try sema.analyzeIsNull(block, ptr_src, ptr, true);
            try sema.addSafetyCheck(block, is_non_null, .unwrap_null);
        }

        // requirement: end <= len
        const opt_len_inst = if (array_ty.zigTypeTag() == .Array)
            try sema.addIntUnsigned(Type.usize, array_ty.arrayLenIncludingSentinel())
        else if (slice_ty.isSlice()) blk: {
            if (try sema.resolveDefinedValue(block, src, ptr_or_slice)) |slice_val| {
                // we don't need to add one for sentinels because the
                // underlying value data includes the sentinel
                break :blk try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(mod));
            }

            const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
            if (slice_ty.sentinel() == null) break :blk slice_len_inst;

            // we have to add one because slice lengths don't include the sentinel
            break :blk try sema.analyzeArithmetic(block, .add, slice_len_inst, .one, src, end_src, end_src, true);
        } else null;
        if (opt_len_inst) |len_inst| {
            const actual_end = if (slice_sentinel != null)
                try sema.analyzeArithmetic(block, .add, end, .one, src, end_src, end_src, true)
            else
                end;
            try sema.panicIndexOutOfBounds(block, actual_end, len_inst, .cmp_lte);
        }

        // requirement: start <= end
        try sema.panicIndexOutOfBounds(block, start, end, .cmp_lte);
    }
    const result = try block.addInst(.{
        .tag = .slice,
        .data = .{ .ty_pl = .{
            .ty = try sema.addType(return_ty),
            .payload = try sema.addExtra(Air.Bin{
                .lhs = new_ptr,
                .rhs = new_len,
            }),
        } },
    });
    if (block.wantSafety()) {
        // requirement: result[new_len] == slice_sentinel
        try sema.panicSentinelMismatch(block, slice_sentinel, elem_ty, result, new_len);
    }
    return result;
}

/// Asserts that lhs and rhs types are both numeric.
fn cmpNumeric(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    uncasted_lhs: Air.Inst.Ref,
    uncasted_rhs: Air.Inst.Ref,
    op: std.math.CompareOperator,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const lhs_ty = sema.typeOf(uncasted_lhs);
    const rhs_ty = sema.typeOf(uncasted_rhs);

    assert(lhs_ty.isNumeric());
    assert(rhs_ty.isNumeric());

    const lhs_ty_tag = lhs_ty.zigTypeTag();
    const rhs_ty_tag = rhs_ty.zigTypeTag();
    const target = sema.mod.getTarget();

    // One exception to heterogeneous comparison: comptime_float needs to
    // coerce to fixed-width float.

    const lhs = if (lhs_ty_tag == .ComptimeFloat and rhs_ty_tag == .Float)
        try sema.coerce(block, rhs_ty, uncasted_lhs, lhs_src)
    else
        uncasted_lhs;

    const rhs = if (lhs_ty_tag == .Float and rhs_ty_tag == .ComptimeFloat)
        try sema.coerce(block, lhs_ty, uncasted_rhs, rhs_src)
    else
        uncasted_rhs;

    const runtime_src: LazySrcLoc = src: {
        if (try sema.resolveMaybeUndefVal(lhs)) |lhs_val| {
            if (try sema.resolveMaybeUndefVal(rhs)) |rhs_val| {
                // Compare ints: const vs. undefined (or vice versa)
                if (!lhs_val.isUndef() and (lhs_ty.isInt() or lhs_ty_tag == .ComptimeInt) and rhs_ty.isInt() and rhs_val.isUndef()) {
                    try sema.resolveLazyValue(lhs_val);
                    if (sema.compareIntsOnlyPossibleResult(target, lhs_val, op, rhs_ty)) |res| {
                        return if (res) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false;
                    }
                } else if (!rhs_val.isUndef() and (rhs_ty.isInt() or rhs_ty_tag == .ComptimeInt) and lhs_ty.isInt() and lhs_val.isUndef()) {
                    try sema.resolveLazyValue(rhs_val);
                    if (sema.compareIntsOnlyPossibleResult(target, rhs_val, op.reverse(), lhs_ty)) |res| {
                        return if (res) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false;
                    }
                }

                if (lhs_val.isUndef() or rhs_val.isUndef()) {
                    return sema.addConstUndef(Type.bool);
                }
                if (lhs_val.isNan() or rhs_val.isNan()) {
                    if (op == std.math.CompareOperator.neq) {
                        return Air.Inst.Ref.bool_true;
                    } else {
                        return Air.Inst.Ref.bool_false;
                    }
                }
                if (try Value.compareHeteroAdvanced(lhs_val, op, rhs_val, target, sema)) {
                    return Air.Inst.Ref.bool_true;
                } else {
                    return Air.Inst.Ref.bool_false;
                }
            } else {
                if (!lhs_val.isUndef() and (lhs_ty.isInt() or lhs_ty_tag == .ComptimeInt) and rhs_ty.isInt()) {
                    // Compare ints: const vs. var
                    try sema.resolveLazyValue(lhs_val);
                    if (sema.compareIntsOnlyPossibleResult(target, lhs_val, op, rhs_ty)) |res| {
                        return if (res) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false;
                    }
                }
                break :src rhs_src;
            }
        } else {
            if (try sema.resolveMaybeUndefVal(rhs)) |rhs_val| {
                if (!rhs_val.isUndef() and (rhs_ty.isInt() or rhs_ty_tag == .ComptimeInt) and lhs_ty.isInt()) {
                    // Compare ints: var vs. const
                    try sema.resolveLazyValue(rhs_val);
                    if (sema.compareIntsOnlyPossibleResult(target, rhs_val, op.reverse(), lhs_ty)) |res| {
                        return if (res) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false;
                    }
                }
            }
            break :src lhs_src;
        }
    };

    // TODO handle comparisons against lazy zero values
    // Some values can be compared against zero without being runtime-known or without forcing
    // a full resolution of their value, for example `@sizeOf(@Frame(function))` is known to
    // always be nonzero, and we benefit from not forcing the full evaluation and stack frame layout
    // of this function if we don't need to.
    try sema.requireRuntimeBlock(block, src, runtime_src);

    // For floats, emit a float comparison instruction.
    const lhs_is_float = switch (lhs_ty_tag) {
        .Float, .ComptimeFloat => true,
        else => false,
    };
    const rhs_is_float = switch (rhs_ty_tag) {
        .Float, .ComptimeFloat => true,
        else => false,
    };

    if (lhs_is_float and rhs_is_float) {
        // Smaller fixed-width floats coerce to larger fixed-width floats.
        // comptime_float coerces to fixed-width float.
        const dest_ty = x: {
            if (lhs_ty_tag == .ComptimeFloat) {
                break :x rhs_ty;
            } else if (rhs_ty_tag == .ComptimeFloat) {
                break :x lhs_ty;
            }
            if (lhs_ty.floatBits(target) >= rhs_ty.floatBits(target)) {
                break :x lhs_ty;
            } else {
                break :x rhs_ty;
            }
        };
        const casted_lhs = try sema.coerce(block, dest_ty, lhs, lhs_src);
        const casted_rhs = try sema.coerce(block, dest_ty, rhs, rhs_src);
        return block.addBinOp(Air.Inst.Tag.fromCmpOp(op, block.float_mode == .Optimized), casted_lhs, casted_rhs);
    }
    // For mixed unsigned integer sizes, implicit cast both operands to the larger integer.
    // For mixed signed and unsigned integers, implicit cast both operands to a signed
    // integer with + 1 bit.
    // For mixed floats and integers, extract the integer part from the float, cast that to
    // a signed integer with mantissa bits + 1, and if there was any non-integral part of the float,
    // add/subtract 1.
    const lhs_is_signed = if (try sema.resolveDefinedValue(block, lhs_src, lhs)) |lhs_val|
        !(try lhs_val.compareAllWithZeroAdvanced(.gte, sema))
    else
        (lhs_ty.isRuntimeFloat() or lhs_ty.isSignedInt());
    const rhs_is_signed = if (try sema.resolveDefinedValue(block, rhs_src, rhs)) |rhs_val|
        !(try rhs_val.compareAllWithZeroAdvanced(.gte, sema))
    else
        (rhs_ty.isRuntimeFloat() or rhs_ty.isSignedInt());
    const dest_int_is_signed = lhs_is_signed or rhs_is_signed;

    var dest_float_type: ?Type = null;

    var lhs_bits: usize = undefined;
    if (try sema.resolveMaybeUndefVal(lhs)) |lhs_val| {
        try sema.resolveLazyValue(lhs_val);
        if (lhs_val.isUndef())
            return sema.addConstUndef(Type.bool);
        if (lhs_val.isNan()) switch (op) {
            .neq => return Air.Inst.Ref.bool_true,
            else => return Air.Inst.Ref.bool_false,
        };
        if (lhs_val.isInf()) switch (op) {
            .neq => return Air.Inst.Ref.bool_true,
            .eq => return Air.Inst.Ref.bool_false,
            .gt, .gte => return if (lhs_val.isNegativeInf()) Air.Inst.Ref.bool_false else Air.Inst.Ref.bool_true,
            .lt, .lte => return if (lhs_val.isNegativeInf()) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false,
        };
        if (!rhs_is_signed) {
            switch (lhs_val.orderAgainstZero()) {
                .gt => {},
                .eq => switch (op) { // LHS = 0, RHS is unsigned
                    .lte => return Air.Inst.Ref.bool_true,
                    .gt => return Air.Inst.Ref.bool_false,
                    else => {},
                },
                .lt => switch (op) { // LHS < 0, RHS is unsigned
                    .neq, .lt, .lte => return Air.Inst.Ref.bool_true,
                    .eq, .gt, .gte => return Air.Inst.Ref.bool_false,
                },
            }
        }
        if (lhs_is_float) {
            if (lhs_val.floatHasFraction()) {
                switch (op) {
                    .eq => return Air.Inst.Ref.bool_false,
                    .neq => return Air.Inst.Ref.bool_true,
                    else => {},
                }
            }

            var bigint = try float128IntPartToBigInt(sema.gpa, lhs_val.toFloat(f128));
            defer bigint.deinit();
            if (lhs_val.floatHasFraction()) {
                if (lhs_is_signed) {
                    try bigint.addScalar(&bigint, -1);
                } else {
                    try bigint.addScalar(&bigint, 1);
                }
            }
            lhs_bits = bigint.toConst().bitCountTwosComp();
        } else {
            lhs_bits = lhs_val.intBitCountTwosComp(target);
        }
        lhs_bits += @boolToInt(!lhs_is_signed and dest_int_is_signed);
    } else if (lhs_is_float) {
        dest_float_type = lhs_ty;
    } else {
        const int_info = lhs_ty.intInfo(target);
        lhs_bits = int_info.bits + @boolToInt(int_info.signedness == .unsigned and dest_int_is_signed);
    }

    var rhs_bits: usize = undefined;
    if (try sema.resolveMaybeUndefVal(rhs)) |rhs_val| {
        try sema.resolveLazyValue(rhs_val);
        if (rhs_val.isUndef())
            return sema.addConstUndef(Type.bool);
        if (rhs_val.isNan()) switch (op) {
            .neq => return Air.Inst.Ref.bool_true,
            else => return Air.Inst.Ref.bool_false,
        };
        if (rhs_val.isInf()) switch (op) {
            .neq => return Air.Inst.Ref.bool_true,
            .eq => return Air.Inst.Ref.bool_false,
            .gt, .gte => return if (rhs_val.isNegativeInf()) Air.Inst.Ref.bool_true else Air.Inst.Ref.bool_false,
            .lt, .lte => return if (rhs_val.isNegativeInf()) Air.Inst.Ref.bool_false else Air.Inst.Ref.bool_true,
        };
        if (!lhs_is_signed) {
            switch (rhs_val.orderAgainstZero()) {
                .gt => {},
                .eq => switch (op) { // RHS = 0, LHS is unsigned
                    .gte => return Air.Inst.Ref.bool_true,
                    .lt => return Air.Inst.Ref.bool_false,
                    else => {},
                },
                .lt => switch (op) { // RHS < 0, LHS is unsigned
                    .neq, .gt, .gte => return Air.Inst.Ref.bool_true,
                    .eq, .lt, .lte => return Air.Inst.Ref.bool_false,
                },
            }
        }
        if (rhs_is_float) {
            if (rhs_val.floatHasFraction()) {
                switch (op) {
                    .eq => return Air.Inst.Ref.bool_false,
                    .neq => return Air.Inst.Ref.bool_true,
                    else => {},
                }
            }

            var bigint = try float128IntPartToBigInt(sema.gpa, rhs_val.toFloat(f128));
            defer bigint.deinit();
            if (rhs_val.floatHasFraction()) {
                if (rhs_is_signed) {
                    try bigint.addScalar(&bigint, -1);
                } else {
                    try bigint.addScalar(&bigint, 1);
                }
            }
            rhs_bits = bigint.toConst().bitCountTwosComp();
        } else {
            rhs_bits = rhs_val.intBitCountTwosComp(target);
        }
        rhs_bits += @boolToInt(!rhs_is_signed and dest_int_is_signed);
    } else if (rhs_is_float) {
        dest_float_type = rhs_ty;
    } else {
        const int_info = rhs_ty.intInfo(target);
        rhs_bits = int_info.bits + @boolToInt(int_info.signedness == .unsigned and dest_int_is_signed);
    }

    const dest_ty = if (dest_float_type) |ft| ft else blk: {
        const max_bits = std.math.max(lhs_bits, rhs_bits);
        const casted_bits = std.math.cast(u16, max_bits) orelse return sema.fail(block, src, "{d} exceeds maximum integer bit count", .{max_bits});
        const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned;
        break :blk try Module.makeIntType(sema.arena, signedness, casted_bits);
    };
    const casted_lhs = try sema.coerce(block, dest_ty, lhs, lhs_src);
    const casted_rhs = try sema.coerce(block, dest_ty, rhs, rhs_src);

    return block.addBinOp(Air.Inst.Tag.fromCmpOp(op, block.float_mode == .Optimized), casted_lhs, casted_rhs);
}

/// Asserts that LHS value is an int or comptime int and not undefined, and that RHS type is an int.
/// Given a const LHS and an unknown RHS, attempt to determine whether `op` has a guaranteed result.
/// If it cannot be determined, returns null.
/// Otherwise returns a bool for the guaranteed comparison operation.
fn compareIntsOnlyPossibleResult(sema: *Sema, target: std.Target, lhs_val: Value, op: std.math.CompareOperator, rhs_ty: Type) ?bool {
    const rhs_info = rhs_ty.intInfo(target);
    const vs_zero = lhs_val.orderAgainstZeroAdvanced(sema) catch unreachable;
    const is_zero = vs_zero == .eq;
    const is_negative = vs_zero == .lt;
    const is_positive = vs_zero == .gt;

    // Anything vs. zero-sized type has guaranteed outcome.
    if (rhs_info.bits == 0) return switch (op) {
        .eq, .lte, .gte => is_zero,
        .neq, .lt, .gt => !is_zero,
    };

    // Special case for i1, which can only be 0 or -1.
    // Zero and positive ints have guaranteed outcome.
    if (rhs_info.bits == 1 and rhs_info.signedness == .signed) {
        if (is_positive) return switch (op) {
            .gt, .gte, .neq => true,
            .lt, .lte, .eq => false,
        };
        if (is_zero) return switch (op) {
            .gte => true,
            .lt => false,
            .gt, .lte, .eq, .neq => null,
        };
    }

    // Negative vs. unsigned has guaranteed outcome.
    if (rhs_info.signedness == .unsigned and is_negative) return switch (op) {
        .eq, .gt, .gte => false,
        .neq, .lt, .lte => true,
    };

    const sign_adj = @boolToInt(!is_negative and rhs_info.signedness == .signed);
    const req_bits = lhs_val.intBitCountTwosComp(target) + sign_adj;

    // No sized type can have more than 65535 bits.
    // The RHS type operand is either a runtime value or sized (but undefined) constant.
    if (req_bits > 65535) return switch (op) {
        .lt, .lte => is_negative,
        .gt, .gte => is_positive,
        .eq => false,
        .neq => true,
    };
    const fits = req_bits <= rhs_info.bits;

    // Oversized int has guaranteed outcome.
    switch (op) {
        .eq => return if (!fits) false else null,
        .neq => return if (!fits) true else null,
        .lt, .lte => if (!fits) return is_negative,
        .gt, .gte => if (!fits) return !is_negative,
    }

    // For any other comparison, we need to know if the LHS value is
    // equal to the maximum or minimum possible value of the RHS type.
    const edge: struct { min: bool, max: bool } = edge: {
        if (is_zero and rhs_info.signedness == .unsigned) break :edge .{
            .min = true,
            .max = false,
        };

        if (req_bits != rhs_info.bits) break :edge .{
            .min = false,
            .max = false,
        };

        var ty_buffer: Type.Payload.Bits = .{
            .base = .{ .tag = if (is_negative) .int_signed else .int_unsigned },
            .data = @intCast(u16, req_bits),
        };
        const ty = Type.initPayload(&ty_buffer.base);
        const pop_count = lhs_val.popCount(ty, target);

        if (is_negative) {
            break :edge .{
                .min = pop_count == 1,
                .max = false,
            };
        } else {
            break :edge .{
                .min = false,
                .max = pop_count == req_bits - sign_adj,
            };
        }
    };

    assert(fits);
    return switch (op) {
        .lt => if (edge.max) false else null,
        .lte => if (edge.min) true else null,
        .gt => if (edge.min) false else null,
        .gte => if (edge.max) true else null,
        .eq, .neq => unreachable,
    };
}

/// Asserts that lhs and rhs types are both vectors.
fn cmpVector(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    lhs: Air.Inst.Ref,
    rhs: Air.Inst.Ref,
    op: std.math.CompareOperator,
    lhs_src: LazySrcLoc,
    rhs_src: LazySrcLoc,
) CompileError!Air.Inst.Ref {
    const lhs_ty = sema.typeOf(lhs);
    const rhs_ty = sema.typeOf(rhs);
    assert(lhs_ty.zigTypeTag() == .Vector);
    assert(rhs_ty.zigTypeTag() == .Vector);
    try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);

    const result_ty = try Type.vector(sema.arena, lhs_ty.vectorLen(), Type.bool);

    const runtime_src: LazySrcLoc = src: {
        if (try sema.resolveMaybeUndefVal(lhs)) |lhs_val| {
            if (try sema.resolveMaybeUndefVal(rhs)) |rhs_val| {
                if (lhs_val.isUndef() or rhs_val.isUndef()) {
                    return sema.addConstUndef(result_ty);
                }
                const cmp_val = try sema.compareVector(lhs_val, op, rhs_val, lhs_ty);
                return sema.addConstant(result_ty, cmp_val);
            } else {
                break :src rhs_src;
            }
        } else {
            break :src lhs_src;
        }
    };

    try sema.requireRuntimeBlock(block, src, runtime_src);
    return block.addCmpVector(lhs, rhs, op);
}

fn wrapOptional(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    if (try sema.resolveMaybeUndefVal(inst)) |val| {
        return sema.addConstant(dest_ty, try Value.Tag.opt_payload.create(sema.arena, val));
    }

    try sema.requireRuntimeBlock(block, inst_src, null);
    return block.addTyOp(.wrap_optional, dest_ty, inst);
}

fn wrapErrorUnionPayload(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const dest_payload_ty = dest_ty.errorUnionPayload();
    const coerced = try sema.coerceExtra(block, dest_payload_ty, inst, inst_src, .{ .report_err = false });
    if (try sema.resolveMaybeUndefVal(coerced)) |val| {
        return sema.addConstant(dest_ty, try Value.Tag.eu_payload.create(sema.arena, val));
    }
    try sema.requireRuntimeBlock(block, inst_src, null);
    try sema.queueFullTypeResolution(dest_payload_ty);
    return block.addTyOp(.wrap_errunion_payload, dest_ty, coerced);
}

fn wrapErrorUnionSet(
    sema: *Sema,
    block: *Block,
    dest_ty: Type,
    inst: Air.Inst.Ref,
    inst_src: LazySrcLoc,
) !Air.Inst.Ref {
    const inst_ty = sema.typeOf(inst);
    const dest_err_set_ty = dest_ty.errorUnionSet();
    if (try sema.resolveMaybeUndefVal(inst)) |val| {
        switch (dest_err_set_ty.tag()) {
            .anyerror => {},
            .error_set_single => ok: {
                const expected_name = val.castTag(.@"error").?.data.name;
                const n = dest_err_set_ty.castTag(.error_set_single).?.data;
                if (mem.eql(u8, expected_name, n)) break :ok;
                return sema.failWithErrorSetCodeMissing(block, inst_src, dest_err_set_ty, inst_ty);
            },
            .error_set => {
                const expected_name = val.castTag(.@"error").?.data.name;
                const error_set = dest_err_set_ty.castTag(.error_set).?.data;
                if (!error_set.names.contains(expected_name)) {
                    return sema.failWithErrorSetCodeMissing(block, inst_src, dest_err_set_ty, inst_ty);
                }
            },
            .error_set_inferred => ok: {
                const expected_name = val.castTag(.@"error").?.data.name;
                const ies = dest_err_set_ty.castTag(.error_set_inferred).?.data;

                // We carefully do this in an order that avoids unnecessarily
                // resolving the destination error set type.
                if (ies.is_anyerror) break :ok;
                if (ies.errors.contains(expected_name)) break :ok;
                if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, dest_err_set_ty, inst_ty, inst_src, inst_src)) {
                    break :ok;
                }

                return sema.failWithErrorSetCodeMissing(block, inst_src, dest_err_set_ty, inst_ty);
            },
            .error_set_merged => {
                const expected_name = val.castTag(.@"error").?.data.name;
                const error_set = dest_err_set_ty.castTag(.error_set_merged).?.data;
                if (!error_set.contains(expected_name)) {
                    return sema.failWithErrorSetCodeMissing(block, inst_src, dest_err_set_ty, inst_ty);
                }
            },
            else => unreachable,
        }
        return sema.addConstant(dest_ty, val);
    }

    try sema.requireRuntimeBlock(block, inst_src, null);
    const coerced = try sema.coerce(block, dest_err_set_ty, inst, inst_src);
    return block.addTyOp(.wrap_errunion_err, dest_ty, coerced);
}

fn unionToTag(
    sema: *Sema,
    block: *Block,
    enum_ty: Type,
    un: Air.Inst.Ref,
    un_src: LazySrcLoc,
) !Air.Inst.Ref {
    if ((try sema.typeHasOnePossibleValue(enum_ty))) |opv| {
        return sema.addConstant(enum_ty, opv);
    }
    if (try sema.resolveMaybeUndefVal(un)) |un_val| {
        return sema.addConstant(enum_ty, un_val.unionTag());
    }
    try sema.requireRuntimeBlock(block, un_src, null);
    return block.addTyOp(.get_union_tag, enum_ty, un);
}

fn resolvePeerTypes(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    instructions: []const Air.Inst.Ref,
    candidate_srcs: Module.PeerTypeCandidateSrc,
) !Type {
    switch (instructions.len) {
        0 => return Type.initTag(.noreturn),
        1 => return sema.typeOf(instructions[0]),
        else => {},
    }

    const target = sema.mod.getTarget();

    var chosen = instructions[0];
    // If this is non-null then it does the following thing, depending on the chosen zigTypeTag().
    //  * ErrorSet: this is an override
    //  * ErrorUnion: this is an override of the error set only
    //  * other: at the end we make an ErrorUnion with the other thing and this
    var err_set_ty: ?Type = null;
    var any_are_null = false;
    var seen_const = false;
    var convert_to_slice = false;
    var chosen_i: usize = 0;
    for (instructions[1..], 0..) |candidate, candidate_i| {
        const candidate_ty = sema.typeOf(candidate);
        const chosen_ty = sema.typeOf(chosen);

        const candidate_ty_tag = try candidate_ty.zigTypeTagOrPoison();
        const chosen_ty_tag = try chosen_ty.zigTypeTagOrPoison();

        // If the candidate can coerce into our chosen type, we're done.
        // If the chosen type can coerce into the candidate, use that.
        if ((try sema.coerceInMemoryAllowed(block, chosen_ty, candidate_ty, false, target, src, src)) == .ok) {
            continue;
        }
        if ((try sema.coerceInMemoryAllowed(block, candidate_ty, chosen_ty, false, target, src, src)) == .ok) {
            chosen = candidate;
            chosen_i = candidate_i + 1;
            continue;
        }

        switch (candidate_ty_tag) {
            .NoReturn, .Undefined => continue,

            .Null => {
                any_are_null = true;
                continue;
            },

            .Int => switch (chosen_ty_tag) {
                .ComptimeInt => {
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
                .Int => {
                    const chosen_info = chosen_ty.intInfo(target);
                    const candidate_info = candidate_ty.intInfo(target);

                    if (chosen_info.bits < candidate_info.bits) {
                        chosen = candidate;
                        chosen_i = candidate_i + 1;
                    }
                    continue;
                },
                .Pointer => if (chosen_ty.ptrSize() == .C) continue,
                else => {},
            },
            .ComptimeInt => switch (chosen_ty_tag) {
                .Int, .Float, .ComptimeFloat => continue,
                .Pointer => if (chosen_ty.ptrSize() == .C) continue,
                else => {},
            },
            .Float => switch (chosen_ty_tag) {
                .Float => {
                    if (chosen_ty.floatBits(target) < candidate_ty.floatBits(target)) {
                        chosen = candidate;
                        chosen_i = candidate_i + 1;
                    }
                    continue;
                },
                .ComptimeFloat, .ComptimeInt => {
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
                else => {},
            },
            .ComptimeFloat => switch (chosen_ty_tag) {
                .Float => continue,
                .ComptimeInt => {
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
                else => {},
            },
            .Enum => switch (chosen_ty_tag) {
                .EnumLiteral => {
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
                .Union => continue,
                else => {},
            },
            .EnumLiteral => switch (chosen_ty_tag) {
                .Enum, .Union => continue,
                else => {},
            },
            .Union => switch (chosen_ty_tag) {
                .Enum, .EnumLiteral => {
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
                else => {},
            },
            .ErrorSet => switch (chosen_ty_tag) {
                .ErrorSet => {
                    // If chosen is superset of candidate, keep it.
                    // If candidate is superset of chosen, switch it.
                    // If neither is a superset, merge errors.
                    const chosen_set_ty = err_set_ty orelse chosen_ty;

                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, candidate_ty, src, src)) {
                        continue;
                    }
                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, candidate_ty, chosen_set_ty, src, src)) {
                        err_set_ty = null;
                        chosen = candidate;
                        chosen_i = candidate_i + 1;
                        continue;
                    }

                    err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, candidate_ty);
                    continue;
                },
                .ErrorUnion => {
                    const chosen_set_ty = err_set_ty orelse chosen_ty.errorUnionSet();

                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, candidate_ty, src, src)) {
                        continue;
                    }
                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, candidate_ty, chosen_set_ty, src, src)) {
                        err_set_ty = candidate_ty;
                        continue;
                    }

                    err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, candidate_ty);
                    continue;
                },
                else => {
                    if (err_set_ty) |chosen_set_ty| {
                        if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, candidate_ty, src, src)) {
                            continue;
                        }
                        if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, candidate_ty, chosen_set_ty, src, src)) {
                            err_set_ty = candidate_ty;
                            continue;
                        }

                        err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, candidate_ty);
                        continue;
                    } else {
                        err_set_ty = candidate_ty;
                        continue;
                    }
                },
            },
            .ErrorUnion => switch (chosen_ty_tag) {
                .ErrorSet => {
                    const chosen_set_ty = err_set_ty orelse chosen_ty;
                    const candidate_set_ty = candidate_ty.errorUnionSet();

                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, candidate_set_ty, src, src)) {
                        err_set_ty = chosen_set_ty;
                    } else if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, candidate_set_ty, chosen_set_ty, src, src)) {
                        err_set_ty = null;
                    } else {
                        err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, candidate_set_ty);
                    }
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },

                .ErrorUnion => {
                    const chosen_payload_ty = chosen_ty.errorUnionPayload();
                    const candidate_payload_ty = candidate_ty.errorUnionPayload();

                    const coerce_chosen = (try sema.coerceInMemoryAllowed(block, chosen_payload_ty, candidate_payload_ty, false, target, src, src)) == .ok;
                    const coerce_candidate = (try sema.coerceInMemoryAllowed(block, candidate_payload_ty, chosen_payload_ty, false, target, src, src)) == .ok;

                    if (coerce_chosen or coerce_candidate) {
                        // If we can coerce to the candidate, we switch to that
                        // type. This is the same logic as the bare (non-union)
                        // coercion check we do at the top of this func.
                        if (coerce_candidate) {
                            chosen = candidate;
                            chosen_i = candidate_i + 1;
                        }

                        const chosen_set_ty = err_set_ty orelse chosen_ty.errorUnionSet();
                        const candidate_set_ty = candidate_ty.errorUnionSet();

                        if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, candidate_set_ty, src, src)) {
                            err_set_ty = chosen_set_ty;
                        } else if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, candidate_set_ty, chosen_set_ty, src, src)) {
                            err_set_ty = candidate_set_ty;
                        } else {
                            err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, candidate_set_ty);
                        }
                        continue;
                    }
                },

                else => {
                    if (err_set_ty) |chosen_set_ty| {
                        const candidate_set_ty = candidate_ty.errorUnionSet();
                        if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, candidate_set_ty, src, src)) {
                            err_set_ty = chosen_set_ty;
                        } else if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, candidate_set_ty, chosen_set_ty, src, src)) {
                            err_set_ty = null;
                        } else {
                            err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, candidate_set_ty);
                        }
                    }
                    seen_const = seen_const or chosen_ty.isConstPtr();
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
            },
            .Pointer => {
                const cand_info = candidate_ty.ptrInfo().data;
                switch (chosen_ty_tag) {
                    .Pointer => {
                        const chosen_info = chosen_ty.ptrInfo().data;

                        seen_const = seen_const or !chosen_info.mutable or !cand_info.mutable;

                        // *[N]T to [*]T
                        // *[N]T to []T
                        if ((cand_info.size == .Many or cand_info.size == .Slice) and
                            chosen_info.size == .One and
                            chosen_info.pointee_type.zigTypeTag() == .Array)
                        {
                            // In case we see i.e.: `*[1]T`, `*[2]T`, `[*]T`
                            convert_to_slice = false;
                            chosen = candidate;
                            chosen_i = candidate_i + 1;
                            continue;
                        }
                        if (cand_info.size == .One and
                            cand_info.pointee_type.zigTypeTag() == .Array and
                            (chosen_info.size == .Many or chosen_info.size == .Slice))
                        {
                            // In case we see i.e.: `*[1]T`, `*[2]T`, `[*]T`
                            convert_to_slice = false;
                            continue;
                        }

                        // *[N]T and *[M]T
                        // Verify both are single-pointers to arrays.
                        // Keep the one whose element type can be coerced into.
                        if (chosen_info.size == .One and
                            cand_info.size == .One and
                            chosen_info.pointee_type.zigTypeTag() == .Array and
                            cand_info.pointee_type.zigTypeTag() == .Array)
                        {
                            const chosen_elem_ty = chosen_info.pointee_type.childType();
                            const cand_elem_ty = cand_info.pointee_type.childType();

                            const chosen_ok = .ok == try sema.coerceInMemoryAllowed(block, chosen_elem_ty, cand_elem_ty, chosen_info.mutable, target, src, src);
                            if (chosen_ok) {
                                convert_to_slice = true;
                                continue;
                            }

                            const cand_ok = .ok == try sema.coerceInMemoryAllowed(block, cand_elem_ty, chosen_elem_ty, cand_info.mutable, target, src, src);
                            if (cand_ok) {
                                convert_to_slice = true;
                                chosen = candidate;
                                chosen_i = candidate_i + 1;
                                continue;
                            }

                            // They're both bad. Report error.
                            // In the future we probably want to use the
                            // coerceInMemoryAllowed error reporting mechanism,
                            // however, for now we just fall through for the
                            // "incompatible types" error below.
                        }

                        // [*c]T and any other pointer size
                        // Whichever element type can coerce to the other one, is
                        // the one we will keep. If they're both OK then we keep the
                        // C pointer since it matches both single and many pointers.
                        if (cand_info.size == .C or chosen_info.size == .C) {
                            const cand_ok = .ok == try sema.coerceInMemoryAllowed(block, cand_info.pointee_type, chosen_info.pointee_type, cand_info.mutable, target, src, src);
                            const chosen_ok = .ok == try sema.coerceInMemoryAllowed(block, chosen_info.pointee_type, cand_info.pointee_type, chosen_info.mutable, target, src, src);

                            if (cand_ok) {
                                if (chosen_ok) {
                                    if (chosen_info.size == .C) {
                                        continue;
                                    } else {
                                        chosen = candidate;
                                        chosen_i = candidate_i + 1;
                                        continue;
                                    }
                                } else {
                                    chosen = candidate;
                                    chosen_i = candidate_i + 1;
                                    continue;
                                }
                            } else {
                                if (chosen_ok) {
                                    continue;
                                } else {
                                    // They're both bad. Report error.
                                    // In the future we probably want to use the
                                    // coerceInMemoryAllowed error reporting mechanism,
                                    // however, for now we just fall through for the
                                    // "incompatible types" error below.
                                }
                            }
                        }
                    },
                    .Int, .ComptimeInt => {
                        if (cand_info.size == .C) {
                            chosen = candidate;
                            chosen_i = candidate_i + 1;
                            continue;
                        }
                    },
                    .Optional => {
                        var opt_child_buf: Type.Payload.ElemType = undefined;
                        const chosen_ptr_ty = chosen_ty.optionalChild(&opt_child_buf);
                        if (chosen_ptr_ty.zigTypeTag() == .Pointer) {
                            const chosen_info = chosen_ptr_ty.ptrInfo().data;

                            seen_const = seen_const or !chosen_info.mutable or !cand_info.mutable;

                            // *[N]T to ?![*]T
                            // *[N]T to ?![]T
                            if (cand_info.size == .One and
                                cand_info.pointee_type.zigTypeTag() == .Array and
                                (chosen_info.size == .Many or chosen_info.size == .Slice))
                            {
                                continue;
                            }
                        }
                    },
                    .ErrorUnion => {
                        const chosen_ptr_ty = chosen_ty.errorUnionPayload();
                        if (chosen_ptr_ty.zigTypeTag() == .Pointer) {
                            const chosen_info = chosen_ptr_ty.ptrInfo().data;

                            seen_const = seen_const or !chosen_info.mutable or !cand_info.mutable;

                            // *[N]T to E![*]T
                            // *[N]T to E![]T
                            if (cand_info.size == .One and
                                cand_info.pointee_type.zigTypeTag() == .Array and
                                (chosen_info.size == .Many or chosen_info.size == .Slice))
                            {
                                continue;
                            }
                        }
                    },
                    .Fn => {
                        if (!cand_info.mutable and cand_info.pointee_type.zigTypeTag() == .Fn and .ok == try sema.coerceInMemoryAllowedFns(block, chosen_ty, cand_info.pointee_type, target, src, src)) {
                            chosen = candidate;
                            chosen_i = candidate_i + 1;
                            continue;
                        }
                    },
                    else => {},
                }
            },
            .Optional => {
                var opt_child_buf: Type.Payload.ElemType = undefined;
                const opt_child_ty = candidate_ty.optionalChild(&opt_child_buf);
                if ((try sema.coerceInMemoryAllowed(block, chosen_ty, opt_child_ty, false, target, src, src)) == .ok) {
                    seen_const = seen_const or opt_child_ty.isConstPtr();
                    any_are_null = true;
                    continue;
                }

                seen_const = seen_const or chosen_ty.isConstPtr();
                any_are_null = false;
                chosen = candidate;
                chosen_i = candidate_i + 1;
                continue;
            },
            .Vector => switch (chosen_ty_tag) {
                .Array => {
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                },
                else => {},
            },
            .Array => switch (chosen_ty_tag) {
                .Vector => continue,
                else => {},
            },
            .Fn => if (chosen_ty.isSinglePointer() and chosen_ty.isConstPtr() and chosen_ty.childType().zigTypeTag() == .Fn) {
                if (.ok == try sema.coerceInMemoryAllowedFns(block, chosen_ty.childType(), candidate_ty, target, src, src)) {
                    continue;
                }
            },
            else => {},
        }

        switch (chosen_ty_tag) {
            .NoReturn, .Undefined => {
                chosen = candidate;
                chosen_i = candidate_i + 1;
                continue;
            },
            .Null => {
                any_are_null = true;
                chosen = candidate;
                chosen_i = candidate_i + 1;
                continue;
            },
            .Optional => {
                var opt_child_buf: Type.Payload.ElemType = undefined;
                const opt_child_ty = chosen_ty.optionalChild(&opt_child_buf);
                if ((try sema.coerceInMemoryAllowed(block, opt_child_ty, candidate_ty, false, target, src, src)) == .ok) {
                    continue;
                }
                if ((try sema.coerceInMemoryAllowed(block, candidate_ty, opt_child_ty, false, target, src, src)) == .ok) {
                    any_are_null = true;
                    chosen = candidate;
                    chosen_i = candidate_i + 1;
                    continue;
                }
            },
            .ErrorUnion => {
                const payload_ty = chosen_ty.errorUnionPayload();
                if ((try sema.coerceInMemoryAllowed(block, payload_ty, candidate_ty, false, target, src, src)) == .ok) {
                    continue;
                }
            },
            .ErrorSet => {
                chosen = candidate;
                chosen_i = candidate_i + 1;
                if (err_set_ty) |chosen_set_ty| {
                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_set_ty, chosen_ty, src, src)) {
                        continue;
                    }
                    if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, chosen_ty, chosen_set_ty, src, src)) {
                        err_set_ty = chosen_ty;
                        continue;
                    }

                    err_set_ty = try chosen_set_ty.errorSetMerge(sema.arena, chosen_ty);
                    continue;
                } else {
                    err_set_ty = chosen_ty;
                    continue;
                }
            },
            else => {},
        }

        // At this point, we hit a compile error. We need to recover
        // the source locations.
        const chosen_src = candidate_srcs.resolve(
            sema.gpa,
            sema.mod.declPtr(block.src_decl),
            chosen_i,
        );
        const candidate_src = candidate_srcs.resolve(
            sema.gpa,
            sema.mod.declPtr(block.src_decl),
            candidate_i + 1,
        );

        const msg = msg: {
            const msg = try sema.errMsg(block, src, "incompatible types: '{}' and '{}'", .{
                chosen_ty.fmt(sema.mod),
                candidate_ty.fmt(sema.mod),
            });
            errdefer msg.destroy(sema.gpa);

            if (chosen_src) |src_loc|
                try sema.errNote(block, src_loc, msg, "type '{}' here", .{chosen_ty.fmt(sema.mod)});

            if (candidate_src) |src_loc|
                try sema.errNote(block, src_loc, msg, "type '{}' here", .{candidate_ty.fmt(sema.mod)});

            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }

    const chosen_ty = sema.typeOf(chosen);

    if (convert_to_slice) {
        // turn *[N]T => []T
        const chosen_child_ty = chosen_ty.childType();
        var info = chosen_ty.ptrInfo();
        info.data.sentinel = chosen_child_ty.sentinel();
        info.data.size = .Slice;
        info.data.mutable = !(seen_const or chosen_child_ty.isConstPtr());
        info.data.pointee_type = chosen_child_ty.elemType2();

        const new_ptr_ty = try Type.ptr(sema.arena, sema.mod, info.data);
        const opt_ptr_ty = if (any_are_null)
            try Type.optional(sema.arena, new_ptr_ty)
        else
            new_ptr_ty;
        const set_ty = err_set_ty orelse return opt_ptr_ty;
        return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, sema.mod);
    }

    if (seen_const) {
        // turn []T => []const T
        switch (chosen_ty.zigTypeTag()) {
            .ErrorUnion => {
                const ptr_ty = chosen_ty.errorUnionPayload();
                var info = ptr_ty.ptrInfo();
                info.data.mutable = false;
                const new_ptr_ty = try Type.ptr(sema.arena, sema.mod, info.data);
                const opt_ptr_ty = if (any_are_null)
                    try Type.optional(sema.arena, new_ptr_ty)
                else
                    new_ptr_ty;
                const set_ty = err_set_ty orelse chosen_ty.errorUnionSet();
                return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, sema.mod);
            },
            .Pointer => {
                var info = chosen_ty.ptrInfo();
                info.data.mutable = false;
                const new_ptr_ty = try Type.ptr(sema.arena, sema.mod, info.data);
                const opt_ptr_ty = if (any_are_null)
                    try Type.optional(sema.arena, new_ptr_ty)
                else
                    new_ptr_ty;
                const set_ty = err_set_ty orelse return opt_ptr_ty;
                return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, sema.mod);
            },
            else => return chosen_ty,
        }
    }

    if (any_are_null) {
        const opt_ty = switch (chosen_ty.zigTypeTag()) {
            .Null, .Optional => chosen_ty,
            else => try Type.optional(sema.arena, chosen_ty),
        };
        const set_ty = err_set_ty orelse return opt_ty;
        return try Type.errorUnion(sema.arena, set_ty, opt_ty, sema.mod);
    }

    if (err_set_ty) |ty| switch (chosen_ty.zigTypeTag()) {
        .ErrorSet => return ty,
        .ErrorUnion => {
            const payload_ty = chosen_ty.errorUnionPayload();
            return try Type.errorUnion(sema.arena, ty, payload_ty, sema.mod);
        },
        else => return try Type.errorUnion(sema.arena, ty, chosen_ty, sema.mod),
    };

    return chosen_ty;
}

pub fn resolveFnTypes(sema: *Sema, fn_info: Type.Payload.Function.Data) CompileError!void {
    try sema.resolveTypeFully(fn_info.return_type);

    if (sema.mod.comp.bin_file.options.error_return_tracing and fn_info.return_type.isError()) {
        // Ensure the type exists so that backends can assume that.
        _ = try sema.getBuiltinType("StackTrace");
    }

    for (fn_info.param_types) |param_ty| {
        try sema.resolveTypeFully(param_ty);
    }
}

/// Make it so that calling hash() and eql() on `val` will not assert due
/// to a type not having its layout resolved.
fn resolveLazyValue(sema: *Sema, val: Value) CompileError!void {
    switch (val.tag()) {
        .lazy_align => {
            const ty = val.castTag(.lazy_align).?.data;
            return sema.resolveTypeLayout(ty);
        },
        .lazy_size => {
            const ty = val.castTag(.lazy_size).?.data;
            return sema.resolveTypeLayout(ty);
        },
        .comptime_field_ptr => {
            const field_ptr = val.castTag(.comptime_field_ptr).?.data;
            return sema.resolveLazyValue(field_ptr.field_val);
        },
        .eu_payload,
        .opt_payload,
        => {
            const sub_val = val.cast(Value.Payload.SubValue).?.data;
            return sema.resolveLazyValue(sub_val);
        },
        .@"union" => {
            const union_val = val.castTag(.@"union").?.data;
            return sema.resolveLazyValue(union_val.val);
        },
        .aggregate => {
            const aggregate = val.castTag(.aggregate).?.data;
            for (aggregate) |elem_val| {
                try sema.resolveLazyValue(elem_val);
            }
        },
        else => return,
    }
}

pub fn resolveTypeLayout(sema: *Sema, ty: Type) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Struct => return sema.resolveStructLayout(ty),
        .Union => return sema.resolveUnionLayout(ty),
        .Array => {
            if (ty.arrayLenIncludingSentinel() == 0) return;
            const elem_ty = ty.childType();
            return sema.resolveTypeLayout(elem_ty);
        },
        .Optional => {
            var buf: Type.Payload.ElemType = undefined;
            const payload_ty = ty.optionalChild(&buf);
            // In case of querying the ABI alignment of this optional, we will ask
            // for hasRuntimeBits() of the payload type, so we need "requires comptime"
            // to be known already before this function returns.
            _ = try sema.typeRequiresComptime(payload_ty);
            return sema.resolveTypeLayout(payload_ty);
        },
        .ErrorUnion => {
            const payload_ty = ty.errorUnionPayload();
            return sema.resolveTypeLayout(payload_ty);
        },
        .Fn => {
            const info = ty.fnInfo();
            if (info.is_generic) {
                // Resolving of generic function types is deferred to when
                // the function is instantiated.
                return;
            }
            for (info.param_types) |param_ty| {
                try sema.resolveTypeLayout(param_ty);
            }
            try sema.resolveTypeLayout(info.return_type);
        },
        else => {},
    }
}

fn resolveStructLayout(sema: *Sema, ty: Type) CompileError!void {
    const resolved_ty = try sema.resolveTypeFields(ty);
    if (resolved_ty.castTag(.@"struct")) |payload| {
        const struct_obj = payload.data;
        switch (struct_obj.status) {
            .none, .have_field_types => {},
            .field_types_wip, .layout_wip => {
                const msg = try Module.ErrorMsg.create(
                    sema.gpa,
                    struct_obj.srcLoc(sema.mod),
                    "struct '{}' depends on itself",
                    .{ty.fmt(sema.mod)},
                );
                return sema.failWithOwnedErrorMsg(msg);
            },
            .have_layout, .fully_resolved_wip, .fully_resolved => return,
        }
        const prev_status = struct_obj.status;
        errdefer if (struct_obj.status == .layout_wip) {
            struct_obj.status = prev_status;
        };

        struct_obj.status = .layout_wip;
        for (struct_obj.fields.values(), 0..) |field, i| {
            sema.resolveTypeLayout(field.ty) catch |err| switch (err) {
                error.AnalysisFail => {
                    const msg = sema.err orelse return err;
                    try sema.addFieldErrNote(ty, i, msg, "while checking this field", .{});
                    return err;
                },
                else => return err,
            };
        }

        if (struct_obj.layout == .Packed) {
            try semaBackingIntType(sema.mod, struct_obj);
        }

        struct_obj.status = .have_layout;
        _ = try sema.resolveTypeRequiresComptime(resolved_ty);

        if (struct_obj.assumed_runtime_bits and !resolved_ty.hasRuntimeBits()) {
            const msg = try Module.ErrorMsg.create(
                sema.gpa,
                struct_obj.srcLoc(sema.mod),
                "struct layout depends on it having runtime bits",
                .{},
            );
            return sema.failWithOwnedErrorMsg(msg);
        }

        if (struct_obj.layout == .Auto and sema.mod.backendSupportsFeature(.field_reordering)) {
            const optimized_order = blk: {
                const decl = sema.mod.declPtr(struct_obj.owner_decl);
                var decl_arena = decl.value_arena.?.promote(sema.mod.gpa);
                defer decl.value_arena.?.* = decl_arena.state;
                const decl_arena_allocator = decl_arena.allocator();

                break :blk try decl_arena_allocator.alloc(u32, struct_obj.fields.count());
            };

            for (struct_obj.fields.values(), 0..) |field, i| {
                optimized_order[i] = if (field.ty.hasRuntimeBits())
                    @intCast(u32, i)
                else
                    Module.Struct.omitted_field;
            }

            const AlignSortContext = struct {
                struct_obj: *Module.Struct,
                sema: *Sema,

                fn lessThan(ctx: @This(), a: u32, b: u32) bool {
                    if (a == Module.Struct.omitted_field) return false;
                    if (b == Module.Struct.omitted_field) return true;
                    const target = ctx.sema.mod.getTarget();
                    return ctx.struct_obj.fields.values()[a].ty.abiAlignment(target) >
                        ctx.struct_obj.fields.values()[b].ty.abiAlignment(target);
                }
            };
            std.sort.sort(u32, optimized_order, AlignSortContext{
                .struct_obj = struct_obj,
                .sema = sema,
            }, AlignSortContext.lessThan);
            struct_obj.optimized_order = optimized_order.ptr;
        }
    }
    // otherwise it's a tuple; no need to resolve anything
}

fn semaBackingIntType(mod: *Module, struct_obj: *Module.Struct) CompileError!void {
    const gpa = mod.gpa;
    const target = mod.getTarget();

    var fields_bit_sum: u64 = 0;
    for (struct_obj.fields.values()) |field| {
        fields_bit_sum += field.ty.bitSize(target);
    }

    const decl_index = struct_obj.owner_decl;
    const decl = mod.declPtr(decl_index);
    var decl_arena = decl.value_arena.?.promote(gpa);
    defer decl.value_arena.?.* = decl_arena.state;
    const decl_arena_allocator = decl_arena.allocator();

    const zir = struct_obj.namespace.file_scope.zir;
    const extended = zir.instructions.items(.data)[struct_obj.zir_index].extended;
    assert(extended.opcode == .struct_decl);
    const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);

    if (small.has_backing_int) {
        var extra_index: usize = extended.operand;
        extra_index += @boolToInt(small.has_src_node);
        extra_index += @boolToInt(small.has_fields_len);
        extra_index += @boolToInt(small.has_decls_len);

        const backing_int_body_len = zir.extra[extra_index];
        extra_index += 1;

        var analysis_arena = std.heap.ArenaAllocator.init(gpa);
        defer analysis_arena.deinit();

        var sema: Sema = .{
            .mod = mod,
            .gpa = gpa,
            .arena = analysis_arena.allocator(),
            .perm_arena = decl_arena_allocator,
            .code = zir,
            .owner_decl = decl,
            .owner_decl_index = decl_index,
            .func = null,
            .fn_ret_ty = Type.void,
            .owner_func = null,
        };
        defer sema.deinit();

        var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
        defer wip_captures.deinit();

        var block: Block = .{
            .parent = null,
            .sema = &sema,
            .src_decl = decl_index,
            .namespace = &struct_obj.namespace,
            .wip_capture_scope = wip_captures.scope,
            .instructions = .{},
            .inlining = null,
            .is_comptime = true,
        };
        defer {
            assert(block.instructions.items.len == 0);
            block.params.deinit(gpa);
        }

        const backing_int_src: LazySrcLoc = .{ .node_offset_container_tag = 0 };
        const backing_int_ty = blk: {
            if (backing_int_body_len == 0) {
                const backing_int_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
                break :blk try sema.resolveType(&block, backing_int_src, backing_int_ref);
            } else {
                const body = zir.extra[extra_index..][0..backing_int_body_len];
                const ty_ref = try sema.resolveBody(&block, body, struct_obj.zir_index);
                break :blk try sema.analyzeAsType(&block, backing_int_src, ty_ref);
            }
        };

        try sema.checkBackingIntType(&block, backing_int_src, backing_int_ty, fields_bit_sum);
        struct_obj.backing_int_ty = try backing_int_ty.copy(decl_arena_allocator);
        try wip_captures.finalize();
    } else {
        if (fields_bit_sum > std.math.maxInt(u16)) {
            var sema: Sema = .{
                .mod = mod,
                .gpa = gpa,
                .arena = undefined,
                .perm_arena = decl_arena_allocator,
                .code = zir,
                .owner_decl = decl,
                .owner_decl_index = decl_index,
                .func = null,
                .fn_ret_ty = Type.void,
                .owner_func = null,
            };
            defer sema.deinit();

            var block: Block = .{
                .parent = null,
                .sema = &sema,
                .src_decl = decl_index,
                .namespace = &struct_obj.namespace,
                .wip_capture_scope = undefined,
                .instructions = .{},
                .inlining = null,
                .is_comptime = true,
            };
            return sema.fail(&block, LazySrcLoc.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});
        }
        var buf: Type.Payload.Bits = .{
            .base = .{ .tag = .int_unsigned },
            .data = @intCast(u16, fields_bit_sum),
        };
        struct_obj.backing_int_ty = try Type.initPayload(&buf.base).copy(decl_arena_allocator);
    }
}

fn checkBackingIntType(sema: *Sema, block: *Block, src: LazySrcLoc, backing_int_ty: Type, fields_bit_sum: u64) CompileError!void {
    const target = sema.mod.getTarget();

    if (!backing_int_ty.isInt()) {
        return sema.fail(block, src, "expected backing integer type, found '{}'", .{backing_int_ty.fmt(sema.mod)});
    }
    if (backing_int_ty.bitSize(target) != fields_bit_sum) {
        return sema.fail(
            block,
            src,
            "backing integer type '{}' has bit size {} but the struct fields have a total bit size of {}",
            .{ backing_int_ty.fmt(sema.mod), backing_int_ty.bitSize(target), fields_bit_sum },
        );
    }
}

fn checkIndexable(sema: *Sema, block: *Block, src: LazySrcLoc, array_ty: Type) !void {
    if (!array_ty.isIndexable()) {
        const msg = msg: {
            const msg = try sema.errMsg(
                block,
                src,
                "type '{}' does not support indexing",
                .{array_ty.fmt(sema.mod)},
            );
            errdefer msg.destroy(sema.gpa);
            try sema.errNote(
                block,
                src,
                msg,
                "for loop operand must be an array, slice, tuple, or vector",
                .{},
            );
            break :msg msg;
        };
        return sema.failWithOwnedErrorMsg(msg);
    }
}

fn resolveUnionLayout(sema: *Sema, ty: Type) CompileError!void {
    const resolved_ty = try sema.resolveTypeFields(ty);
    const union_obj = resolved_ty.cast(Type.Payload.Union).?.data;
    switch (union_obj.status) {
        .none, .have_field_types => {},
        .field_types_wip, .layout_wip => {
            const msg = try Module.ErrorMsg.create(
                sema.gpa,
                union_obj.srcLoc(sema.mod),
                "union '{}' depends on itself",
                .{ty.fmt(sema.mod)},
            );
            return sema.failWithOwnedErrorMsg(msg);
        },
        .have_layout, .fully_resolved_wip, .fully_resolved => return,
    }
    const prev_status = union_obj.status;
    errdefer if (union_obj.status == .layout_wip) {
        union_obj.status = prev_status;
    };

    union_obj.status = .layout_wip;
    for (union_obj.fields.values(), 0..) |field, i| {
        sema.resolveTypeLayout(field.ty) catch |err| switch (err) {
            error.AnalysisFail => {
                const msg = sema.err orelse return err;
                try sema.addFieldErrNote(ty, i, msg, "while checking this field", .{});
                return err;
            },
            else => return err,
        };
    }
    union_obj.status = .have_layout;
    _ = try sema.resolveTypeRequiresComptime(resolved_ty);

    if (union_obj.assumed_runtime_bits and !resolved_ty.hasRuntimeBits()) {
        const msg = try Module.ErrorMsg.create(
            sema.gpa,
            union_obj.srcLoc(sema.mod),
            "union layout depends on it having runtime bits",
            .{},
        );
        return sema.failWithOwnedErrorMsg(msg);
    }
}

// In case of querying the ABI alignment of this struct, we will ask
// for hasRuntimeBits() of each field, so we need "requires comptime"
// to be known already before this function returns.
pub fn resolveTypeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
    return switch (ty.tag()) {
        .u1,
        .u8,
        .i8,
        .u16,
        .i16,
        .u29,
        .u32,
        .i32,
        .u64,
        .i64,
        .u128,
        .i128,
        .usize,
        .isize,
        .c_short,
        .c_ushort,
        .c_int,
        .c_uint,
        .c_long,
        .c_ulong,
        .c_longlong,
        .c_ulonglong,
        .c_longdouble,
        .f16,
        .f32,
        .f64,
        .f80,
        .f128,
        .anyopaque,
        .bool,
        .void,
        .anyerror,
        .noreturn,
        .@"anyframe",
        .null,
        .undefined,
        .atomic_order,
        .atomic_rmw_op,
        .calling_convention,
        .address_space,
        .float_mode,
        .reduce_op,
        .modifier,
        .prefetch_options,
        .export_options,
        .extern_options,
        .manyptr_u8,
        .manyptr_const_u8,
        .manyptr_const_u8_sentinel_0,
        .const_slice_u8,
        .const_slice_u8_sentinel_0,
        .anyerror_void_error_union,
        .empty_struct_literal,
        .empty_struct,
        .error_set,
        .error_set_single,
        .error_set_inferred,
        .error_set_merged,
        .@"opaque",
        .generic_poison,
        .array_u8,
        .array_u8_sentinel_0,
        .int_signed,
        .int_unsigned,
        .enum_simple,
        => false,

        .single_const_pointer_to_comptime_int,
        .type,
        .comptime_int,
        .comptime_float,
        .enum_literal,
        .type_info,
        // These are function bodies, not function pointers.
        .fn_noreturn_no_args,
        .fn_void_no_args,
        .fn_naked_noreturn_no_args,
        .fn_ccc_void_no_args,
        .function,
        => true,

        .var_args_param => unreachable,
        .inferred_alloc_mut => unreachable,
        .inferred_alloc_const => unreachable,
        .bound_fn => unreachable,

        .array,
        .array_sentinel,
        .vector,
        => return sema.resolveTypeRequiresComptime(ty.childType()),

        .pointer,
        .single_const_pointer,
        .single_mut_pointer,
        .many_const_pointer,
        .many_mut_pointer,
        .c_const_pointer,
        .c_mut_pointer,
        .const_slice,
        .mut_slice,
        => {
            const child_ty = ty.childType();
            if (child_ty.zigTypeTag() == .Fn) {
                return child_ty.fnInfo().is_generic;
            } else {
                return sema.resolveTypeRequiresComptime(child_ty);
            }
        },

        .optional,
        .optional_single_mut_pointer,
        .optional_single_const_pointer,
        => {
            var buf: Type.Payload.ElemType = undefined;
            return sema.resolveTypeRequiresComptime(ty.optionalChild(&buf));
        },

        .tuple, .anon_struct => {
            const tuple = ty.tupleFields();
            for (tuple.types, 0..) |field_ty, i| {
                const have_comptime_val = tuple.values[i].tag() != .unreachable_value;
                if (!have_comptime_val and try sema.resolveTypeRequiresComptime(field_ty)) {
                    return true;
                }
            }
            return false;
        },

        .@"struct" => {
            const struct_obj = ty.castTag(.@"struct").?.data;
            switch (struct_obj.requires_comptime) {
                .no, .wip => return false,
                .yes => return true,
                .unknown => {
                    var requires_comptime = false;
                    struct_obj.requires_comptime = .wip;
                    for (struct_obj.fields.values()) |field| {
                        if (try sema.resolveTypeRequiresComptime(field.ty)) requires_comptime = true;
                    }
                    if (requires_comptime) {
                        struct_obj.requires_comptime = .yes;
                    } else {
                        struct_obj.requires_comptime = .no;
                    }
                    return requires_comptime;
                },
            }
        },

        .@"union", .union_safety_tagged, .union_tagged => {
            const union_obj = ty.cast(Type.Payload.Union).?.data;
            switch (union_obj.requires_comptime) {
                .no, .wip => return false,
                .yes => return true,
                .unknown => {
                    var requires_comptime = false;
                    union_obj.requires_comptime = .wip;
                    for (union_obj.fields.values()) |field| {
                        if (try sema.resolveTypeRequiresComptime(field.ty)) requires_comptime = true;
                    }
                    if (requires_comptime) {
                        union_obj.requires_comptime = .yes;
                    } else {
                        union_obj.requires_comptime = .no;
                    }
                    return requires_comptime;
                },
            }
        },

        .error_union => return sema.resolveTypeRequiresComptime(ty.errorUnionPayload()),
        .anyframe_T => {
            const child_ty = ty.castTag(.anyframe_T).?.data;
            return sema.resolveTypeRequiresComptime(child_ty);
        },
        .enum_numbered => {
            const tag_ty = ty.castTag(.enum_numbered).?.data.tag_ty;
            return sema.resolveTypeRequiresComptime(tag_ty);
        },
        .enum_full, .enum_nonexhaustive => {
            const tag_ty = ty.cast(Type.Payload.EnumFull).?.data.tag_ty;
            return sema.resolveTypeRequiresComptime(tag_ty);
        },
    };
}

/// Returns `error.AnalysisFail` if any of the types (recursively) failed to
/// be resolved.
pub fn resolveTypeFully(sema: *Sema, ty: Type) CompileError!void {
    switch (ty.zigTypeTag()) {
        .Pointer => {
            const child_ty = try sema.resolveTypeFields(ty.childType());
            return sema.resolveTypeFully(child_ty);
        },
        .Struct => switch (ty.tag()) {
            .@"struct" => return sema.resolveStructFully(ty),
            .tuple, .anon_struct => {
                const tuple = ty.tupleFields();

                for (tuple.types) |field_ty| {
                    try sema.resolveTypeFully(field_ty);
                }
            },
            else => {},
        },
        .Union => return sema.resolveUnionFully(ty),
        .Array => return sema.resolveTypeFully(ty.childType()),
        .Optional => {
            var buf: Type.Payload.ElemType = undefined;
            return sema.resolveTypeFully(ty.optionalChild(&buf));
        },
        .ErrorUnion => return sema.resolveTypeFully(ty.errorUnionPayload()),
        .Fn => {
            const info = ty.fnInfo();
            if (info.is_generic) {
                // Resolving of generic function types is deferred to when
                // the function is instantiated.
                return;
            }
            for (info.param_types) |param_ty| {
                try sema.resolveTypeFully(param_ty);
            }
            try sema.resolveTypeFully(info.return_type);
        },
        else => {},
    }
}

fn resolveStructFully(sema: *Sema, ty: Type) CompileError!void {
    try sema.resolveStructLayout(ty);

    const resolved_ty = try sema.resolveTypeFields(ty);
    const payload = resolved_ty.castTag(.@"struct").?;
    const struct_obj = payload.data;

    switch (struct_obj.status) {
        .none, .have_field_types, .field_types_wip, .layout_wip, .have_layout => {},
        .fully_resolved_wip, .fully_resolved => return,
    }

    {
        // After we have resolve struct layout we have to go over the fields again to
        // make sure pointer fields get their child types resolved as well.
        // See also similar code for unions.
        const prev_status = struct_obj.status;
        errdefer struct_obj.status = prev_status;

        struct_obj.status = .fully_resolved_wip;
        for (struct_obj.fields.values()) |field| {
            try sema.resolveTypeFully(field.ty);
        }
        struct_obj.status = .fully_resolved;
    }

    // And let's not forget comptime-only status.
    _ = try sema.typeRequiresComptime(ty);
}

fn resolveUnionFully(sema: *Sema, ty: Type) CompileError!void {
    try sema.resolveUnionLayout(ty);

    const resolved_ty = try sema.resolveTypeFields(ty);
    const union_obj = resolved_ty.cast(Type.Payload.Union).?.data;
    switch (union_obj.status) {
        .none, .have_field_types, .field_types_wip, .layout_wip, .have_layout => {},
        .fully_resolved_wip, .fully_resolved => return,
    }

    {
        // After we have resolve union layout we have to go over the fields again to
        // make sure pointer fields get their child types resolved as well.
        // See also similar code for structs.
        const prev_status = union_obj.status;
        errdefer union_obj.status = prev_status;

        union_obj.status = .fully_resolved_wip;
        for (union_obj.fields.values()) |field| {
            try sema.resolveTypeFully(field.ty);
        }
        union_obj.status = .fully_resolved;
    }

    // And let's not forget comptime-only status.
    _ = try sema.typeRequiresComptime(ty);
}

pub fn resolveTypeFields(sema: *Sema, ty: Type) CompileError!Type {
    switch (ty.tag()) {
        .@"struct" => {
            const struct_obj = ty.castTag(.@"struct").?.data;
            try sema.resolveTypeFieldsStruct(ty, struct_obj);
            return ty;
        },
        .@"union", .union_safety_tagged, .union_tagged => {
            const union_obj = ty.cast(Type.Payload.Union).?.data;
            try sema.resolveTypeFieldsUnion(ty, union_obj);
            return ty;
        },
        .type_info => return sema.getBuiltinType("Type"),
        .extern_options => return sema.getBuiltinType("ExternOptions"),
        .export_options => return sema.getBuiltinType("ExportOptions"),
        .atomic_order => return sema.getBuiltinType("AtomicOrder"),
        .atomic_rmw_op => return sema.getBuiltinType("AtomicRmwOp"),
        .calling_convention => return sema.getBuiltinType("CallingConvention"),
        .address_space => return sema.getBuiltinType("AddressSpace"),
        .float_mode => return sema.getBuiltinType("FloatMode"),
        .reduce_op => return sema.getBuiltinType("ReduceOp"),
        .modifier => return sema.getBuiltinType("CallModifier"),
        .prefetch_options => return sema.getBuiltinType("PrefetchOptions"),

        else => return ty,
    }
}

fn resolveTypeFieldsStruct(
    sema: *Sema,
    ty: Type,
    struct_obj: *Module.Struct,
) CompileError!void {
    switch (sema.mod.declPtr(struct_obj.owner_decl).analysis) {
        .file_failure,
        .dependency_failure,
        .sema_failure,
        .sema_failure_retryable,
        => {
            sema.owner_decl.analysis = .dependency_failure;
            sema.owner_decl.generation = sema.mod.generation;
            return error.AnalysisFail;
        },
        else => {},
    }
    switch (struct_obj.status) {
        .none => {},
        .field_types_wip => {
            const msg = try Module.ErrorMsg.create(
                sema.gpa,
                struct_obj.srcLoc(sema.mod),
                "struct '{}' depends on itself",
                .{ty.fmt(sema.mod)},
            );
            return sema.failWithOwnedErrorMsg(msg);
        },
        .have_field_types,
        .have_layout,
        .layout_wip,
        .fully_resolved_wip,
        .fully_resolved,
        => return,
    }

    struct_obj.status = .field_types_wip;
    errdefer struct_obj.status = .none;
    try semaStructFields(sema.mod, struct_obj);
}

fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_obj: *Module.Union) CompileError!void {
    switch (sema.mod.declPtr(union_obj.owner_decl).analysis) {
        .file_failure,
        .dependency_failure,
        .sema_failure,
        .sema_failure_retryable,
        => {
            sema.owner_decl.analysis = .dependency_failure;
            sema.owner_decl.generation = sema.mod.generation;
            return error.AnalysisFail;
        },
        else => {},
    }
    switch (union_obj.status) {
        .none => {},
        .field_types_wip => {
            const msg = try Module.ErrorMsg.create(
                sema.gpa,
                union_obj.srcLoc(sema.mod),
                "union '{}' depends on itself",
                .{ty.fmt(sema.mod)},
            );
            return sema.failWithOwnedErrorMsg(msg);
        },
        .have_field_types,
        .have_layout,
        .layout_wip,
        .fully_resolved_wip,
        .fully_resolved,
        => return,
    }

    union_obj.status = .field_types_wip;
    errdefer union_obj.status = .none;
    try semaUnionFields(sema.mod, union_obj);
    union_obj.status = .have_field_types;
}

fn resolveInferredErrorSet(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ies: *Module.Fn.InferredErrorSet,
) CompileError!void {
    if (ies.is_resolved) return;

    if (ies.func.state == .in_progress) {
        return sema.fail(block, src, "unable to resolve inferred error set", .{});
    }

    // In order to ensure that all dependencies are properly added to the set, we
    // need to ensure the function body is analyzed of the inferred error set.
    // However, in the case of comptime/inline function calls with inferred error sets,
    // each call gets a new InferredErrorSet object, which points to the same
    // `*Module.Fn`. Not only is the function not relevant to the inferred error set
    // in this case, it may be a generic function which would cause an assertion failure
    // if we called `ensureFuncBodyAnalyzed` on it here.
    const ies_func_owner_decl = sema.mod.declPtr(ies.func.owner_decl);
    const ies_func_info = ies_func_owner_decl.ty.fnInfo();
    // if ies declared by a inline function with generic return type, the return_type should be generic_poison,
    // because inline function does not create a new declaration, and the ies has been filled with analyzeCall,
    // so here we can simply skip this case.
    if (ies_func_info.return_type.tag() == .generic_poison) {
        assert(ies_func_info.cc == .Inline);
    } else if (ies_func_info.return_type.errorUnionSet().castTag(.error_set_inferred).?.data == ies) {
        // In this case we are dealing with the actual InferredErrorSet object that
        // corresponds to the function, not one created to track an inline/comptime call.
        try sema.ensureFuncBodyAnalyzed(ies.func);
    }

    ies.is_resolved = true;

    for (ies.inferred_error_sets.keys()) |other_ies| {
        if (ies == other_ies) continue;
        try sema.resolveInferredErrorSet(block, src, other_ies);

        for (other_ies.errors.keys()) |key| {
            try ies.errors.put(sema.gpa, key, {});
        }
        if (other_ies.is_anyerror)
            ies.is_anyerror = true;
    }
}

fn resolveInferredErrorSetTy(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    ty: Type,
) CompileError!void {
    if (ty.castTag(.error_set_inferred)) |inferred| {
        try sema.resolveInferredErrorSet(block, src, inferred.data);
    }
}

fn semaStructFields(mod: *Module, struct_obj: *Module.Struct) CompileError!void {
    const gpa = mod.gpa;
    const decl_index = struct_obj.owner_decl;
    const zir = struct_obj.namespace.file_scope.zir;
    const extended = zir.instructions.items(.data)[struct_obj.zir_index].extended;
    assert(extended.opcode == .struct_decl);
    const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);
    var extra_index: usize = extended.operand;

    const src = LazySrcLoc.nodeOffset(0);
    extra_index += @boolToInt(small.has_src_node);

    const fields_len = if (small.has_fields_len) blk: {
        const fields_len = zir.extra[extra_index];
        extra_index += 1;
        break :blk fields_len;
    } else 0;

    const decls_len = if (small.has_decls_len) decls_len: {
        const decls_len = zir.extra[extra_index];
        extra_index += 1;
        break :decls_len decls_len;
    } else 0;

    // The backing integer cannot be handled until `resolveStructLayout()`.
    if (small.has_backing_int) {
        const backing_int_body_len = zir.extra[extra_index];
        extra_index += 1; // backing_int_body_len
        if (backing_int_body_len == 0) {
            extra_index += 1; // backing_int_ref
        } else {
            extra_index += backing_int_body_len; // backing_int_body_inst
        }
    }

    // Skip over decls.
    var decls_it = zir.declIteratorInner(extra_index, decls_len);
    while (decls_it.next()) |_| {}
    extra_index = decls_it.extra_index;

    if (fields_len == 0) {
        if (struct_obj.layout == .Packed) {
            try semaBackingIntType(mod, struct_obj);
        }
        struct_obj.status = .have_layout;
        return;
    }

    const decl = mod.declPtr(decl_index);
    var decl_arena = decl.value_arena.?.promote(gpa);
    defer decl.value_arena.?.* = decl_arena.state;
    const decl_arena_allocator = decl_arena.allocator();

    var analysis_arena = std.heap.ArenaAllocator.init(gpa);
    defer analysis_arena.deinit();

    var sema: Sema = .{
        .mod = mod,
        .gpa = gpa,
        .arena = analysis_arena.allocator(),
        .perm_arena = decl_arena_allocator,
        .code = zir,
        .owner_decl = decl,
        .owner_decl_index = decl_index,
        .func = null,
        .fn_ret_ty = Type.void,
        .owner_func = null,
    };
    defer sema.deinit();

    var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
    defer wip_captures.deinit();

    var block_scope: Block = .{
        .parent = null,
        .sema = &sema,
        .src_decl = decl_index,
        .namespace = &struct_obj.namespace,
        .wip_capture_scope = wip_captures.scope,
        .instructions = .{},
        .inlining = null,
        .is_comptime = true,
    };
    defer {
        assert(block_scope.instructions.items.len == 0);
        block_scope.params.deinit(gpa);
    }

    struct_obj.fields = .{};
    try struct_obj.fields.ensureTotalCapacity(decl_arena_allocator, fields_len);

    const Field = struct {
        type_body_len: u32 = 0,
        align_body_len: u32 = 0,
        init_body_len: u32 = 0,
        type_ref: Air.Inst.Ref = .none,
    };
    const fields = try sema.arena.alloc(Field, fields_len);
    var any_inits = false;

    {
        const bits_per_field = 4;
        const fields_per_u32 = 32 / bits_per_field;
        const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
        const flags_index = extra_index;
        var bit_bag_index: usize = flags_index;
        extra_index += bit_bags_count;
        var cur_bit_bag: u32 = undefined;
        var field_i: u32 = 0;
        while (field_i < fields_len) : (field_i += 1) {
            if (field_i % fields_per_u32 == 0) {
                cur_bit_bag = zir.extra[bit_bag_index];
                bit_bag_index += 1;
            }
            const has_align = @truncate(u1, cur_bit_bag) != 0;
            cur_bit_bag >>= 1;
            const has_init = @truncate(u1, cur_bit_bag) != 0;
            cur_bit_bag >>= 1;
            const is_comptime = @truncate(u1, cur_bit_bag) != 0;
            cur_bit_bag >>= 1;
            const has_type_body = @truncate(u1, cur_bit_bag) != 0;
            cur_bit_bag >>= 1;

            var field_name_zir: ?[:0]const u8 = null;
            if (!small.is_tuple) {
                field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]);
                extra_index += 1;
            }
            extra_index += 1; // doc_comment

            fields[field_i] = .{};

            if (has_type_body) {
                fields[field_i].type_body_len = zir.extra[extra_index];
            } else {
                fields[field_i].type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
            }
            extra_index += 1;

            // This string needs to outlive the ZIR code.
            const field_name = if (field_name_zir) |some|
                try decl_arena_allocator.dupe(u8, some)
            else
                try std.fmt.allocPrint(decl_arena_allocator, "{d}", .{field_i});

            const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
            if (gop.found_existing) {
                const msg = msg: {
                    const field_src = struct_obj.fieldSrcLoc(sema.mod, .{ .index = field_i }).lazy;
                    const msg = try sema.errMsg(&block_scope, field_src, "duplicate struct field: '{s}'", .{field_name});
                    errdefer msg.destroy(gpa);

                    const prev_field_index = struct_obj.fields.getIndex(field_name).?;
                    const prev_field_src = struct_obj.fieldSrcLoc(sema.mod, .{ .index = prev_field_index });
                    try sema.mod.errNoteNonLazy(prev_field_src, msg, "other field here", .{});
                    try sema.errNote(&block_scope, src, msg, "struct declared here", .{});
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
            gop.value_ptr.* = .{
                .ty = Type.initTag(.noreturn),
                .abi_align = 0,
                .default_val = Value.initTag(.unreachable_value),
                .is_comptime = is_comptime,
                .offset = undefined,
            };

            if (has_align) {
                fields[field_i].align_body_len = zir.extra[extra_index];
                extra_index += 1;
            }
            if (has_init) {
                fields[field_i].init_body_len = zir.extra[extra_index];
                extra_index += 1;
                any_inits = true;
            }
        }
    }

    // Next we do only types and alignments, saving the inits for a second pass,
    // so that init values may depend on type layout.
    const bodies_index = extra_index;

    for (fields, 0..) |zir_field, field_i| {
        const field_ty: Type = ty: {
            if (zir_field.type_ref != .none) {
                break :ty sema.resolveType(&block_scope, .unneeded, zir_field.type_ref) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const ty_src = struct_obj.fieldSrcLoc(sema.mod, .{
                            .index = field_i,
                            .range = .type,
                        }).lazy;
                        _ = try sema.resolveType(&block_scope, ty_src, zir_field.type_ref);
                        unreachable;
                    },
                    else => |e| return e,
                };
            }
            assert(zir_field.type_body_len != 0);
            const body = zir.extra[extra_index..][0..zir_field.type_body_len];
            extra_index += body.len;
            const ty_ref = try sema.resolveBody(&block_scope, body, struct_obj.zir_index);
            break :ty sema.analyzeAsType(&block_scope, .unneeded, ty_ref) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const ty_src = struct_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .type,
                    }).lazy;
                    _ = try sema.analyzeAsType(&block_scope, ty_src, ty_ref);
                    unreachable;
                },
                else => |e| return e,
            };
        };
        if (field_ty.tag() == .generic_poison) {
            return error.GenericPoison;
        }

        const field = &struct_obj.fields.values()[field_i];
        field.ty = try field_ty.copy(decl_arena_allocator);

        if (field_ty.zigTypeTag() == .Opaque) {
            const msg = msg: {
                const ty_src = struct_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                }).lazy;
                const msg = try sema.errMsg(&block_scope, ty_src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});
                errdefer msg.destroy(sema.gpa);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (field_ty.zigTypeTag() == .NoReturn) {
            const msg = msg: {
                const ty_src = struct_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                }).lazy;
                const msg = try sema.errMsg(&block_scope, ty_src, "struct fields cannot be 'noreturn'", .{});
                errdefer msg.destroy(sema.gpa);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (struct_obj.layout == .Extern and !try sema.validateExternType(field.ty, .struct_field)) {
            const msg = msg: {
                const ty_src = struct_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                });
                const msg = try sema.errMsg(&block_scope, ty_src.lazy, "extern structs cannot contain fields of type '{}'", .{field.ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                try sema.explainWhyTypeIsNotExtern(msg, ty_src, field.ty, .struct_field);

                try sema.addDeclaredHereNote(msg, field.ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        } else if (struct_obj.layout == .Packed and !(validatePackedType(field.ty))) {
            const msg = msg: {
                const ty_src = struct_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                });
                const msg = try sema.errMsg(&block_scope, ty_src.lazy, "packed structs cannot contain fields of type '{}'", .{field.ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                try sema.explainWhyTypeIsNotPacked(msg, ty_src, field.ty);

                try sema.addDeclaredHereNote(msg, field.ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }

        if (zir_field.align_body_len > 0) {
            const body = zir.extra[extra_index..][0..zir_field.align_body_len];
            extra_index += body.len;
            const align_ref = try sema.resolveBody(&block_scope, body, struct_obj.zir_index);
            field.abi_align = sema.analyzeAsAlign(&block_scope, .unneeded, align_ref) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const align_src = struct_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .alignment,
                    }).lazy;
                    _ = try sema.analyzeAsAlign(&block_scope, align_src, align_ref);
                    unreachable;
                },
                else => |e| return e,
            };
        }

        extra_index += zir_field.init_body_len;
    }

    struct_obj.status = .have_field_types;

    if (any_inits) {
        extra_index = bodies_index;
        for (fields, 0..) |zir_field, field_i| {
            extra_index += zir_field.type_body_len;
            extra_index += zir_field.align_body_len;
            if (zir_field.init_body_len > 0) {
                const body = zir.extra[extra_index..][0..zir_field.init_body_len];
                extra_index += body.len;
                const init = try sema.resolveBody(&block_scope, body, struct_obj.zir_index);
                const field = &struct_obj.fields.values()[field_i];
                const coerced = sema.coerce(&block_scope, field.ty, init, .unneeded) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const init_src = struct_obj.fieldSrcLoc(sema.mod, .{
                            .index = field_i,
                            .range = .value,
                        }).lazy;
                        _ = try sema.coerce(&block_scope, field.ty, init, init_src);
                        unreachable;
                    },
                    else => |e| return e,
                };
                const default_val = (try sema.resolveMaybeUndefVal(coerced)) orelse {
                    const init_src = struct_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .value,
                    }).lazy;
                    return sema.failWithNeededComptime(&block_scope, init_src, "struct field default value must be comptime-known");
                };
                field.default_val = try default_val.copy(decl_arena_allocator);
            }
        }
    }
    try wip_captures.finalize();

    struct_obj.have_field_inits = true;
}

fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
    const tracy = trace(@src());
    defer tracy.end();

    const gpa = mod.gpa;
    const decl_index = union_obj.owner_decl;
    const zir = union_obj.namespace.file_scope.zir;
    const extended = zir.instructions.items(.data)[union_obj.zir_index].extended;
    assert(extended.opcode == .union_decl);
    const small = @bitCast(Zir.Inst.UnionDecl.Small, extended.small);
    var extra_index: usize = extended.operand;

    const src = LazySrcLoc.nodeOffset(0);
    extra_index += @boolToInt(small.has_src_node);

    const tag_type_ref: Zir.Inst.Ref = if (small.has_tag_type) blk: {
        const ty_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
        extra_index += 1;
        break :blk ty_ref;
    } else .none;

    const body_len = if (small.has_body_len) blk: {
        const body_len = zir.extra[extra_index];
        extra_index += 1;
        break :blk body_len;
    } else 0;

    const fields_len = if (small.has_fields_len) blk: {
        const fields_len = zir.extra[extra_index];
        extra_index += 1;
        break :blk fields_len;
    } else 0;

    const decls_len = if (small.has_decls_len) decls_len: {
        const decls_len = zir.extra[extra_index];
        extra_index += 1;
        break :decls_len decls_len;
    } else 0;

    // Skip over decls.
    var decls_it = zir.declIteratorInner(extra_index, decls_len);
    while (decls_it.next()) |_| {}
    extra_index = decls_it.extra_index;

    const body = zir.extra[extra_index..][0..body_len];
    extra_index += body.len;

    const decl = mod.declPtr(decl_index);

    var decl_arena = decl.value_arena.?.promote(gpa);
    defer decl.value_arena.?.* = decl_arena.state;
    const decl_arena_allocator = decl_arena.allocator();

    var analysis_arena = std.heap.ArenaAllocator.init(gpa);
    defer analysis_arena.deinit();

    var sema: Sema = .{
        .mod = mod,
        .gpa = gpa,
        .arena = analysis_arena.allocator(),
        .perm_arena = decl_arena_allocator,
        .code = zir,
        .owner_decl = decl,
        .owner_decl_index = decl_index,
        .func = null,
        .fn_ret_ty = Type.void,
        .owner_func = null,
    };
    defer sema.deinit();

    var wip_captures = try WipCaptureScope.init(gpa, decl_arena_allocator, decl.src_scope);
    defer wip_captures.deinit();

    var block_scope: Block = .{
        .parent = null,
        .sema = &sema,
        .src_decl = decl_index,
        .namespace = &union_obj.namespace,
        .wip_capture_scope = wip_captures.scope,
        .instructions = .{},
        .inlining = null,
        .is_comptime = true,
    };
    defer {
        assert(block_scope.instructions.items.len == 0);
        block_scope.params.deinit(gpa);
    }

    if (body.len != 0) {
        try sema.analyzeBody(&block_scope, body);
    }

    try wip_captures.finalize();

    try union_obj.fields.ensureTotalCapacity(decl_arena_allocator, fields_len);

    var int_tag_ty: Type = undefined;
    var enum_field_names: ?*Module.EnumNumbered.NameMap = null;
    var enum_value_map: ?*Module.EnumNumbered.ValueMap = null;
    var tag_ty_field_names: ?Module.EnumFull.NameMap = null;
    if (tag_type_ref != .none) {
        const tag_ty_src: LazySrcLoc = .{ .node_offset_container_tag = src.node_offset.x };
        const provided_ty = try sema.resolveType(&block_scope, tag_ty_src, tag_type_ref);
        if (small.auto_enum_tag) {
            // The provided type is an integer type and we must construct the enum tag type here.
            int_tag_ty = provided_ty;
            if (int_tag_ty.zigTypeTag() != .Int and int_tag_ty.zigTypeTag() != .ComptimeInt) {
                return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(sema.mod)});
            }

            if (fields_len > 0) {
                var field_count_val: Value.Payload.U64 = .{
                    .base = .{ .tag = .int_u64 },
                    .data = fields_len - 1,
                };
                if (!(try sema.intFitsInType(Value.initPayload(&field_count_val.base), int_tag_ty, null))) {
                    const msg = msg: {
                        const msg = try sema.errMsg(&block_scope, tag_ty_src, "specified integer tag type cannot represent every field", .{});
                        errdefer msg.destroy(sema.gpa);
                        try sema.errNote(&block_scope, tag_ty_src, msg, "type '{}' cannot fit values in range 0...{d}", .{
                            int_tag_ty.fmt(sema.mod),
                            fields_len - 1,
                        });
                        break :msg msg;
                    };
                    return sema.failWithOwnedErrorMsg(msg);
                }
            }
            union_obj.tag_ty = try sema.generateUnionTagTypeNumbered(&block_scope, fields_len, provided_ty, union_obj);
            const enum_obj = union_obj.tag_ty.castTag(.enum_numbered).?.data;
            enum_field_names = &enum_obj.fields;
            enum_value_map = &enum_obj.values;
        } else {
            // The provided type is the enum tag type.
            union_obj.tag_ty = try provided_ty.copy(decl_arena_allocator);
            if (union_obj.tag_ty.zigTypeTag() != .Enum) {
                return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{union_obj.tag_ty.fmt(sema.mod)});
            }
            // The fields of the union must match the enum exactly.
            // Store a copy of the enum field names so we can check for
            // missing or extraneous fields later.
            tag_ty_field_names = try union_obj.tag_ty.enumFields().clone(sema.arena);
        }
    } else {
        // If auto_enum_tag is false, this is an untagged union. However, for semantic analysis
        // purposes, we still auto-generate an enum tag type the same way. That the union is
        // untagged is represented by the Type tag (union vs union_tagged).
        union_obj.tag_ty = try sema.generateUnionTagTypeSimple(&block_scope, fields_len, union_obj);
        enum_field_names = &union_obj.tag_ty.castTag(.enum_simple).?.data.fields;
    }

    if (fields_len == 0) {
        return;
    }

    const bits_per_field = 4;
    const fields_per_u32 = 32 / bits_per_field;
    const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
    var bit_bag_index: usize = extra_index;
    extra_index += bit_bags_count;
    var cur_bit_bag: u32 = undefined;
    var field_i: u32 = 0;
    var last_tag_val: ?Value = null;
    while (field_i < fields_len) : (field_i += 1) {
        if (field_i % fields_per_u32 == 0) {
            cur_bit_bag = zir.extra[bit_bag_index];
            bit_bag_index += 1;
        }
        const has_type = @truncate(u1, cur_bit_bag) != 0;
        cur_bit_bag >>= 1;
        const has_align = @truncate(u1, cur_bit_bag) != 0;
        cur_bit_bag >>= 1;
        const has_tag = @truncate(u1, cur_bit_bag) != 0;
        cur_bit_bag >>= 1;
        const unused = @truncate(u1, cur_bit_bag) != 0;
        cur_bit_bag >>= 1;
        _ = unused;

        const field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]);
        extra_index += 1;

        // doc_comment
        extra_index += 1;

        const field_type_ref: Zir.Inst.Ref = if (has_type) blk: {
            const field_type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
            extra_index += 1;
            break :blk field_type_ref;
        } else .none;

        const align_ref: Zir.Inst.Ref = if (has_align) blk: {
            const align_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
            extra_index += 1;
            break :blk align_ref;
        } else .none;

        const tag_ref: Zir.Inst.Ref = if (has_tag) blk: {
            const tag_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
            extra_index += 1;
            break :blk try sema.resolveInst(tag_ref);
        } else .none;

        if (enum_value_map) |map| {
            const copied_val = if (tag_ref != .none) blk: {
                const val = sema.semaUnionFieldVal(&block_scope, .unneeded, int_tag_ty, tag_ref) catch |err| switch (err) {
                    error.NeededSourceLocation => {
                        const val_src = union_obj.fieldSrcLoc(sema.mod, .{
                            .index = field_i,
                            .range = .value,
                        }).lazy;
                        _ = try sema.semaUnionFieldVal(&block_scope, val_src, int_tag_ty, tag_ref);
                        unreachable;
                    },
                    else => |e| return e,
                };
                last_tag_val = val;

                // This puts the memory into the union arena, not the enum arena, but
                // it is OK since they share the same lifetime.
                break :blk try val.copy(decl_arena_allocator);
            } else blk: {
                const val = if (last_tag_val) |val|
                    try sema.intAdd(val, Value.one, int_tag_ty)
                else
                    Value.zero;
                last_tag_val = val;

                break :blk try val.copy(decl_arena_allocator);
            };
            const gop = map.getOrPutAssumeCapacityContext(copied_val, .{
                .ty = int_tag_ty,
                .mod = mod,
            });
            if (gop.found_existing) {
                const field_src = union_obj.fieldSrcLoc(sema.mod, .{ .index = field_i }).lazy;
                const other_field_src = union_obj.fieldSrcLoc(sema.mod, .{ .index = gop.index }).lazy;
                const msg = msg: {
                    const msg = try sema.errMsg(&block_scope, field_src, "enum tag value {} already taken", .{copied_val.fmtValue(int_tag_ty, sema.mod)});
                    errdefer msg.destroy(gpa);
                    try sema.errNote(&block_scope, other_field_src, msg, "other occurrence here", .{});
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
        }

        // This string needs to outlive the ZIR code.
        const field_name = try decl_arena_allocator.dupe(u8, field_name_zir);
        if (enum_field_names) |set| {
            set.putAssumeCapacity(field_name, {});
        }

        const field_ty: Type = if (!has_type)
            Type.void
        else if (field_type_ref == .none)
            Type.initTag(.noreturn)
        else
            sema.resolveType(&block_scope, .unneeded, field_type_ref) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const ty_src = union_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .type,
                    }).lazy;
                    _ = try sema.resolveType(&block_scope, ty_src, field_type_ref);
                    unreachable;
                },
                else => |e| return e,
            };

        if (field_ty.tag() == .generic_poison) {
            return error.GenericPoison;
        }

        const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
        if (gop.found_existing) {
            const msg = msg: {
                const field_src = union_obj.fieldSrcLoc(sema.mod, .{ .index = field_i }).lazy;
                const msg = try sema.errMsg(&block_scope, field_src, "duplicate union field: '{s}'", .{field_name});
                errdefer msg.destroy(gpa);

                const prev_field_index = union_obj.fields.getIndex(field_name).?;
                const prev_field_src = union_obj.fieldSrcLoc(sema.mod, .{ .index = prev_field_index }).lazy;
                try sema.mod.errNoteNonLazy(prev_field_src.toSrcLoc(decl), msg, "other field here", .{});
                try sema.errNote(&block_scope, src, msg, "union declared here", .{});
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }

        if (tag_ty_field_names) |*names| {
            const enum_has_field = names.orderedRemove(field_name);
            if (!enum_has_field) {
                const msg = msg: {
                    const ty_src = union_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .type,
                    }).lazy;
                    const msg = try sema.errMsg(&block_scope, ty_src, "no field named '{s}' in enum '{}'", .{ field_name, union_obj.tag_ty.fmt(sema.mod) });
                    errdefer msg.destroy(sema.gpa);
                    try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
                    break :msg msg;
                };
                return sema.failWithOwnedErrorMsg(msg);
            }
        }

        if (field_ty.zigTypeTag() == .Opaque) {
            const msg = msg: {
                const ty_src = union_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                }).lazy;
                const msg = try sema.errMsg(&block_scope, ty_src, "opaque types have unknown size and therefore cannot be directly embedded in unions", .{});
                errdefer msg.destroy(sema.gpa);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
        if (union_obj.layout == .Extern and !try sema.validateExternType(field_ty, .union_field)) {
            const msg = msg: {
                const ty_src = union_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                });
                const msg = try sema.errMsg(&block_scope, ty_src.lazy, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                try sema.explainWhyTypeIsNotExtern(msg, ty_src, field_ty, .union_field);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        } else if (union_obj.layout == .Packed and !(validatePackedType(field_ty))) {
            const msg = msg: {
                const ty_src = union_obj.fieldSrcLoc(sema.mod, .{
                    .index = field_i,
                    .range = .type,
                });
                const msg = try sema.errMsg(&block_scope, ty_src.lazy, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
                errdefer msg.destroy(sema.gpa);

                try sema.explainWhyTypeIsNotPacked(msg, ty_src, field_ty);

                try sema.addDeclaredHereNote(msg, field_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }

        gop.value_ptr.* = .{
            .ty = try field_ty.copy(decl_arena_allocator),
            .abi_align = 0,
        };

        if (align_ref != .none) {
            gop.value_ptr.abi_align = sema.resolveAlign(&block_scope, .unneeded, align_ref) catch |err| switch (err) {
                error.NeededSourceLocation => {
                    const align_src = union_obj.fieldSrcLoc(sema.mod, .{
                        .index = field_i,
                        .range = .alignment,
                    }).lazy;
                    _ = try sema.resolveAlign(&block_scope, align_src, align_ref);
                    unreachable;
                },
                else => |e| return e,
            };
        } else {
            gop.value_ptr.abi_align = 0;
        }
    }

    if (tag_ty_field_names) |names| {
        if (names.count() > 0) {
            const msg = msg: {
                const msg = try sema.errMsg(&block_scope, src, "enum field(s) missing in union", .{});
                errdefer msg.destroy(sema.gpa);

                const enum_ty = union_obj.tag_ty;
                for (names.keys()) |field_name| {
                    const field_index = enum_ty.enumFieldIndex(field_name).?;
                    try sema.addFieldErrNote(enum_ty, field_index, msg, "field '{s}' missing, declared here", .{field_name});
                }
                try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
                break :msg msg;
            };
            return sema.failWithOwnedErrorMsg(msg);
        }
    }
}

fn semaUnionFieldVal(sema: *Sema, block: *Block, src: LazySrcLoc, int_tag_ty: Type, tag_ref: Air.Inst.Ref) CompileError!Value {
    const coerced = try sema.coerce(block, int_tag_ty, tag_ref, src);
    return sema.resolveConstValue(block, src, coerced, "enum tag value must be comptime-known");
}

fn generateUnionTagTypeNumbered(
    sema: *Sema,
    block: *Block,
    fields_len: u32,
    int_ty: Type,
    union_obj: *Module.Union,
) !Type {
    const mod = sema.mod;

    var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const enum_obj = try new_decl_arena_allocator.create(Module.EnumNumbered);
    const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumNumbered);
    enum_ty_payload.* = .{
        .base = .{ .tag = .enum_numbered },
        .data = enum_obj,
    };
    const enum_ty = Type.initPayload(&enum_ty_payload.base);
    const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);

    const src_decl = mod.declPtr(block.src_decl);
    const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node, block.wip_capture_scope);
    errdefer mod.destroyDecl(new_decl_index);
    const name = name: {
        const fqn = try union_obj.getFullyQualifiedName(mod);
        defer sema.gpa.free(fqn);
        break :name try std.fmt.allocPrintZ(mod.gpa, "@typeInfo({s}).Union.tag_type.?", .{fqn});
    };
    try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, block.namespace, .{
        .ty = Type.type,
        .val = enum_val,
    }, name);
    sema.mod.declPtr(new_decl_index).name_fully_qualified = true;

    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    new_decl.name_fully_qualified = true;
    errdefer mod.abortAnonDecl(new_decl_index);

    const copied_int_ty = try int_ty.copy(new_decl_arena_allocator);
    enum_obj.* = .{
        .owner_decl = new_decl_index,
        .tag_ty = copied_int_ty,
        .fields = .{},
        .values = .{},
    };
    // Here we pre-allocate the maps using the decl arena.
    try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
    try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{
        .ty = copied_int_ty,
        .mod = mod,
    });
    try new_decl.finalizeNewArena(&new_decl_arena);
    return enum_ty;
}

fn generateUnionTagTypeSimple(sema: *Sema, block: *Block, fields_len: usize, maybe_union_obj: ?*Module.Union) !Type {
    const mod = sema.mod;

    var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
    errdefer new_decl_arena.deinit();
    const new_decl_arena_allocator = new_decl_arena.allocator();

    const enum_obj = try new_decl_arena_allocator.create(Module.EnumSimple);
    const enum_ty_payload = try new_decl_arena_allocator.create(Type.Payload.EnumSimple);
    enum_ty_payload.* = .{
        .base = .{ .tag = .enum_simple },
        .data = enum_obj,
    };
    const enum_ty = Type.initPayload(&enum_ty_payload.base);
    const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);

    const new_decl_index = new_decl_index: {
        const union_obj = maybe_union_obj orelse {
            break :new_decl_index try mod.createAnonymousDecl(block, .{
                .ty = Type.type,
                .val = enum_val,
            });
        };
        const src_decl = mod.declPtr(block.src_decl);
        const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node, block.wip_capture_scope);
        errdefer mod.destroyDecl(new_decl_index);
        const name = name: {
            const fqn = try union_obj.getFullyQualifiedName(mod);
            defer sema.gpa.free(fqn);
            break :name try std.fmt.allocPrintZ(mod.gpa, "@typeInfo({s}).Union.tag_type.?", .{fqn});
        };
        try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, block.namespace, .{
            .ty = Type.type,
            .val = enum_val,
        }, name);
        sema.mod.declPtr(new_decl_index).name_fully_qualified = true;
        break :new_decl_index new_decl_index;
    };

    const new_decl = mod.declPtr(new_decl_index);
    new_decl.owns_tv = true;
    errdefer mod.abortAnonDecl(new_decl_index);

    enum_obj.* = .{
        .owner_decl = new_decl_index,
        .fields = .{},
    };
    // Here we pre-allocate the maps using the decl arena.
    try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
    try new_decl.finalizeNewArena(&new_decl_arena);
    return enum_ty;
}

fn getBuiltin(sema: *Sema, name: []const u8) CompileError!Air.Inst.Ref {
    var wip_captures = try WipCaptureScope.init(sema.gpa, sema.perm_arena, sema.owner_decl.src_scope);
    defer wip_captures.deinit();

    var block: Block = .{
        .parent = null,
        .sema = sema,
        .src_decl = sema.owner_decl_index,
        .namespace = sema.owner_decl.src_namespace,
        .wip_capture_scope = wip_captures.scope,
        .instructions = .{},
        .inlining = null,
        .is_comptime = true,
    };
    defer {
        block.instructions.deinit(sema.gpa);
        block.params.deinit(sema.gpa);
    }
    const src = LazySrcLoc.nodeOffset(0);

    const mod = sema.mod;
    const std_pkg = mod.main_pkg.table.get("std").?;
    const std_file = (mod.importPkg(std_pkg) catch unreachable).file;
    const opt_builtin_inst = (try sema.namespaceLookupRef(
        &block,
        src,
        mod.declPtr(std_file.root_decl.unwrap().?).src_namespace,
        "builtin",
    )) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
    const builtin_inst = try sema.analyzeLoad(&block, src, opt_builtin_inst, src);
    const builtin_ty = sema.analyzeAsType(&block, src, builtin_inst) catch |err| switch (err) {
        error.AnalysisFail => std.debug.panic("std.builtin is corrupt", .{}),
        else => |e| return e,
    };
    const opt_ty_decl = (try sema.namespaceLookup(
        &block,
        src,
        builtin_ty.getNamespace().?,
        name,
    )) orelse std.debug.panic("lib/std/builtin.zig is corrupt and missing '{s}'", .{name});
    return sema.analyzeDeclVal(&block, src, opt_ty_decl);
}

fn getBuiltinType(sema: *Sema, name: []const u8) CompileError!Type {
    const ty_inst = try sema.getBuiltin(name);

    var wip_captures = try WipCaptureScope.init(sema.gpa, sema.perm_arena, sema.owner_decl.src_scope);
    defer wip_captures.deinit();

    var block: Block = .{
        .parent = null,
        .sema = sema,
        .src_decl = sema.owner_decl_index,
        .namespace = sema.owner_decl.src_namespace,
        .wip_capture_scope = wip_captures.scope,
        .instructions = .{},
        .inlining = null,
        .is_comptime = true,
    };
    defer {
        block.instructions.deinit(sema.gpa);
        block.params.deinit(sema.gpa);
    }
    const src = LazySrcLoc.nodeOffset(0);

    const result_ty = sema.analyzeAsType(&block, src, ty_inst) catch |err| switch (err) {
        error.AnalysisFail => std.debug.panic("std.builtin.{s} is corrupt", .{name}),
        else => |e| return e,
    };
    try sema.resolveTypeFully(result_ty); // Should not fail
    return result_ty;
}

/// There is another implementation of this in `Type.onePossibleValue`. This one
/// in `Sema` is for calling during semantic analysis, and performs field resolution
/// to get the answer. The one in `Type` is for calling during codegen and asserts
/// that the types are already resolved.
/// TODO assert the return value matches `ty.onePossibleValue`
pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
    switch (ty.tag()) {
        .f16,
        .f32,
        .f64,
        .f80,
        .f128,
        .c_longdouble,
        .comptime_int,
        .comptime_float,
        .u1,
        .u8,
        .i8,
        .u16,
        .i16,
        .u29,
        .u32,
        .i32,
        .u64,
        .i64,
        .u128,
        .i128,
        .usize,
        .isize,
        .c_short,
        .c_ushort,
        .c_int,
        .c_uint,
        .c_long,
        .c_ulong,
        .c_longlong,
        .c_ulonglong,
        .bool,
        .type,
        .anyerror,
        .error_set_single,
        .error_set,
        .error_set_merged,
        .error_union,
        .fn_noreturn_no_args,
        .fn_void_no_args,
        .fn_naked_noreturn_no_args,
        .fn_ccc_void_no_args,
        .function,
        .single_const_pointer_to_comptime_int,
        .array_sentinel,
        .array_u8_sentinel_0,
        .const_slice_u8,
        .const_slice_u8_sentinel_0,
        .const_slice,
        .mut_slice,
        .anyopaque,
        .optional_single_mut_pointer,
        .optional_single_const_pointer,
        .enum_literal,
        .anyerror_void_error_union,
        .error_set_inferred,
        .@"opaque",
        .var_args_param,
        .manyptr_u8,
        .manyptr_const_u8,
        .manyptr_const_u8_sentinel_0,
        .atomic_order,
        .atomic_rmw_op,
        .calling_convention,
        .address_space,
        .float_mode,
        .reduce_op,
        .modifier,
        .prefetch_options,
        .export_options,
        .extern_options,
        .type_info,
        .@"anyframe",
        .anyframe_T,
        .many_const_pointer,
        .many_mut_pointer,
        .c_const_pointer,
        .c_mut_pointer,
        .single_const_pointer,
        .single_mut_pointer,
        .pointer,
        .bound_fn,
        => return null,

        .optional => {
            var buf: Type.Payload.ElemType = undefined;
            const child_ty = ty.optionalChild(&buf);
            if (child_ty.isNoReturn()) {
                return Value.null;
            } else {
                return null;
            }
        },

        .@"struct" => {
            const resolved_ty = try sema.resolveTypeFields(ty);
            const s = resolved_ty.castTag(.@"struct").?.data;
            for (s.fields.values(), 0..) |field, i| {
                if (field.is_comptime) continue;
                if (field.ty.eql(resolved_ty, sema.mod)) {
                    const msg = try Module.ErrorMsg.create(
                        sema.gpa,
                        s.srcLoc(sema.mod),
                        "struct '{}' depends on itself",
                        .{ty.fmt(sema.mod)},
                    );
                    try sema.addFieldErrNote(resolved_ty, i, msg, "while checking this field", .{});
                    return sema.failWithOwnedErrorMsg(msg);
                }
                if ((try sema.typeHasOnePossibleValue(field.ty)) == null) {
                    return null;
                }
            }
            return Value.initTag(.empty_struct_value);
        },

        .tuple, .anon_struct => {
            const tuple = ty.tupleFields();
            for (tuple.values, 0..) |val, i| {
                const is_comptime = val.tag() != .unreachable_value;
                if (is_comptime) continue;
                if ((try sema.typeHasOnePossibleValue(tuple.types[i])) != null) continue;
                return null;
            }
            return Value.initTag(.empty_struct_value);
        },

        .enum_numbered => {
            const resolved_ty = try sema.resolveTypeFields(ty);
            const enum_obj = resolved_ty.castTag(.enum_numbered).?.data;
            // An explicit tag type is always provided for enum_numbered.
            if (enum_obj.tag_ty.hasRuntimeBits()) {
                return null;
            }
            if (enum_obj.fields.count() == 1) {
                if (enum_obj.values.count() == 0) {
                    return Value.zero; // auto-numbered
                } else {
                    return enum_obj.values.keys()[0];
                }
            } else {
                return null;
            }
        },
        .enum_full => {
            const resolved_ty = try sema.resolveTypeFields(ty);
            const enum_obj = resolved_ty.castTag(.enum_full).?.data;
            if (enum_obj.tag_ty.hasRuntimeBits()) {
                return null;
            }
            switch (enum_obj.fields.count()) {
                0 => return Value.initTag(.unreachable_value),
                1 => if (enum_obj.values.count() == 0) {
                    return Value.zero; // auto-numbered
                } else {
                    return enum_obj.values.keys()[0];
                },
                else => return null,
            }
        },
        .enum_simple => {
            const resolved_ty = try sema.resolveTypeFields(ty);
            const enum_simple = resolved_ty.castTag(.enum_simple).?.data;
            switch (enum_simple.fields.count()) {
                0 => return Value.initTag(.unreachable_value),
                1 => return Value.zero,
                else => return null,
            }
        },
        .enum_nonexhaustive => {
            const tag_ty = ty.castTag(.enum_nonexhaustive).?.data.tag_ty;
            if (tag_ty.zigTypeTag() != .ComptimeInt and !(try sema.typeHasRuntimeBits(tag_ty))) {
                return Value.zero;
            } else {
                return null;
            }
        },
        .@"union", .union_safety_tagged, .union_tagged => {
            const resolved_ty = try sema.resolveTypeFields(ty);
            const union_obj = resolved_ty.cast(Type.Payload.Union).?.data;
            const tag_val = (try sema.typeHasOnePossibleValue(union_obj.tag_ty)) orelse
                return null;
            const fields = union_obj.fields.values();
            if (fields.len == 0) return Value.initTag(.unreachable_value);
            const only_field = fields[0];
            if (only_field.ty.eql(resolved_ty, sema.mod)) {
                const msg = try Module.ErrorMsg.create(
                    sema.gpa,
                    union_obj.srcLoc(sema.mod),
                    "union '{}' depends on itself",
                    .{ty.fmt(sema.mod)},
                );
                try sema.addFieldErrNote(resolved_ty, 0, msg, "while checking this field", .{});
                return sema.failWithOwnedErrorMsg(msg);
            }
            const val_val = (try sema.typeHasOnePossibleValue(only_field.ty)) orelse
                return null;
            // TODO make this not allocate. The function in `Type.onePossibleValue`
            // currently returns `empty_struct_value` and we should do that here too.
            return try Value.Tag.@"union".create(sema.arena, .{
                .tag = tag_val,
                .val = val_val,
            });
        },

        .empty_struct, .empty_struct_literal => return Value.initTag(.empty_struct_value),
        .void => return Value.void,
        .noreturn => return Value.initTag(.unreachable_value),
        .null => return Value.null,
        .undefined => return Value.initTag(.undef),

        .int_unsigned, .int_signed => {
            if (ty.cast(Type.Payload.Bits).?.data == 0) {
                return Value.zero;
            } else {
                return null;
            }
        },
        .vector, .array, .array_u8 => {
            if (ty.arrayLen() == 0)
                return Value.initTag(.empty_array);
            if ((try sema.typeHasOnePossibleValue(ty.elemType())) != null) {
                return Value.initTag(.the_only_possible_value);
            }
            return null;
        },

        .inferred_alloc_const => unreachable,
        .inferred_alloc_mut => unreachable,
        .generic_poison => return error.GenericPoison,
    }
}

/// Returns the type of the AIR instruction.
fn typeOf(sema: *Sema, inst: Air.Inst.Ref) Type {
    return sema.getTmpAir().typeOf(inst);
}

pub fn getTmpAir(sema: Sema) Air {
    return .{
        .instructions = sema.air_instructions.slice(),
        .extra = sema.air_extra.items,
        .values = sema.air_values.items,
    };
}

pub fn addType(sema: *Sema, ty: Type) !Air.Inst.Ref {
    switch (ty.tag()) {
        .u1 => return .u1_type,
        .u8 => return .u8_type,
        .i8 => return .i8_type,
        .u16 => return .u16_type,
        .u29 => return .u29_type,
        .i16 => return .i16_type,
        .u32 => return .u32_type,
        .i32 => return .i32_type,
        .u64 => return .u64_type,
        .i64 => return .i64_type,
        .u128 => return .u128_type,
        .i128 => return .i128_type,
        .usize => return .usize_type,
        .isize => return .isize_type,
        .c_short => return .c_short_type,
        .c_ushort => return .c_ushort_type,
        .c_int => return .c_int_type,
        .c_uint => return .c_uint_type,
        .c_long => return .c_long_type,
        .c_ulong => return .c_ulong_type,
        .c_longlong => return .c_longlong_type,
        .c_ulonglong => return .c_ulonglong_type,
        .c_longdouble => return .c_longdouble_type,
        .f16 => return .f16_type,
        .f32 => return .f32_type,
        .f64 => return .f64_type,
        .f80 => return .f80_type,
        .f128 => return .f128_type,
        .anyopaque => return .anyopaque_type,
        .bool => return .bool_type,
        .void => return .void_type,
        .type => return .type_type,
        .anyerror => return .anyerror_type,
        .comptime_int => return .comptime_int_type,
        .comptime_float => return .comptime_float_type,
        .noreturn => return .noreturn_type,
        .@"anyframe" => return .anyframe_type,
        .null => return .null_type,
        .undefined => return .undefined_type,
        .enum_literal => return .enum_literal_type,
        .atomic_order => return .atomic_order_type,
        .atomic_rmw_op => return .atomic_rmw_op_type,
        .calling_convention => return .calling_convention_type,
        .address_space => return .address_space_type,
        .float_mode => return .float_mode_type,
        .reduce_op => return .reduce_op_type,
        .modifier => return .modifier_type,
        .prefetch_options => return .prefetch_options_type,
        .export_options => return .export_options_type,
        .extern_options => return .extern_options_type,
        .type_info => return .type_info_type,
        .manyptr_u8 => return .manyptr_u8_type,
        .manyptr_const_u8 => return .manyptr_const_u8_type,
        .fn_noreturn_no_args => return .fn_noreturn_no_args_type,
        .fn_void_no_args => return .fn_void_no_args_type,
        .fn_naked_noreturn_no_args => return .fn_naked_noreturn_no_args_type,
        .fn_ccc_void_no_args => return .fn_ccc_void_no_args_type,
        .single_const_pointer_to_comptime_int => return .single_const_pointer_to_comptime_int_type,
        .const_slice_u8 => return .const_slice_u8_type,
        .anyerror_void_error_union => return .anyerror_void_error_union_type,
        .generic_poison => return .generic_poison_type,
        else => {},
    }
    try sema.air_instructions.append(sema.gpa, .{
        .tag = .const_ty,
        .data = .{ .ty = ty },
    });
    return Air.indexToRef(@intCast(u32, sema.air_instructions.len - 1));
}

fn addIntUnsigned(sema: *Sema, ty: Type, int: u64) CompileError!Air.Inst.Ref {
    return sema.addConstant(ty, try Value.Tag.int_u64.create(sema.arena, int));
}

fn addConstUndef(sema: *Sema, ty: Type) CompileError!Air.Inst.Ref {
    return sema.addConstant(ty, Value.undef);
}

pub fn addConstant(sema: *Sema, ty: Type, val: Value) SemaError!Air.Inst.Ref {
    const gpa = sema.gpa;
    const ty_inst = try sema.addType(ty);
    try sema.air_values.append(gpa, val);
    try sema.air_instructions.append(gpa, .{
        .tag = .constant,
        .data = .{ .ty_pl = .{
            .ty = ty_inst,
            .payload = @intCast(u32, sema.air_values.items.len - 1),
        } },
    });
    return Air.indexToRef(@intCast(u32, sema.air_instructions.len - 1));
}

pub fn addExtra(sema: *Sema, extra: anytype) Allocator.Error!u32 {
    const fields = std.meta.fields(@TypeOf(extra));
    try sema.air_extra.ensureUnusedCapacity(sema.gpa, fields.len);
    return sema.addExtraAssumeCapacity(extra);
}

pub fn addExtraAssumeCapacity(sema: *Sema, extra: anytype) u32 {
    const fields = std.meta.fields(@TypeOf(extra));
    const result = @intCast(u32, sema.air_extra.items.len);
    inline for (fields) |field| {
        sema.air_extra.appendAssumeCapacity(switch (field.type) {
            u32 => @field(extra, field.name),
            Air.Inst.Ref => @enumToInt(@field(extra, field.name)),
            i32 => @bitCast(u32, @field(extra, field.name)),
            else => @compileError("bad field type"),
        });
    }
    return result;
}

fn appendRefsAssumeCapacity(sema: *Sema, refs: []const Air.Inst.Ref) void {
    const coerced = @ptrCast([]const u32, refs);
    sema.air_extra.appendSliceAssumeCapacity(coerced);
}

fn getBreakBlock(sema: *Sema, inst_index: Air.Inst.Index) ?Air.Inst.Index {
    const air_datas = sema.air_instructions.items(.data);
    const air_tags = sema.air_instructions.items(.tag);
    switch (air_tags[inst_index]) {
        .br => return air_datas[inst_index].br.block_inst,
        else => return null,
    }
}

fn isComptimeKnown(
    sema: *Sema,
    inst: Air.Inst.Ref,
) !bool {
    return (try sema.resolveMaybeUndefVal(inst)) != null;
}

fn analyzeComptimeAlloc(
    sema: *Sema,
    block: *Block,
    var_type: Type,
    alignment: u32,
) CompileError!Air.Inst.Ref {
    // Needed to make an anon decl with type `var_type` (the `finish()` call below).
    _ = try sema.typeHasOnePossibleValue(var_type);

    const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = var_type,
        .@"addrspace" = target_util.defaultAddressSpace(sema.mod.getTarget(), .global_constant),
        .@"align" = alignment,
    });

    var anon_decl = try block.startAnonDecl();
    defer anon_decl.deinit();

    const decl_index = try anon_decl.finish(
        try var_type.copy(anon_decl.arena()),
        // There will be stores before the first load, but they may be to sub-elements or
        // sub-fields. So we need to initialize with undef to allow the mechanism to expand
        // into fields/elements and have those overridden with stored values.
        Value.undef,
        alignment,
    );
    const decl = sema.mod.declPtr(decl_index);
    decl.@"align" = alignment;

    try sema.mod.declareDeclDependency(sema.owner_decl_index, decl_index);
    return sema.addConstant(ptr_type, try Value.Tag.decl_ref_mut.create(sema.arena, .{
        .runtime_index = block.runtime_index,
        .decl_index = decl_index,
    }));
}

/// The places where a user can specify an address space attribute
pub const AddressSpaceContext = enum {
    /// A function is specified to be placed in a certain address space.
    function,

    /// A (global) variable is specified to be placed in a certain address space.
    /// In contrast to .constant, these values (and thus the address space they will be
    /// placed in) are required to be mutable.
    variable,

    /// A (global) constant value is specified to be placed in a certain address space.
    /// In contrast to .variable, values placed in this address space are not required to be mutable.
    constant,

    /// A pointer is ascripted to point into a certain address space.
    pointer,
};

pub fn analyzeAddressSpace(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    zir_ref: Zir.Inst.Ref,
    ctx: AddressSpaceContext,
) !std.builtin.AddressSpace {
    const addrspace_tv = try sema.resolveInstConst(block, src, zir_ref, "addresspace must be comptime-known");
    const address_space = addrspace_tv.val.toEnum(std.builtin.AddressSpace);
    const target = sema.mod.getTarget();
    const arch = target.cpu.arch;

    const is_nv = arch == .nvptx or arch == .nvptx64;
    const is_amd = arch == .amdgcn;
    const is_spirv = arch == .spirv32 or arch == .spirv64;
    const is_gpu = is_nv or is_amd or is_spirv;

    const supported = switch (address_space) {
        // TODO: on spir-v only when os is opencl.
        .generic => true,
        .gs, .fs, .ss => (arch == .x86 or arch == .x86_64) and ctx == .pointer,
        // TODO: check that .shared and .local are left uninitialized
        .param => is_nv,
        .global, .shared, .local => is_gpu,
        .constant => is_gpu and (ctx == .constant),
        // TODO this should also check how many flash banks the cpu has
        .flash, .flash1, .flash2, .flash3, .flash4, .flash5 => arch == .avr,
    };

    if (!supported) {
        // TODO error messages could be made more elaborate here
        const entity = switch (ctx) {
            .function => "functions",
            .variable => "mutable values",
            .constant => "constant values",
            .pointer => "pointers",
        };
        return sema.fail(
            block,
            src,
            "{s} with address space '{s}' are not supported on {s}",
            .{ entity, @tagName(address_space), arch.genericName() },
        );
    }

    return address_space;
}

/// Asserts the value is a pointer and dereferences it.
/// Returns `null` if the pointer contents cannot be loaded at comptime.
fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr_ty: Type) CompileError!?Value {
    const load_ty = ptr_ty.childType();
    const res = try sema.pointerDerefExtra(block, src, ptr_val, load_ty, true);
    switch (res) {
        .runtime_load => return null,
        .val => |v| return v,
        .needed_well_defined => |ty| return sema.fail(
            block,
            src,
            "comptime dereference requires '{}' to have a well-defined layout, but it does not.",
            .{ty.fmt(sema.mod)},
        ),
        .out_of_bounds => |ty| return sema.fail(
            block,
            src,
            "dereference of '{}' exceeds bounds of containing decl of type '{}'",
            .{ ptr_ty.fmt(sema.mod), ty.fmt(sema.mod) },
        ),
    }
}

const DerefResult = union(enum) {
    runtime_load,
    val: Value,
    needed_well_defined: Type,
    out_of_bounds: Type,
};

fn pointerDerefExtra(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, load_ty: Type, want_mutable: bool) CompileError!DerefResult {
    const target = sema.mod.getTarget();
    const deref = sema.beginComptimePtrLoad(block, src, ptr_val, load_ty) catch |err| switch (err) {
        error.RuntimeLoad => return DerefResult{ .runtime_load = {} },
        else => |e| return e,
    };

    if (deref.pointee) |tv| {
        const coerce_in_mem_ok =
            (try sema.coerceInMemoryAllowed(block, load_ty, tv.ty, false, target, src, src)) == .ok or
            (try sema.coerceInMemoryAllowed(block, tv.ty, load_ty, false, target, src, src)) == .ok;
        if (coerce_in_mem_ok) {
            // We have a Value that lines up in virtual memory exactly with what we want to load,
            // and it is in-memory coercible to load_ty. It may be returned without modifications.
            if (deref.is_mutable and want_mutable) {
                // The decl whose value we are obtaining here may be overwritten with
                // a different value upon further semantic analysis, which would
                // invalidate this memory. So we must copy here.
                return DerefResult{ .val = try tv.val.copy(sema.arena) };
            }
            return DerefResult{ .val = tv.val };
        }
    }

    // The type is not in-memory coercible or the direct dereference failed, so it must
    // be bitcast according to the pointer type we are performing the load through.
    if (!load_ty.hasWellDefinedLayout()) {
        return DerefResult{ .needed_well_defined = load_ty };
    }

    const load_sz = try sema.typeAbiSize(load_ty);

    // Try the smaller bit-cast first, since that's more efficient than using the larger `parent`
    if (deref.pointee) |tv| if (load_sz <= try sema.typeAbiSize(tv.ty))
        return DerefResult{ .val = (try sema.bitCastVal(block, src, tv.val, tv.ty, load_ty, 0)) orelse return .runtime_load };

    // If that fails, try to bit-cast from the largest parent value with a well-defined layout
    if (deref.parent) |parent| if (load_sz + parent.byte_offset <= try sema.typeAbiSize(parent.tv.ty))
        return DerefResult{ .val = (try sema.bitCastVal(block, src, parent.tv.val, parent.tv.ty, load_ty, parent.byte_offset)) orelse return .runtime_load };

    if (deref.ty_without_well_defined_layout) |bad_ty| {
        // We got no parent for bit-casting, or the parent we got was too small. Either way, the problem
        // is that some type we encountered when de-referencing does not have a well-defined layout.
        return DerefResult{ .needed_well_defined = bad_ty };
    } else {
        // If all encountered types had well-defined layouts, the parent is the root decl and it just
        // wasn't big enough for the load.
        return DerefResult{ .out_of_bounds = deref.parent.?.tv.ty };
    }
}

/// Used to convert a u64 value to a usize value, emitting a compile error if the number
/// is too big to fit.
fn usizeCast(sema: *Sema, block: *Block, src: LazySrcLoc, int: u64) CompileError!usize {
    if (@bitSizeOf(u64) <= @bitSizeOf(usize)) return int;
    return std.math.cast(usize, int) orelse return sema.fail(block, src, "expression produces integer value '{d}' which is too big for this compiler implementation to handle", .{int});
}

/// For pointer-like optionals, it returns the pointer type. For pointers,
/// the type is returned unmodified.
/// This can return `error.AnalysisFail` because it sometimes requires resolving whether
/// a type has zero bits, which can cause a "foo depends on itself" compile error.
/// This logic must be kept in sync with `Type.isPtrLikeOptional`.
fn typePtrOrOptionalPtrTy(
    sema: *Sema,
    ty: Type,
    buf: *Type.Payload.ElemType,
) !?Type {
    switch (ty.tag()) {
        .optional_single_const_pointer,
        .optional_single_mut_pointer,
        .c_const_pointer,
        .c_mut_pointer,
        => return ty.optionalChild(buf),

        .single_const_pointer_to_comptime_int,
        .single_const_pointer,
        .single_mut_pointer,
        .many_const_pointer,
        .many_mut_pointer,
        .manyptr_u8,
        .manyptr_const_u8,
        .manyptr_const_u8_sentinel_0,
        => return ty,

        .pointer => switch (ty.ptrSize()) {
            .Slice => return null,
            .C => return ty.optionalChild(buf),
            else => return ty,
        },

        .inferred_alloc_const => unreachable,
        .inferred_alloc_mut => unreachable,

        .optional => {
            const child_type = ty.optionalChild(buf);
            if (child_type.zigTypeTag() != .Pointer) return null;

            const info = child_type.ptrInfo().data;
            switch (info.size) {
                .Slice, .C => return null,
                .Many, .One => {
                    if (info.@"allowzero") return null;

                    // optionals of zero sized types behave like bools, not pointers
                    if ((try sema.typeHasOnePossibleValue(child_type)) != null) {
                        return null;
                    }

                    return child_type;
                },
            }
        },

        else => return null,
    }
}

/// `generic_poison` will return false.
/// This function returns false negatives when structs and unions are having their
/// field types resolved.
/// TODO assert the return value matches `ty.comptimeOnly`
/// TODO merge these implementations together with the "advanced"/opt_sema pattern seen
/// elsewhere in value.zig
pub fn typeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
    return switch (ty.tag()) {
        .u1,
        .u8,
        .i8,
        .u16,
        .i16,
        .u29,
        .u32,
        .i32,
        .u64,
        .i64,
        .u128,
        .i128,
        .usize,
        .isize,
        .c_short,
        .c_ushort,
        .c_int,
        .c_uint,
        .c_long,
        .c_ulong,
        .c_longlong,
        .c_ulonglong,
        .c_longdouble,
        .f16,
        .f32,
        .f64,
        .f80,
        .f128,
        .anyopaque,
        .bool,
        .void,
        .anyerror,
        .noreturn,
        .@"anyframe",
        .null,
        .undefined,
        .atomic_order,
        .atomic_rmw_op,
        .calling_convention,
        .address_space,
        .float_mode,
        .reduce_op,
        .modifier,
        .prefetch_options,
        .export_options,
        .extern_options,
        .manyptr_u8,
        .manyptr_const_u8,
        .manyptr_const_u8_sentinel_0,
        .const_slice_u8,
        .const_slice_u8_sentinel_0,
        .anyerror_void_error_union,
        .empty_struct_literal,
        .empty_struct,
        .error_set,
        .error_set_single,
        .error_set_inferred,
        .error_set_merged,
        .@"opaque",
        .generic_poison,
        .array_u8,
        .array_u8_sentinel_0,
        .int_signed,
        .int_unsigned,
        .enum_simple,
        => false,

        .single_const_pointer_to_comptime_int,
        .type,
        .comptime_int,
        .comptime_float,
        .enum_literal,
        .type_info,
        // These are function bodies, not function pointers.
        .fn_noreturn_no_args,
        .fn_void_no_args,
        .fn_naked_noreturn_no_args,
        .fn_ccc_void_no_args,
        .function,
        => true,

        .var_args_param => unreachable,
        .inferred_alloc_mut => unreachable,
        .inferred_alloc_const => unreachable,
        .bound_fn => unreachable,

        .array,
        .array_sentinel,
        .vector,
        => return sema.typeRequiresComptime(ty.childType()),

        .pointer,
        .single_const_pointer,
        .single_mut_pointer,
        .many_const_pointer,
        .many_mut_pointer,
        .c_const_pointer,
        .c_mut_pointer,
        .const_slice,
        .mut_slice,
        => {
            const child_ty = ty.childType();
            if (child_ty.zigTypeTag() == .Fn) {
                return child_ty.fnInfo().is_generic;
            } else {
                return sema.typeRequiresComptime(child_ty);
            }
        },

        .optional,
        .optional_single_mut_pointer,
        .optional_single_const_pointer,
        => {
            var buf: Type.Payload.ElemType = undefined;
            return sema.typeRequiresComptime(ty.optionalChild(&buf));
        },

        .tuple, .anon_struct => {
            const tuple = ty.tupleFields();
            for (tuple.types, 0..) |field_ty, i| {
                const have_comptime_val = tuple.values[i].tag() != .unreachable_value;
                if (!have_comptime_val and try sema.typeRequiresComptime(field_ty)) {
                    return true;
                }
            }
            return false;
        },

        .@"struct" => {
            const struct_obj = ty.castTag(.@"struct").?.data;
            switch (struct_obj.requires_comptime) {
                .no, .wip => return false,
                .yes => return true,
                .unknown => {
                    if (struct_obj.status == .field_types_wip)
                        return false;

                    try sema.resolveTypeFieldsStruct(ty, struct_obj);

                    struct_obj.requires_comptime = .wip;
                    for (struct_obj.fields.values()) |field| {
                        if (field.is_comptime) continue;
                        if (try sema.typeRequiresComptime(field.ty)) {
                            struct_obj.requires_comptime = .yes;
                            return true;
                        }
                    }
                    struct_obj.requires_comptime = .no;
                    return false;
                },
            }
        },

        .@"union", .union_safety_tagged, .union_tagged => {
            const union_obj = ty.cast(Type.Payload.Union).?.data;
            switch (union_obj.requires_comptime) {
                .no, .wip => return false,
                .yes => return true,
                .unknown => {
                    if (union_obj.status == .field_types_wip)
                        return false;

                    try sema.resolveTypeFieldsUnion(ty, union_obj);

                    union_obj.requires_comptime = .wip;
                    for (union_obj.fields.values()) |field| {
                        if (try sema.typeRequiresComptime(field.ty)) {
                            union_obj.requires_comptime = .yes;
                            return true;
                        }
                    }
                    union_obj.requires_comptime = .no;
                    return false;
                },
            }
        },

        .error_union => return sema.typeRequiresComptime(ty.errorUnionPayload()),
        .anyframe_T => {
            const child_ty = ty.castTag(.anyframe_T).?.data;
            return sema.typeRequiresComptime(child_ty);
        },
        .enum_numbered => {
            const tag_ty = ty.castTag(.enum_numbered).?.data.tag_ty;
            return sema.typeRequiresComptime(tag_ty);
        },
        .enum_full, .enum_nonexhaustive => {
            const tag_ty = ty.cast(Type.Payload.EnumFull).?.data.tag_ty;
            return sema.typeRequiresComptime(tag_ty);
        },
    };
}

pub fn typeHasRuntimeBits(sema: *Sema, ty: Type) CompileError!bool {
    return ty.hasRuntimeBitsAdvanced(false, .{ .sema = sema }) catch |err| switch (err) {
        error.NeedLazy => unreachable,
        else => |e| return e,
    };
}

fn typeAbiSize(sema: *Sema, ty: Type) !u64 {
    try sema.resolveTypeLayout(ty);
    const target = sema.mod.getTarget();
    return ty.abiSize(target);
}

fn typeAbiAlignment(sema: *Sema, ty: Type) CompileError!u32 {
    const target = sema.mod.getTarget();
    return (try ty.abiAlignmentAdvanced(target, .{ .sema = sema })).scalar;
}

/// Not valid to call for packed unions.
/// Keep implementation in sync with `Module.Union.Field.normalAlignment`.
fn unionFieldAlignment(sema: *Sema, field: Module.Union.Field) !u32 {
    if (field.ty.zigTypeTag() == .NoReturn) {
        return @as(u32, 0);
    } else if (field.abi_align == 0) {
        return sema.typeAbiAlignment(field.ty);
    } else {
        return field.abi_align;
    }
}

/// Synchronize logic with `Type.isFnOrHasRuntimeBits`.
pub fn fnHasRuntimeBits(sema: *Sema, ty: Type) CompileError!bool {
    const fn_info = ty.fnInfo();
    if (fn_info.is_generic) return false;
    if (fn_info.is_var_args) return true;
    switch (fn_info.cc) {
        // If there was a comptime calling convention, it should also return false here.
        .Inline => return false,
        else => {},
    }
    if (try sema.typeRequiresComptime(fn_info.return_type)) {
        return false;
    }
    return true;
}

fn unionFieldIndex(
    sema: *Sema,
    block: *Block,
    unresolved_union_ty: Type,
    field_name: []const u8,
    field_src: LazySrcLoc,
) !u32 {
    const union_ty = try sema.resolveTypeFields(unresolved_union_ty);
    const union_obj = union_ty.cast(Type.Payload.Union).?.data;
    const field_index_usize = union_obj.fields.getIndex(field_name) orelse
        return sema.failWithBadUnionFieldAccess(block, union_obj, field_src, field_name);
    return @intCast(u32, field_index_usize);
}

fn structFieldIndex(
    sema: *Sema,
    block: *Block,
    unresolved_struct_ty: Type,
    field_name: []const u8,
    field_src: LazySrcLoc,
) !u32 {
    const struct_ty = try sema.resolveTypeFields(unresolved_struct_ty);
    if (struct_ty.isAnonStruct()) {
        return sema.anonStructFieldIndex(block, struct_ty, field_name, field_src);
    } else {
        const struct_obj = struct_ty.castTag(.@"struct").?.data;
        const field_index_usize = struct_obj.fields.getIndex(field_name) orelse
            return sema.failWithBadStructFieldAccess(block, struct_obj, field_src, field_name);
        return @intCast(u32, field_index_usize);
    }
}

fn anonStructFieldIndex(
    sema: *Sema,
    block: *Block,
    struct_ty: Type,
    field_name: []const u8,
    field_src: LazySrcLoc,
) !u32 {
    const anon_struct = struct_ty.castTag(.anon_struct).?.data;
    for (anon_struct.names, 0..) |name, i| {
        if (mem.eql(u8, name, field_name)) {
            return @intCast(u32, i);
        }
    }
    return sema.fail(block, field_src, "no field named '{s}' in anonymous struct '{}'", .{
        field_name, struct_ty.fmt(sema.mod),
    });
}

fn queueFullTypeResolution(sema: *Sema, ty: Type) !void {
    const inst_ref = try sema.addType(ty);
    try sema.types_to_resolve.append(sema.gpa, inst_ref);
}

fn intAdd(sema: *Sema, lhs: Value, rhs: Value, ty: Type) !Value {
    if (ty.zigTypeTag() == .Vector) {
        const result_data = try sema.arena.alloc(Value, ty.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            scalar.* = try sema.intAddScalar(lhs_elem, rhs_elem);
        }
        return Value.Tag.aggregate.create(sema.arena, result_data);
    }
    return sema.intAddScalar(lhs, rhs);
}

fn intAddScalar(sema: *Sema, lhs: Value, rhs: Value) !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 target = sema.mod.getTarget();
    const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, target, sema);
    const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, target, sema);
    const limbs = try sema.arena.alloc(
        std.math.big.Limb,
        std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
    );
    var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
    result_bigint.add(lhs_bigint, rhs_bigint);
    return Value.fromBigInt(sema.arena, result_bigint.toConst());
}

/// Supports both floats and ints; handles undefined.
fn numberAddWrapScalar(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value {
    if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

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

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

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

fn intSub(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value {
    if (ty.zigTypeTag() == .Vector) {
        const result_data = try sema.arena.alloc(Value, ty.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            scalar.* = try sema.intSubScalar(lhs_elem, rhs_elem);
        }
        return Value.Tag.aggregate.create(sema.arena, result_data);
    }
    return sema.intSubScalar(lhs, rhs);
}

fn intSubScalar(sema: *Sema, lhs: Value, rhs: Value) !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 target = sema.mod.getTarget();
    const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, target, sema);
    const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, target, sema);
    const limbs = try sema.arena.alloc(
        std.math.big.Limb,
        std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
    );
    var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
    result_bigint.sub(lhs_bigint, rhs_bigint);
    return Value.fromBigInt(sema.arena, result_bigint.toConst());
}

/// Supports both floats and ints; handles undefined.
fn numberSubWrapScalar(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value {
    if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

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

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

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

fn floatAdd(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    float_type: Type,
) !Value {
    if (float_type.zigTypeTag() == .Vector) {
        const result_data = try sema.arena.alloc(Value, float_type.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            scalar.* = try sema.floatAddScalar(lhs_elem, rhs_elem, float_type.scalarType());
        }
        return Value.Tag.aggregate.create(sema.arena, result_data);
    }
    return sema.floatAddScalar(lhs, rhs, float_type);
}

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

fn floatSub(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    float_type: Type,
) !Value {
    if (float_type.zigTypeTag() == .Vector) {
        const result_data = try sema.arena.alloc(Value, float_type.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            scalar.* = try sema.floatSubScalar(lhs_elem, rhs_elem, float_type.scalarType());
        }
        return Value.Tag.aggregate.create(sema.arena, result_data);
    }
    return sema.floatSubScalar(lhs, rhs, float_type);
}

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

fn intSubWithOverflow(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value.OverflowArithmeticResult {
    if (ty.zigTypeTag() == .Vector) {
        const overflowed_data = try sema.arena.alloc(Value, ty.vectorLen());
        const result_data = try sema.arena.alloc(Value, ty.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            const of_math_result = try sema.intSubWithOverflowScalar(lhs_elem, rhs_elem, ty.scalarType());
            overflowed_data[i] = of_math_result.overflow_bit;
            scalar.* = of_math_result.wrapped_result;
        }
        return Value.OverflowArithmeticResult{
            .overflow_bit = try Value.Tag.aggregate.create(sema.arena, overflowed_data),
            .wrapped_result = try Value.Tag.aggregate.create(sema.arena, result_data),
        };
    }
    return sema.intSubWithOverflowScalar(lhs, rhs, ty);
}

fn intSubWithOverflowScalar(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value.OverflowArithmeticResult {
    const target = sema.mod.getTarget();
    const info = ty.intInfo(target);

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

fn floatToInt(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    val: Value,
    float_ty: Type,
    int_ty: Type,
) CompileError!Value {
    if (float_ty.zigTypeTag() == .Vector) {
        const elem_ty = float_ty.childType();
        const result_data = try sema.arena.alloc(Value, float_ty.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var buf: Value.ElemValueBuffer = undefined;
            const elem_val = val.elemValueBuffer(sema.mod, i, &buf);
            scalar.* = try sema.floatToIntScalar(block, src, elem_val, elem_ty, int_ty.scalarType());
        }
        return Value.Tag.aggregate.create(sema.arena, result_data);
    }
    return sema.floatToIntScalar(block, src, val, float_ty, int_ty);
}

// float is expected to be finite and non-NaN
fn float128IntPartToBigInt(
    arena: Allocator,
    float: f128,
) !std.math.big.int.Managed {
    const is_negative = std.math.signbit(float);
    const floored = @floor(@fabs(float));

    var rational = try std.math.big.Rational.init(arena);
    defer rational.q.deinit();
    rational.setFloat(f128, 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 big_one = std.math.big.int.Const{ .limbs = &.{1}, .positive = true };
    assert(rational.q.toConst().eqAbs(big_one));

    if (is_negative) {
        rational.negate();
    }
    return rational.p;
}

fn floatToIntScalar(
    sema: *Sema,
    block: *Block,
    src: LazySrcLoc,
    val: Value,
    float_ty: Type,
    int_ty: Type,
) CompileError!Value {
    const Limb = std.math.big.Limb;

    const float = val.toFloat(f128);
    if (std.math.isNan(float)) {
        return sema.fail(block, src, "float value NaN cannot be stored in integer type '{}'", .{
            int_ty.fmt(sema.mod),
        });
    }
    if (std.math.isInf(float)) {
        return sema.fail(block, src, "float value Inf cannot be stored in integer type '{}'", .{
            int_ty.fmt(sema.mod),
        });
    }

    var big_int = try float128IntPartToBigInt(sema.arena, float);
    defer big_int.deinit();

    const result_limbs = try sema.arena.dupe(Limb, big_int.toConst().limbs);
    const result = if (!big_int.isPositive())
        try Value.Tag.int_big_negative.create(sema.arena, result_limbs)
    else
        try Value.Tag.int_big_positive.create(sema.arena, result_limbs);

    if (!(try sema.intFitsInType(result, int_ty, null))) {
        return sema.fail(block, src, "float value '{}' cannot be stored in integer type '{}'", .{
            val.fmtValue(float_ty, sema.mod), int_ty.fmt(sema.mod),
        });
    }
    return result;
}

/// Asserts the value is an integer, and the destination type is ComptimeInt or Int.
/// Vectors are also accepted. Vector results are reduced with AND.
///
/// If provided, `vector_index` reports the first element that failed the range check.
fn intFitsInType(
    sema: *Sema,
    val: Value,
    ty: Type,
    vector_index: ?*usize,
) CompileError!bool {
    const target = sema.mod.getTarget();
    switch (val.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,
        },

        .lazy_align => switch (ty.zigTypeTag()) {
            .Int => {
                const info = ty.intInfo(target);
                const max_needed_bits = @as(u16, 16) + @boolToInt(info.signedness == .signed);
                // If it is u16 or bigger we know the alignment fits without resolving it.
                if (info.bits >= max_needed_bits) return true;
                const x = try sema.typeAbiAlignment(val.castTag(.lazy_align).?.data);
                if (x == 0) return true;
                const actual_needed_bits = std.math.log2(x) + 1 + @boolToInt(info.signedness == .signed);
                return info.bits >= actual_needed_bits;
            },
            .ComptimeInt => return true,
            else => unreachable,
        },
        .lazy_size => switch (ty.zigTypeTag()) {
            .Int => {
                const info = ty.intInfo(target);
                const max_needed_bits = @as(u16, 64) + @boolToInt(info.signedness == .signed);
                // If it is u64 or bigger we know the size fits without resolving it.
                if (info.bits >= max_needed_bits) return true;
                const x = try sema.typeAbiSize(val.castTag(.lazy_size).?.data);
                if (x == 0) return true;
                const actual_needed_bits = std.math.log2(x) + 1 + @boolToInt(info.signedness == .signed);
                return info.bits >= actual_needed_bits;
            },
            .ComptimeInt => return true,
            else => unreachable,
        },

        .int_u64 => switch (ty.zigTypeTag()) {
            .Int => {
                const x = val.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 = val.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: Value.BigIntSpace = undefined;
                return (try val.toBigIntAdvanced(&buffer, target, sema)).fitsInTwosComp(info.signedness, info.bits);
            },
            .ComptimeInt => return true,
            else => unreachable,
        },
        .int_big_positive => switch (ty.zigTypeTag()) {
            .Int => {
                const info = ty.intInfo(target);
                return val.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 val.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,
        },

        .aggregate => {
            assert(ty.zigTypeTag() == .Vector);
            for (val.castTag(.aggregate).?.data, 0..) |elem, i| {
                if (!(try sema.intFitsInType(elem, ty.scalarType(), null))) {
                    if (vector_index) |some| some.* = i;
                    return false;
                }
            }
            return true;
        },

        else => unreachable,
    }
}

fn intInRange(
    sema: *Sema,
    tag_ty: Type,
    int_val: Value,
    end: usize,
) !bool {
    if (!(try int_val.compareAllWithZeroAdvanced(.gte, sema))) return false;
    var end_payload: Value.Payload.U64 = .{
        .base = .{ .tag = .int_u64 },
        .data = end,
    };
    const end_val = Value.initPayload(&end_payload.base);
    if (!(try sema.compareAll(int_val, .lt, end_val, tag_ty))) return false;
    return true;
}

/// Asserts the type is an enum.
fn enumHasInt(
    sema: *Sema,
    ty: Type,
    int: Value,
) CompileError!bool {
    switch (ty.tag()) {
        .enum_nonexhaustive => unreachable,
        .enum_full => {
            const enum_full = ty.castTag(.enum_full).?.data;
            const tag_ty = enum_full.tag_ty;
            if (enum_full.values.count() == 0) {
                return sema.intInRange(tag_ty, int, enum_full.fields.count());
            } else {
                return enum_full.values.containsContext(int, .{
                    .ty = tag_ty,
                    .mod = sema.mod,
                });
            }
        },
        .enum_numbered => {
            const enum_obj = ty.castTag(.enum_numbered).?.data;
            const tag_ty = enum_obj.tag_ty;
            if (enum_obj.values.count() == 0) {
                return sema.intInRange(tag_ty, int, enum_obj.fields.count());
            } else {
                return enum_obj.values.containsContext(int, .{
                    .ty = tag_ty,
                    .mod = sema.mod,
                });
            }
        },
        .enum_simple => {
            const enum_simple = ty.castTag(.enum_simple).?.data;
            const fields_len = enum_simple.fields.count();
            const bits = std.math.log2_int_ceil(usize, fields_len);
            var buffer: Type.Payload.Bits = .{
                .base = .{ .tag = .int_unsigned },
                .data = bits,
            };
            const tag_ty = Type.initPayload(&buffer.base);
            return sema.intInRange(tag_ty, int, fields_len);
        },
        .atomic_order,
        .atomic_rmw_op,
        .calling_convention,
        .address_space,
        .float_mode,
        .reduce_op,
        .modifier,
        .prefetch_options,
        .export_options,
        .extern_options,
        => unreachable,

        else => unreachable,
    }
}

fn intAddWithOverflow(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value.OverflowArithmeticResult {
    if (ty.zigTypeTag() == .Vector) {
        const overflowed_data = try sema.arena.alloc(Value, ty.vectorLen());
        const result_data = try sema.arena.alloc(Value, ty.vectorLen());
        for (result_data, 0..) |*scalar, i| {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            const of_math_result = try sema.intAddWithOverflowScalar(lhs_elem, rhs_elem, ty.scalarType());
            overflowed_data[i] = of_math_result.overflow_bit;
            scalar.* = of_math_result.wrapped_result;
        }
        return Value.OverflowArithmeticResult{
            .overflow_bit = try Value.Tag.aggregate.create(sema.arena, overflowed_data),
            .wrapped_result = try Value.Tag.aggregate.create(sema.arena, result_data),
        };
    }
    return sema.intAddWithOverflowScalar(lhs, rhs, ty);
}

fn intAddWithOverflowScalar(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) !Value.OverflowArithmeticResult {
    const target = sema.mod.getTarget();
    const info = ty.intInfo(target);

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

/// Asserts the values are comparable. Both operands have type `ty`.
/// For vectors, returns true if the comparison is true for ALL elements.
///
/// Note that `!compareAll(.eq, ...) != compareAll(.neq, ...)`
fn compareAll(
    sema: *Sema,
    lhs: Value,
    op: std.math.CompareOperator,
    rhs: Value,
    ty: Type,
) CompileError!bool {
    if (ty.zigTypeTag() == .Vector) {
        var i: usize = 0;
        while (i < ty.vectorLen()) : (i += 1) {
            var lhs_buf: Value.ElemValueBuffer = undefined;
            var rhs_buf: Value.ElemValueBuffer = undefined;
            const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
            const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
            if (!(try sema.compareScalar(lhs_elem, op, rhs_elem, ty.scalarType()))) {
                return false;
            }
        }
        return true;
    }
    return sema.compareScalar(lhs, op, rhs, ty);
}

/// Asserts the values are comparable. Both operands have type `ty`.
fn compareScalar(
    sema: *Sema,
    lhs: Value,
    op: std.math.CompareOperator,
    rhs: Value,
    ty: Type,
) CompileError!bool {
    switch (op) {
        .eq => return sema.valuesEqual(lhs, rhs, ty),
        .neq => return !(try sema.valuesEqual(lhs, rhs, ty)),
        else => return Value.compareHeteroAdvanced(lhs, op, rhs, sema.mod.getTarget(), sema),
    }
}

fn valuesEqual(
    sema: *Sema,
    lhs: Value,
    rhs: Value,
    ty: Type,
) CompileError!bool {
    return Value.eqlAdvanced(lhs, ty, rhs, ty, sema.mod, sema);
}

/// Asserts the values are comparable vectors of type `ty`.
fn compareVector(
    sema: *Sema,
    lhs: Value,
    op: std.math.CompareOperator,
    rhs: Value,
    ty: Type,
) !Value {
    assert(ty.zigTypeTag() == .Vector);
    const result_data = try sema.arena.alloc(Value, ty.vectorLen());
    for (result_data, 0..) |*scalar, i| {
        var lhs_buf: Value.ElemValueBuffer = undefined;
        var rhs_buf: Value.ElemValueBuffer = undefined;
        const lhs_elem = lhs.elemValueBuffer(sema.mod, i, &lhs_buf);
        const rhs_elem = rhs.elemValueBuffer(sema.mod, i, &rhs_buf);
        const res_bool = try sema.compareScalar(lhs_elem, op, rhs_elem, ty.scalarType());
        scalar.* = Value.makeBool(res_bool);
    }
    return Value.Tag.aggregate.create(sema.arena, result_data);
}

/// Returns the type of a pointer to an element.
/// Asserts that the type is a pointer, and that the element type is indexable.
/// For *[N]T, return *T
/// For [*]T, returns *T
/// For []T, returns *T
/// Handles const-ness and address spaces in particular.
/// This code is duplicated in `analyzePtrArithmetic`.
fn elemPtrType(sema: *Sema, ptr_ty: Type, offset: ?usize) !Type {
    const ptr_info = ptr_ty.ptrInfo().data;
    const elem_ty = ptr_ty.elemType2();
    const allow_zero = ptr_info.@"allowzero" and (offset orelse 0) == 0;
    const target = sema.mod.getTarget();
    const parent_ty = ptr_ty.childType();

    const VI = Type.Payload.Pointer.Data.VectorIndex;

    const vector_info: struct {
        host_size: u16 = 0,
        alignment: u32 = 0,
        vector_index: VI = .none,
    } = if (parent_ty.tag() == .vector and ptr_info.size == .One) blk: {
        const elem_bits = elem_ty.bitSize(target);
        if (elem_bits == 0) break :blk .{};
        const is_packed = elem_bits < 8 or !std.math.isPowerOfTwo(elem_bits);
        if (!is_packed) break :blk .{};

        break :blk .{
            .host_size = @intCast(u16, parent_ty.arrayLen()),
            .alignment = @intCast(u16, parent_ty.abiAlignment(target)),
            .vector_index = if (offset) |some| @intToEnum(VI, some) else .runtime,
        };
    } else .{};

    const alignment: u32 = a: {
        // Calculate the new pointer alignment.
        if (ptr_info.@"align" == 0) {
            if (vector_info.alignment != 0) break :a vector_info.alignment;
            // ABI-aligned pointer. Any pointer arithmetic maintains the same ABI-alignedness.
            break :a 0;
        }
        // If the addend is not a comptime-known value we can still count on
        // it being a multiple of the type size.
        const elem_size = try sema.typeAbiSize(elem_ty);
        const addend = if (offset) |off| elem_size * off else elem_size;

        // The resulting pointer is aligned to the lcd between the offset (an
        // arbitrary number) and the alignment factor (always a power of two,
        // non zero).
        const new_align = @as(u32, 1) << @intCast(u5, @ctz(addend | ptr_info.@"align"));
        break :a new_align;
    };
    return try Type.ptr(sema.arena, sema.mod, .{
        .pointee_type = elem_ty,
        .mutable = ptr_info.mutable,
        .@"addrspace" = ptr_info.@"addrspace",
        .@"allowzero" = allow_zero,
        .@"volatile" = ptr_info.@"volatile",
        .@"align" = alignment,
        .host_size = vector_info.host_size,
        .vector_index = vector_info.vector_index,
    });
}