aboutsummaryrefslogtreecommitdiff
path: root/src/Compilation.zig
blob: de433a680075e9664e889353d4d1804320b3b987 (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
const Compilation = @This();

const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.compilation);
const Target = std.Target;

const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const target_util = @import("target.zig");
const Package = @import("Package.zig");
const link = @import("link.zig");
const tracy = @import("tracy.zig");
const trace = tracy.trace;
const build_options = @import("build_options");
const LibCInstallation = @import("libc_installation.zig").LibCInstallation;
const glibc = @import("glibc.zig");
const musl = @import("musl.zig");
const mingw = @import("mingw.zig");
const libunwind = @import("libunwind.zig");
const libcxx = @import("libcxx.zig");
const wasi_libc = @import("wasi_libc.zig");
const fatal = @import("main.zig").fatal;
const clangMain = @import("main.zig").clangMain;
const Module = @import("Module.zig");
const Cache = std.Build.Cache;
const translate_c = @import("translate_c.zig");
const clang = @import("clang.zig");
const c_codegen = @import("codegen/c.zig");
const ThreadPool = @import("ThreadPool.zig");
const WaitGroup = @import("WaitGroup.zig");
const libtsan = @import("libtsan.zig");
const Zir = @import("Zir.zig");
const Autodoc = @import("Autodoc.zig");
const Color = @import("main.zig").Color;

/// General-purpose allocator. Used for both temporary and long-term storage.
gpa: Allocator,
/// Arena-allocated memory used during initialization. Should be untouched until deinit.
arena_state: std.heap.ArenaAllocator.State,
bin_file: *link.File,
c_object_table: std.AutoArrayHashMapUnmanaged(*CObject, void) = .{},
/// This is a pointer to a local variable inside `update()`.
whole_cache_manifest: ?*Cache.Manifest = null,
whole_cache_manifest_mutex: std.Thread.Mutex = .{},

link_error_flags: link.File.ErrorFlags = .{},
lld_errors: std.ArrayListUnmanaged(LldError) = .{},

work_queue: std.fifo.LinearFifo(Job, .Dynamic),
anon_work_queue: std.fifo.LinearFifo(Job, .Dynamic),

/// These jobs are to invoke the Clang compiler to create an object file, which
/// gets linked with the Compilation.
c_object_work_queue: std.fifo.LinearFifo(*CObject, .Dynamic),

/// These jobs are to tokenize, parse, and astgen files, which may be outdated
/// since the last compilation, as well as scan for `@import` and queue up
/// additional jobs corresponding to those new files.
astgen_work_queue: std.fifo.LinearFifo(*Module.File, .Dynamic),
/// These jobs are to inspect the file system stat() and if the embedded file has changed
/// on disk, mark the corresponding Decl outdated and queue up an `analyze_decl`
/// task for it.
embed_file_work_queue: std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic),

/// The ErrorMsg memory is owned by the `CObject`, using Compilation's general purpose allocator.
/// This data is accessed by multiple threads and is protected by `mutex`.
failed_c_objects: std.AutoArrayHashMapUnmanaged(*CObject, *CObject.ErrorMsg) = .{},

/// Miscellaneous things that can fail.
misc_failures: std.AutoArrayHashMapUnmanaged(MiscTask, MiscError) = .{},

keep_source_files_loaded: bool,
use_clang: bool,
sanitize_c: bool,
/// When this is `true` it means invoking clang as a sub-process is expected to inherit
/// stdin, stdout, stderr, and if it returns non success, to forward the exit code.
/// Otherwise we attempt to parse the error messages and expose them via the Compilation API.
/// This is `true` for `zig cc`, `zig c++`, and `zig translate-c`.
clang_passthrough_mode: bool,
clang_preprocessor_mode: ClangPreprocessorMode,
/// Whether to print clang argvs to stdout.
verbose_cc: bool,
verbose_air: bool,
verbose_llvm_ir: bool,
verbose_cimport: bool,
verbose_llvm_cpu_features: bool,
disable_c_depfile: bool,
time_report: bool,
stack_report: bool,
unwind_tables: bool,
test_evented_io: bool,
debug_compiler_runtime_libs: bool,
debug_compile_errors: bool,
job_queued_compiler_rt_lib: bool = false,
job_queued_compiler_rt_obj: bool = false,
alloc_failure_occurred: bool = false,
formatted_panics: bool = false,

c_source_files: []const CSourceFile,
clang_argv: []const []const u8,
cache_parent: *Cache,
/// Path to own executable for invoking `zig clang`.
self_exe_path: ?[]const u8,
/// null means -fno-emit-bin.
/// This is mutable memory allocated into the Compilation-lifetime arena (`arena_state`)
/// of exactly the correct size for "o/[digest]/[basename]".
/// The basename is of the outputted binary file in case we don't know the directory yet.
whole_bin_sub_path: ?[]u8,
/// Same as `whole_bin_sub_path` but for implibs.
whole_implib_sub_path: ?[]u8,
zig_lib_directory: Directory,
local_cache_directory: Directory,
global_cache_directory: Directory,
libc_include_dir_list: []const []const u8,
thread_pool: *ThreadPool,

/// Populated when we build the libc++ static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libcxx_static_lib: ?CRTFile = null,
/// Populated when we build the libc++abi static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libcxxabi_static_lib: ?CRTFile = null,
/// Populated when we build the libunwind static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libunwind_static_lib: ?CRTFile = null,
/// Populated when we build the TSAN static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
tsan_static_lib: ?CRTFile = null,
/// Populated when we build the libssp static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libssp_static_lib: ?CRTFile = null,
/// Populated when we build the libc static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libc_static_lib: ?CRTFile = null,
/// Populated when we build the libcompiler_rt static library. A Job to build this is indicated
/// by setting `job_queued_compiler_rt_lib` and resolved before calling linker.flush().
compiler_rt_lib: ?CRTFile = null,
/// Populated when we build the compiler_rt_obj object. A Job to build this is indicated
/// by setting `job_queued_compiler_rt_obj` and resolved before calling linker.flush().
compiler_rt_obj: ?CRTFile = null,

glibc_so_files: ?glibc.BuiltSharedObjects = null,

/// For example `Scrt1.o` and `libc_nonshared.a`. These are populated after building libc from source,
/// The set of needed CRT (C runtime) files differs depending on the target and compilation settings.
/// The key is the basename, and the value is the absolute path to the completed build artifact.
crt_files: std.StringHashMapUnmanaged(CRTFile) = .{},

/// Keeping track of this possibly open resource so we can close it later.
owned_link_dir: ?std.fs.Dir,

/// This is for stage1 and should be deleted upon completion of self-hosting.
/// Don't use this for anything other than stage1 compatibility.
color: Color = .auto,

/// How many lines of reference trace should be included per compile error.
/// Null means only show snippet on first error.
reference_trace: ?u32 = null,

libcxx_abi_version: libcxx.AbiVersion = libcxx.AbiVersion.default,

/// This mutex guards all `Compilation` mutable state.
mutex: std.Thread.Mutex = .{},

test_filter: ?[]const u8,
test_name_prefix: ?[]const u8,

emit_asm: ?EmitLoc,
emit_llvm_ir: ?EmitLoc,
emit_llvm_bc: ?EmitLoc,
emit_analysis: ?EmitLoc,
emit_docs: ?EmitLoc,

work_queue_wait_group: WaitGroup = .{},
astgen_wait_group: WaitGroup = .{},

pub const default_stack_protector_buffer_size = 4;
pub const SemaError = Module.SemaError;

pub const CRTFile = struct {
    lock: Cache.Lock,
    full_object_path: []const u8,

    pub fn deinit(self: *CRTFile, gpa: Allocator) void {
        self.lock.release();
        gpa.free(self.full_object_path);
        self.* = undefined;
    }
};

// supported languages for "zig clang -x <lang>".
// Loosely based on llvm-project/clang/include/clang/Driver/Types.def
pub const LangToExt = std.ComptimeStringMap(FileExt, .{
    .{ "c", .c },
    .{ "c-header", .h },
    .{ "c++", .cpp },
    .{ "c++-header", .h },
    .{ "objective-c", .m },
    .{ "objective-c-header", .h },
    .{ "objective-c++", .mm },
    .{ "objective-c++-header", .h },
    .{ "assembler", .assembly },
    .{ "assembler-with-cpp", .assembly_with_cpp },
    .{ "cuda", .cu },
});

/// For passing to a C compiler.
pub const CSourceFile = struct {
    src_path: []const u8,
    extra_flags: []const []const u8 = &.{},
    /// Same as extra_flags except they are not added to the Cache hash.
    cache_exempt_flags: []const []const u8 = &.{},
    // this field is non-null iff language was explicitly set with "-x lang".
    ext: ?FileExt = null,
};

const Job = union(enum) {
    /// Write the constant value for a Decl to the output file.
    codegen_decl: Module.Decl.Index,
    /// Write the machine code for a function to the output file.
    codegen_func: *Module.Fn,
    /// Render the .h file snippet for the Decl.
    emit_h_decl: Module.Decl.Index,
    /// The Decl needs to be analyzed and possibly export itself.
    /// It may have already be analyzed, or it may have been determined
    /// to be outdated; in this case perform semantic analysis again.
    analyze_decl: Module.Decl.Index,
    /// The file that was loaded with `@embedFile` has changed on disk
    /// and has been re-loaded into memory. All Decls that depend on it
    /// need to be re-analyzed.
    update_embed_file: *Module.EmbedFile,
    /// The source file containing the Decl has been updated, and so the
    /// Decl may need its line number information updated in the debug info.
    update_line_number: Module.Decl.Index,
    /// The main source file for the package needs to be analyzed.
    analyze_pkg: *Package,

    /// one of the glibc static objects
    glibc_crt_file: glibc.CRTFile,
    /// all of the glibc shared objects
    glibc_shared_objects,
    /// one of the musl static objects
    musl_crt_file: musl.CRTFile,
    /// one of the mingw-w64 static objects
    mingw_crt_file: mingw.CRTFile,
    /// libunwind.a, usually needed when linking libc
    libunwind: void,
    libcxx: void,
    libcxxabi: void,
    libtsan: void,
    libssp: void,
    /// needed when not linking libc and using LLVM for code generation because it generates
    /// calls to, for example, memcpy and memset.
    zig_libc: void,
    /// one of WASI libc static objects
    wasi_libc_crt_file: wasi_libc.CRTFile,

    /// The value is the index into `link.File.Options.system_libs`.
    windows_import_lib: usize,
};

pub const CObject = struct {
    /// Relative to cwd. Owned by arena.
    src: CSourceFile,
    status: union(enum) {
        new,
        success: struct {
            /// The outputted result. Owned by gpa.
            object_path: []u8,
            /// This is a file system lock on the cache hash manifest representing this
            /// object. It prevents other invocations of the Zig compiler from interfering
            /// with this object until released.
            lock: Cache.Lock,
        },
        /// There will be a corresponding ErrorMsg in Compilation.failed_c_objects.
        failure,
        /// A transient failure happened when trying to compile the C Object; it may
        /// succeed if we try again. There may be a corresponding ErrorMsg in
        /// Compilation.failed_c_objects. If there is not, the failure is out of memory.
        failure_retryable,
    },

    pub const ErrorMsg = struct {
        msg: []const u8,
        line: u32,
        column: u32,

        pub fn destroy(em: *ErrorMsg, gpa: Allocator) void {
            gpa.free(em.msg);
            gpa.destroy(em);
        }
    };

    /// Returns if there was failure.
    pub fn clearStatus(self: *CObject, gpa: Allocator) bool {
        switch (self.status) {
            .new => return false,
            .failure, .failure_retryable => {
                self.status = .new;
                return true;
            },
            .success => |*success| {
                gpa.free(success.object_path);
                success.lock.release();
                self.status = .new;
                return false;
            },
        }
    }

    pub fn destroy(self: *CObject, gpa: Allocator) void {
        _ = self.clearStatus(gpa);
        gpa.destroy(self);
    }
};

pub const MiscTask = enum {
    write_builtin_zig,
    glibc_crt_file,
    glibc_shared_objects,
    musl_crt_file,
    mingw_crt_file,
    windows_import_lib,
    libunwind,
    libcxx,
    libcxxabi,
    libtsan,
    wasi_libc_crt_file,
    compiler_rt,
    libssp,
    zig_libc,
    analyze_pkg,
};

pub const MiscError = struct {
    /// Allocated with gpa.
    msg: []u8,
    children: ?AllErrors = null,

    pub fn deinit(misc_err: *MiscError, gpa: Allocator) void {
        gpa.free(misc_err.msg);
        if (misc_err.children) |*children| {
            children.deinit(gpa);
        }
        misc_err.* = undefined;
    }
};

pub const LldError = struct {
    /// Allocated with gpa.
    msg: []const u8,
    context_lines: []const []const u8 = &.{},

    pub fn deinit(self: *LldError, gpa: Allocator) void {
        for (self.context_lines) |line| {
            gpa.free(line);
        }

        gpa.free(self.context_lines);
        gpa.free(self.msg);
    }
};

/// To support incremental compilation, errors are stored in various places
/// so that they can be created and destroyed appropriately. This structure
/// is used to collect all the errors from the various places into one
/// convenient place for API users to consume. It is allocated into 1 arena
/// and freed all at once.
pub const AllErrors = struct {
    arena: std.heap.ArenaAllocator.State,
    list: []const Message,

    pub const Message = union(enum) {
        src: struct {
            msg: []const u8,
            src_path: []const u8,
            line: u32,
            column: u32,
            span: Module.SrcLoc.Span,
            /// Usually one, but incremented for redundant messages.
            count: u32 = 1,
            /// Does not include the trailing newline.
            source_line: ?[]const u8,
            notes: []const Message = &.{},
            reference_trace: []Message = &.{},

            /// Splits the error message up into lines to properly indent them
            /// to allow for long, good-looking error messages.
            ///
            /// This is used to split the message in `@compileError("hello\nworld")` for example.
            fn writeMsg(src: @This(), stderr: anytype, indent: usize) !void {
                var lines = mem.split(u8, src.msg, "\n");
                while (lines.next()) |line| {
                    try stderr.writeAll(line);
                    if (lines.index == null) break;
                    try stderr.writeByte('\n');
                    try stderr.writeByteNTimes(' ', indent);
                }
            }
        },
        plain: struct {
            msg: []const u8,
            notes: []Message = &.{},
            /// Usually one, but incremented for redundant messages.
            count: u32 = 1,
        },

        pub fn incrementCount(msg: *Message) void {
            switch (msg.*) {
                .src => |*src| {
                    src.count += 1;
                },
                .plain => |*plain| {
                    plain.count += 1;
                },
            }
        }

        pub fn renderToStdErr(msg: Message, ttyconf: std.debug.TTY.Config) void {
            std.debug.getStderrMutex().lock();
            defer std.debug.getStderrMutex().unlock();
            const stderr = std.io.getStdErr();
            return msg.renderToWriter(ttyconf, stderr.writer(), "error", .Red, 0) catch return;
        }

        pub fn renderToWriter(
            msg: Message,
            ttyconf: std.debug.TTY.Config,
            stderr: anytype,
            kind: []const u8,
            color: std.debug.TTY.Color,
            indent: usize,
        ) anyerror!void {
            var counting_writer = std.io.countingWriter(stderr);
            const counting_stderr = counting_writer.writer();
            switch (msg) {
                .src => |src| {
                    try counting_stderr.writeByteNTimes(' ', indent);
                    try ttyconf.setColor(stderr, .Bold);
                    try counting_stderr.print("{s}:{d}:{d}: ", .{
                        src.src_path,
                        src.line + 1,
                        src.column + 1,
                    });
                    try ttyconf.setColor(stderr, color);
                    try counting_stderr.writeAll(kind);
                    try counting_stderr.writeAll(": ");
                    // This is the length of the part before the error message:
                    // e.g. "file.zig:4:5: error: "
                    const prefix_len = @intCast(usize, counting_stderr.context.bytes_written);
                    try ttyconf.setColor(stderr, .Reset);
                    try ttyconf.setColor(stderr, .Bold);
                    if (src.count == 1) {
                        try src.writeMsg(stderr, prefix_len);
                        try stderr.writeByte('\n');
                    } else {
                        try src.writeMsg(stderr, prefix_len);
                        try ttyconf.setColor(stderr, .Dim);
                        try stderr.print(" ({d} times)\n", .{src.count});
                    }
                    try ttyconf.setColor(stderr, .Reset);
                    if (src.source_line) |line| {
                        for (line) |b| switch (b) {
                            '\t' => try stderr.writeByte(' '),
                            else => try stderr.writeByte(b),
                        };
                        try stderr.writeByte('\n');
                        // TODO basic unicode code point monospace width
                        const before_caret = src.span.main - src.span.start;
                        // -1 since span.main includes the caret
                        const after_caret = src.span.end - src.span.main -| 1;
                        try stderr.writeByteNTimes(' ', src.column - before_caret);
                        try ttyconf.setColor(stderr, .Green);
                        try stderr.writeByteNTimes('~', before_caret);
                        try stderr.writeByte('^');
                        try stderr.writeByteNTimes('~', after_caret);
                        try stderr.writeByte('\n');
                        try ttyconf.setColor(stderr, .Reset);
                    }
                    for (src.notes) |note| {
                        try note.renderToWriter(ttyconf, stderr, "note", .Cyan, indent);
                    }
                    if (src.reference_trace.len != 0) {
                        try ttyconf.setColor(stderr, .Reset);
                        try ttyconf.setColor(stderr, .Dim);
                        try stderr.print("referenced by:\n", .{});
                        for (src.reference_trace) |reference| {
                            switch (reference) {
                                .src => |ref_src| try stderr.print("    {s}: {s}:{d}:{d}\n", .{
                                    ref_src.msg,
                                    ref_src.src_path,
                                    ref_src.line + 1,
                                    ref_src.column + 1,
                                }),
                                .plain => |plain| if (plain.count != 0) {
                                    try stderr.print(
                                        "    {d} reference(s) hidden; use '-freference-trace={d}' to see all references\n",
                                        .{ plain.count, plain.count + src.reference_trace.len - 1 },
                                    );
                                } else {
                                    try stderr.print(
                                        "    remaining reference traces hidden; use '-freference-trace' to see all reference traces\n",
                                        .{},
                                    );
                                },
                            }
                        }
                        try stderr.writeByte('\n');
                        try ttyconf.setColor(stderr, .Reset);
                    }
                },
                .plain => |plain| {
                    try ttyconf.setColor(stderr, color);
                    try stderr.writeByteNTimes(' ', indent);
                    try stderr.writeAll(kind);
                    try stderr.writeAll(": ");
                    try ttyconf.setColor(stderr, .Reset);
                    if (plain.count == 1) {
                        try stderr.print("{s}\n", .{plain.msg});
                    } else {
                        try stderr.print("{s}", .{plain.msg});
                        try ttyconf.setColor(stderr, .Dim);
                        try stderr.print(" ({d} times)\n", .{plain.count});
                    }
                    try ttyconf.setColor(stderr, .Reset);
                    for (plain.notes) |note| {
                        try note.renderToWriter(ttyconf, stderr, "note", .Cyan, indent + 4);
                    }
                },
            }
        }

        pub const HashContext = struct {
            pub fn hash(ctx: HashContext, key: *Message) u64 {
                _ = ctx;
                var hasher = std.hash.Wyhash.init(0);

                switch (key.*) {
                    .src => |src| {
                        hasher.update(src.msg);
                        hasher.update(src.src_path);
                        std.hash.autoHash(&hasher, src.line);
                        std.hash.autoHash(&hasher, src.column);
                        std.hash.autoHash(&hasher, src.span.main);
                    },
                    .plain => |plain| {
                        hasher.update(plain.msg);
                    },
                }

                return hasher.final();
            }

            pub fn eql(ctx: HashContext, a: *Message, b: *Message) bool {
                _ = ctx;
                switch (a.*) {
                    .src => |a_src| switch (b.*) {
                        .src => |b_src| {
                            return mem.eql(u8, a_src.msg, b_src.msg) and
                                mem.eql(u8, a_src.src_path, b_src.src_path) and
                                a_src.line == b_src.line and
                                a_src.column == b_src.column and
                                a_src.span.main == b_src.span.main;
                        },
                        .plain => return false,
                    },
                    .plain => |a_plain| switch (b.*) {
                        .src => return false,
                        .plain => |b_plain| {
                            return mem.eql(u8, a_plain.msg, b_plain.msg);
                        },
                    },
                }
            }
        };
    };

    pub fn deinit(self: *AllErrors, gpa: Allocator) void {
        self.arena.promote(gpa).deinit();
    }

    pub fn add(
        module: *Module,
        arena: *std.heap.ArenaAllocator,
        errors: *std.ArrayList(Message),
        module_err_msg: Module.ErrorMsg,
    ) !void {
        const allocator = arena.allocator();

        const notes_buf = try allocator.alloc(Message, module_err_msg.notes.len);
        var note_i: usize = 0;

        // De-duplicate error notes. The main use case in mind for this is
        // too many "note: called from here" notes when eval branch quota is reached.
        var seen_notes = std.HashMap(
            *Message,
            void,
            Message.HashContext,
            std.hash_map.default_max_load_percentage,
        ).init(allocator);
        const err_source = module_err_msg.src_loc.file_scope.getSource(module.gpa) catch |err| {
            const file_path = try module_err_msg.src_loc.file_scope.fullPath(allocator);
            try errors.append(.{
                .plain = .{
                    .msg = try std.fmt.allocPrint(allocator, "unable to load '{s}': {s}", .{
                        file_path, @errorName(err),
                    }),
                },
            });
            return;
        };
        const err_span = try module_err_msg.src_loc.span(module.gpa);
        const err_loc = std.zig.findLineColumn(err_source.bytes, err_span.main);

        for (module_err_msg.notes) |module_note| {
            const source = try module_note.src_loc.file_scope.getSource(module.gpa);
            const span = try module_note.src_loc.span(module.gpa);
            const loc = std.zig.findLineColumn(source.bytes, span.main);
            const file_path = try module_note.src_loc.file_scope.fullPath(allocator);
            const note = &notes_buf[note_i];
            note.* = .{
                .src = .{
                    .src_path = file_path,
                    .msg = try allocator.dupe(u8, module_note.msg),
                    .span = span,
                    .line = @intCast(u32, loc.line),
                    .column = @intCast(u32, loc.column),
                    .source_line = if (err_loc.eql(loc)) null else try allocator.dupe(u8, loc.source_line),
                },
            };
            const gop = try seen_notes.getOrPut(note);
            if (gop.found_existing) {
                gop.key_ptr.*.incrementCount();
            } else {
                note_i += 1;
            }
        }

        const reference_trace = try allocator.alloc(Message, module_err_msg.reference_trace.len);
        for (reference_trace, 0..) |*reference, i| {
            const module_reference = module_err_msg.reference_trace[i];
            if (module_reference.hidden != 0) {
                reference.* = .{ .plain = .{ .msg = undefined, .count = module_reference.hidden } };
                break;
            } else if (module_reference.decl == null) {
                reference.* = .{ .plain = .{ .msg = undefined, .count = 0 } };
                break;
            }
            const source = try module_reference.src_loc.file_scope.getSource(module.gpa);
            const span = try module_reference.src_loc.span(module.gpa);
            const loc = std.zig.findLineColumn(source.bytes, span.main);
            const file_path = try module_reference.src_loc.file_scope.fullPath(allocator);
            reference.* = .{
                .src = .{
                    .src_path = file_path,
                    .msg = try allocator.dupe(u8, std.mem.sliceTo(module_reference.decl.?, 0)),
                    .span = span,
                    .line = @intCast(u32, loc.line),
                    .column = @intCast(u32, loc.column),
                    .source_line = null,
                },
            };
        }
        const file_path = try module_err_msg.src_loc.file_scope.fullPath(allocator);
        try errors.append(.{
            .src = .{
                .src_path = file_path,
                .msg = try allocator.dupe(u8, module_err_msg.msg),
                .span = err_span,
                .line = @intCast(u32, err_loc.line),
                .column = @intCast(u32, err_loc.column),
                .notes = notes_buf[0..note_i],
                .reference_trace = reference_trace,
                .source_line = if (module_err_msg.src_loc.lazy == .entire_file) null else try allocator.dupe(u8, err_loc.source_line),
            },
        });
    }

    pub fn addZir(
        arena: Allocator,
        errors: *std.ArrayList(Message),
        file: *Module.File,
    ) !void {
        assert(file.zir_loaded);
        assert(file.tree_loaded);
        assert(file.source_loaded);
        const payload_index = file.zir.extra[@enumToInt(Zir.ExtraIndex.compile_errors)];
        assert(payload_index != 0);

        const header = file.zir.extraData(Zir.Inst.CompileErrors, payload_index);
        const items_len = header.data.items_len;
        var extra_index = header.end;
        var item_i: usize = 0;
        while (item_i < items_len) : (item_i += 1) {
            const item = file.zir.extraData(Zir.Inst.CompileErrors.Item, extra_index);
            extra_index = item.end;
            const err_span = blk: {
                if (item.data.node != 0) {
                    break :blk Module.SrcLoc.nodeToSpan(&file.tree, item.data.node);
                }
                const token_starts = file.tree.tokens.items(.start);
                const start = token_starts[item.data.token] + item.data.byte_offset;
                const end = start + @intCast(u32, file.tree.tokenSlice(item.data.token).len) - item.data.byte_offset;
                break :blk Module.SrcLoc.Span{ .start = start, .end = end, .main = start };
            };
            const err_loc = std.zig.findLineColumn(file.source, err_span.main);

            var notes: []Message = &[0]Message{};
            if (item.data.notes != 0) {
                const block = file.zir.extraData(Zir.Inst.Block, item.data.notes);
                const body = file.zir.extra[block.end..][0..block.data.body_len];
                notes = try arena.alloc(Message, body.len);
                for (notes, 0..) |*note, i| {
                    const note_item = file.zir.extraData(Zir.Inst.CompileErrors.Item, body[i]);
                    const msg = file.zir.nullTerminatedString(note_item.data.msg);
                    const span = blk: {
                        if (note_item.data.node != 0) {
                            break :blk Module.SrcLoc.nodeToSpan(&file.tree, note_item.data.node);
                        }
                        const token_starts = file.tree.tokens.items(.start);
                        const start = token_starts[note_item.data.token] + note_item.data.byte_offset;
                        const end = start + @intCast(u32, file.tree.tokenSlice(note_item.data.token).len) - item.data.byte_offset;
                        break :blk Module.SrcLoc.Span{ .start = start, .end = end, .main = start };
                    };
                    const loc = std.zig.findLineColumn(file.source, span.main);

                    note.* = .{
                        .src = .{
                            .src_path = try file.fullPath(arena),
                            .msg = try arena.dupe(u8, msg),
                            .span = span,
                            .line = @intCast(u32, loc.line),
                            .column = @intCast(u32, loc.column),
                            .notes = &.{}, // TODO rework this function to be recursive
                            .source_line = if (loc.eql(err_loc)) null else try arena.dupe(u8, loc.source_line),
                        },
                    };
                }
            }

            const msg = file.zir.nullTerminatedString(item.data.msg);
            try errors.append(.{
                .src = .{
                    .src_path = try file.fullPath(arena),
                    .msg = try arena.dupe(u8, msg),
                    .span = err_span,
                    .line = @intCast(u32, err_loc.line),
                    .column = @intCast(u32, err_loc.column),
                    .notes = notes,
                    .source_line = try arena.dupe(u8, err_loc.source_line),
                },
            });
        }
    }

    fn addPlain(
        arena: *std.heap.ArenaAllocator,
        errors: *std.ArrayList(Message),
        msg: []const u8,
    ) !void {
        _ = arena;
        try errors.append(.{ .plain = .{ .msg = msg } });
    }

    fn addPlainWithChildren(
        arena: *std.heap.ArenaAllocator,
        errors: *std.ArrayList(Message),
        msg: []const u8,
        optional_children: ?AllErrors,
    ) !void {
        const allocator = arena.allocator();
        const duped_msg = try allocator.dupe(u8, msg);
        if (optional_children) |*children| {
            try errors.append(.{ .plain = .{
                .msg = duped_msg,
                .notes = try dupeList(children.list, allocator),
            } });
        } else {
            try errors.append(.{ .plain = .{ .msg = duped_msg } });
        }
    }

    fn dupeList(list: []const Message, arena: Allocator) Allocator.Error![]Message {
        const duped_list = try arena.alloc(Message, list.len);
        for (list, 0..) |item, i| {
            duped_list[i] = switch (item) {
                .src => |src| .{ .src = .{
                    .msg = try arena.dupe(u8, src.msg),
                    .src_path = try arena.dupe(u8, src.src_path),
                    .line = src.line,
                    .column = src.column,
                    .span = src.span,
                    .source_line = if (src.source_line) |s| try arena.dupe(u8, s) else null,
                    .notes = try dupeList(src.notes, arena),
                } },
                .plain => |plain| .{ .plain = .{
                    .msg = try arena.dupe(u8, plain.msg),
                    .notes = try dupeList(plain.notes, arena),
                } },
            };
        }
        return duped_list;
    }
};

pub const Directory = Cache.Directory;

pub const EmitLoc = struct {
    /// If this is `null` it means the file will be output to the cache directory.
    /// When provided, both the open file handle and the path name must outlive the `Compilation`.
    directory: ?Compilation.Directory,
    /// This may not have sub-directories in it.
    basename: []const u8,
};

pub const cache_helpers = struct {
    pub fn addEmitLoc(hh: *Cache.HashHelper, emit_loc: EmitLoc) void {
        hh.addBytes(emit_loc.basename);
    }

    pub fn addOptionalEmitLoc(hh: *Cache.HashHelper, optional_emit_loc: ?EmitLoc) void {
        hh.add(optional_emit_loc != null);
        addEmitLoc(hh, optional_emit_loc orelse return);
    }

    pub fn hashCSource(self: *Cache.Manifest, c_source: Compilation.CSourceFile) !void {
        _ = try self.addFile(c_source.src_path, null);
        // Hash the extra flags, with special care to call addFile for file parameters.
        // TODO this logic can likely be improved by utilizing clang_options_data.zig.
        const file_args = [_][]const u8{"-include"};
        var arg_i: usize = 0;
        while (arg_i < c_source.extra_flags.len) : (arg_i += 1) {
            const arg = c_source.extra_flags[arg_i];
            self.hash.addBytes(arg);
            for (file_args) |file_arg| {
                if (mem.eql(u8, file_arg, arg) and arg_i + 1 < c_source.extra_flags.len) {
                    arg_i += 1;
                    _ = try self.addFile(c_source.extra_flags[arg_i], null);
                }
            }
        }
    }
};

pub const ClangPreprocessorMode = enum {
    no,
    /// This means we are doing `zig cc -E -o <path>`.
    yes,
    /// This means we are doing `zig cc -E`.
    stdout,
};

pub const SystemLib = link.SystemLib;
pub const CacheMode = link.CacheMode;

pub const LinkObject = struct {
    path: []const u8,
    must_link: bool = false,
};

pub const InitOptions = struct {
    zig_lib_directory: Directory,
    local_cache_directory: Directory,
    global_cache_directory: Directory,
    target: Target,
    root_name: []const u8,
    main_pkg: ?*Package,
    output_mode: std.builtin.OutputMode,
    thread_pool: *ThreadPool,
    dynamic_linker: ?[]const u8 = null,
    sysroot: ?[]const u8 = null,
    /// `null` means to not emit a binary file.
    emit_bin: ?EmitLoc,
    /// `null` means to not emit a C header file.
    emit_h: ?EmitLoc = null,
    /// `null` means to not emit assembly.
    emit_asm: ?EmitLoc = null,
    /// `null` means to not emit LLVM IR.
    emit_llvm_ir: ?EmitLoc = null,
    /// `null` means to not emit LLVM module bitcode.
    emit_llvm_bc: ?EmitLoc = null,
    /// `null` means to not emit semantic analysis JSON.
    emit_analysis: ?EmitLoc = null,
    /// `null` means to not emit docs.
    emit_docs: ?EmitLoc = null,
    /// `null` means to not emit an import lib.
    emit_implib: ?EmitLoc = null,
    link_mode: ?std.builtin.LinkMode = null,
    dll_export_fns: ?bool = false,
    /// Normally when using LLD to link, Zig uses a file named "lld.id" in the
    /// same directory as the output binary which contains the hash of the link
    /// operation, allowing Zig to skip linking when the hash would be unchanged.
    /// In the case that the output binary is being emitted into a directory which
    /// is externally modified - essentially anything other than zig-cache - then
    /// this flag would be set to disable this machinery to avoid false positives.
    disable_lld_caching: bool = false,
    cache_mode: CacheMode = .incremental,
    optimize_mode: std.builtin.Mode = .Debug,
    keep_source_files_loaded: bool = false,
    clang_argv: []const []const u8 = &[0][]const u8{},
    lib_dirs: []const []const u8 = &[0][]const u8{},
    rpath_list: []const []const u8 = &[0][]const u8{},
    c_source_files: []const CSourceFile = &[0]CSourceFile{},
    link_objects: []LinkObject = &[0]LinkObject{},
    framework_dirs: []const []const u8 = &[0][]const u8{},
    frameworks: std.StringArrayHashMapUnmanaged(SystemLib) = .{},
    system_lib_names: []const []const u8 = &.{},
    system_lib_infos: []const SystemLib = &.{},
    /// These correspond to the WASI libc emulated subcomponents including:
    /// * process clocks
    /// * getpid
    /// * mman
    /// * signal
    wasi_emulated_libs: []const wasi_libc.CRTFile = &[0]wasi_libc.CRTFile{},
    link_libc: bool = false,
    link_libcpp: bool = false,
    link_libunwind: bool = false,
    want_pic: ?bool = null,
    /// This means that if the output mode is an executable it will be a
    /// Position Independent Executable. If the output mode is not an
    /// executable this field is ignored.
    want_pie: ?bool = null,
    want_sanitize_c: ?bool = null,
    want_stack_check: ?bool = null,
    /// null means default.
    /// 0 means no stack protector.
    /// other number means stack protection with that buffer size.
    want_stack_protector: ?u32 = null,
    want_red_zone: ?bool = null,
    omit_frame_pointer: ?bool = null,
    want_valgrind: ?bool = null,
    want_tsan: ?bool = null,
    want_compiler_rt: ?bool = null,
    want_lto: ?bool = null,
    want_unwind_tables: ?bool = null,
    use_llvm: ?bool = null,
    use_lld: ?bool = null,
    use_clang: ?bool = null,
    single_threaded: ?bool = null,
    strip: ?bool = null,
    formatted_panics: ?bool = null,
    rdynamic: bool = false,
    function_sections: bool = false,
    no_builtin: bool = false,
    is_native_os: bool,
    is_native_abi: bool,
    time_report: bool = false,
    stack_report: bool = false,
    link_eh_frame_hdr: bool = false,
    link_emit_relocs: bool = false,
    linker_script: ?[]const u8 = null,
    version_script: ?[]const u8 = null,
    soname: ?[]const u8 = null,
    linker_gc_sections: ?bool = null,
    linker_allow_shlib_undefined: ?bool = null,
    linker_bind_global_refs_locally: ?bool = null,
    linker_import_memory: ?bool = null,
    linker_import_symbols: bool = false,
    linker_import_table: bool = false,
    linker_export_table: bool = false,
    linker_initial_memory: ?u64 = null,
    linker_max_memory: ?u64 = null,
    linker_shared_memory: bool = false,
    linker_global_base: ?u64 = null,
    linker_export_symbol_names: []const []const u8 = &.{},
    linker_print_gc_sections: bool = false,
    linker_print_icf_sections: bool = false,
    linker_print_map: bool = false,
    linker_opt_bisect_limit: i32 = -1,
    each_lib_rpath: ?bool = null,
    build_id: ?bool = null,
    disable_c_depfile: bool = false,
    linker_z_nodelete: bool = false,
    linker_z_notext: bool = false,
    linker_z_defs: bool = false,
    linker_z_origin: bool = false,
    linker_z_now: bool = true,
    linker_z_relro: bool = true,
    linker_z_nocopyreloc: bool = false,
    linker_z_common_page_size: ?u64 = null,
    linker_z_max_page_size: ?u64 = null,
    linker_tsaware: bool = false,
    linker_nxcompat: bool = false,
    linker_dynamicbase: bool = false,
    linker_optimization: ?u8 = null,
    linker_compress_debug_sections: ?link.CompressDebugSections = null,
    linker_module_definition_file: ?[]const u8 = null,
    linker_sort_section: ?link.SortSection = null,
    major_subsystem_version: ?u32 = null,
    minor_subsystem_version: ?u32 = null,
    clang_passthrough_mode: bool = false,
    verbose_cc: bool = false,
    verbose_link: bool = false,
    verbose_air: bool = false,
    verbose_llvm_ir: bool = false,
    verbose_cimport: bool = false,
    verbose_llvm_cpu_features: bool = false,
    is_test: bool = false,
    test_evented_io: bool = false,
    debug_compiler_runtime_libs: bool = false,
    debug_compile_errors: bool = false,
    /// Normally when you create a `Compilation`, Zig will automatically build
    /// and link in required dependencies, such as compiler-rt and libc. When
    /// building such dependencies themselves, this flag must be set to avoid
    /// infinite recursion.
    skip_linker_dependencies: bool = false,
    parent_compilation_link_libc: bool = false,
    hash_style: link.HashStyle = .both,
    entry: ?[]const u8 = null,
    stack_size_override: ?u64 = null,
    image_base_override: ?u64 = null,
    self_exe_path: ?[]const u8 = null,
    version: ?std.builtin.Version = null,
    compatibility_version: ?std.builtin.Version = null,
    libc_installation: ?*const LibCInstallation = null,
    machine_code_model: std.builtin.CodeModel = .default,
    clang_preprocessor_mode: ClangPreprocessorMode = .no,
    /// This is for stage1 and should be deleted upon completion of self-hosting.
    color: Color = .auto,
    reference_trace: ?u32 = null,
    error_tracing: ?bool = null,
    test_filter: ?[]const u8 = null,
    test_name_prefix: ?[]const u8 = null,
    test_runner_path: ?[]const u8 = null,
    subsystem: ?std.Target.SubSystem = null,
    /// WASI-only. Type of WASI execution model ("command" or "reactor").
    wasi_exec_model: ?std.builtin.WasiExecModel = null,
    /// (Zig compiler development) Enable dumping linker's state as JSON.
    enable_link_snapshots: bool = false,
    /// (Darwin) Path and version of the native SDK if detected.
    native_darwin_sdk: ?std.zig.system.darwin.DarwinSDK = null,
    /// (Darwin) Install name of the dylib
    install_name: ?[]const u8 = null,
    /// (Darwin) Path to entitlements file
    entitlements: ?[]const u8 = null,
    /// (Darwin) size of the __PAGEZERO segment
    pagezero_size: ?u64 = null,
    /// (Darwin) search strategy for system libraries
    search_strategy: ?link.File.MachO.SearchStrategy = null,
    /// (Darwin) set minimum space for future expansion of the load commands
    headerpad_size: ?u32 = null,
    /// (Darwin) set enough space as if all paths were MATPATHLEN
    headerpad_max_install_names: bool = false,
    /// (Darwin) remove dylibs that are unreachable by the entry point or exported symbols
    dead_strip_dylibs: bool = false,
    libcxx_abi_version: libcxx.AbiVersion = libcxx.AbiVersion.default,
    /// (Windows) PDB source path prefix to instruct the linker how to resolve relative
    /// paths when consolidating CodeView streams into a single PDB file.
    pdb_source_path: ?[]const u8 = null,
    /// (Windows) PDB output path
    pdb_out_path: ?[]const u8 = null,
};

fn addPackageTableToCacheHash(
    hash: *Cache.HashHelper,
    arena: *std.heap.ArenaAllocator,
    pkg_table: Package.Table,
    seen_table: *std.AutoHashMap(*Package, void),
    hash_type: union(enum) { path_bytes, files: *Cache.Manifest },
) (error{OutOfMemory} || std.os.GetCwdError)!void {
    const allocator = arena.allocator();

    const packages = try allocator.alloc(Package.Table.KV, pkg_table.count());
    {
        // Copy over the hashmap entries to our slice
        var table_it = pkg_table.iterator();
        var idx: usize = 0;
        while (table_it.next()) |entry| : (idx += 1) {
            packages[idx] = .{
                .key = entry.key_ptr.*,
                .value = entry.value_ptr.*,
            };
        }
    }
    // Sort the slice by package name
    std.sort.sort(Package.Table.KV, packages, {}, struct {
        fn lessThan(_: void, lhs: Package.Table.KV, rhs: Package.Table.KV) bool {
            return std.mem.lessThan(u8, lhs.key, rhs.key);
        }
    }.lessThan);

    for (packages) |pkg| {
        if ((try seen_table.getOrPut(pkg.value)).found_existing) continue;

        // Finally insert the package name and path to the cache hash.
        hash.addBytes(pkg.key);
        switch (hash_type) {
            .path_bytes => {
                hash.addBytes(pkg.value.root_src_path);
                hash.addOptionalBytes(pkg.value.root_src_directory.path);
            },
            .files => |man| {
                const pkg_zig_file = try pkg.value.root_src_directory.join(allocator, &[_][]const u8{
                    pkg.value.root_src_path,
                });
                _ = try man.addFile(pkg_zig_file, null);
            },
        }
        // Recurse to handle the package's dependencies
        try addPackageTableToCacheHash(hash, arena, pkg.value.table, seen_table, hash_type);
    }
}

pub fn create(gpa: Allocator, options: InitOptions) !*Compilation {
    const is_dyn_lib = switch (options.output_mode) {
        .Obj, .Exe => false,
        .Lib => (options.link_mode orelse .Static) == .Dynamic,
    };
    const is_exe_or_dyn_lib = switch (options.output_mode) {
        .Obj => false,
        .Lib => is_dyn_lib,
        .Exe => true,
    };

    const needs_c_symbols = !options.skip_linker_dependencies and is_exe_or_dyn_lib;

    // WASI-only. Resolve the optional exec-model option, defaults to command.
    const wasi_exec_model = if (options.target.os.tag != .wasi) undefined else options.wasi_exec_model orelse .command;

    if (options.linker_export_table and options.linker_import_table) {
        return error.ExportTableAndImportTableConflict;
    }

    // The `have_llvm` condition is here only because native backends cannot yet build compiler-rt.
    // Once they are capable this condition could be removed. When removing this condition,
    // also test the use case of `build-obj -fcompiler-rt` with the native backends
    // and make sure the compiler-rt symbols are emitted.
    const capable_of_building_compiler_rt = build_options.have_llvm and options.target.os.tag != .plan9;

    const capable_of_building_zig_libc = build_options.have_llvm and options.target.os.tag != .plan9;
    const capable_of_building_ssp = build_options.have_llvm and options.target.os.tag != .plan9;

    const comp: *Compilation = comp: {
        // For allocations that have the same lifetime as Compilation. This arena is used only during this
        // initialization and then is freed in deinit().
        var arena_allocator = std.heap.ArenaAllocator.init(gpa);
        errdefer arena_allocator.deinit();
        const arena = arena_allocator.allocator();

        // We put the `Compilation` itself in the arena. Freeing the arena will free the module.
        // It's initialized later after we prepare the initialization options.
        const comp = try arena.create(Compilation);
        const root_name = try arena.dupeZ(u8, options.root_name);

        // Make a decision on whether to use LLVM or our own backend.
        const use_llvm = build_options.have_llvm and blk: {
            if (options.use_llvm) |explicit|
                break :blk explicit;

            // If emitting to LLVM bitcode object format, must use LLVM backend.
            if (options.emit_llvm_ir != null or options.emit_llvm_bc != null)
                break :blk true;

            // If we have no zig code to compile, no need for LLVM.
            if (options.main_pkg == null)
                break :blk false;

            // If LLVM does not support the target, then we can't use it.
            if (!target_util.hasLlvmSupport(options.target, options.target.ofmt))
                break :blk false;

            // Prefer LLVM for release builds.
            if (options.optimize_mode != .Debug)
                break :blk true;

            // At this point we would prefer to use our own self-hosted backend,
            // because the compilation speed is better than LLVM. But only do it if
            // we are confident in the robustness of the backend.
            break :blk !target_util.selfHostedBackendIsAsRobustAsLlvm(options.target);
        };
        if (!use_llvm) {
            if (options.use_llvm == true) {
                return error.ZigCompilerNotBuiltWithLLVMExtensions;
            }
            if (options.emit_llvm_ir != null or options.emit_llvm_bc != null) {
                return error.EmittingLlvmModuleRequiresUsingLlvmBackend;
            }
        }

        // TODO: once we support incremental compilation for the LLVM backend via
        // saving the LLVM module into a bitcode file and restoring it, along with
        // compiler state, the second clause here can be removed so that incremental
        // cache mode is used for LLVM backend too. We need some fuzz testing before
        // that can be enabled.
        const cache_mode = if (use_llvm and !options.disable_lld_caching)
            CacheMode.whole
        else
            options.cache_mode;

        const tsan = options.want_tsan orelse false;
        // TSAN is implemented in C++ so it requires linking libc++.
        const link_libcpp = options.link_libcpp or tsan;
        const link_libc = link_libcpp or options.link_libc or options.link_libunwind or
            target_util.osRequiresLibC(options.target);

        const link_libunwind = options.link_libunwind or
            (link_libcpp and target_util.libcNeedsLibUnwind(options.target));
        const unwind_tables = options.want_unwind_tables orelse
            (link_libunwind or target_util.needUnwindTables(options.target));
        const link_eh_frame_hdr = options.link_eh_frame_hdr or unwind_tables;
        const build_id = options.build_id orelse false;

        // Make a decision on whether to use LLD or our own linker.
        const use_lld = options.use_lld orelse blk: {
            if (options.target.isDarwin()) {
                break :blk false;
            }

            if (!build_options.have_llvm)
                break :blk false;

            if (options.target.ofmt == .c)
                break :blk false;

            if (options.want_lto) |lto| {
                if (lto) {
                    break :blk true;
                }
            }

            // Our linker can't handle objects or most advanced options yet.
            if (options.link_objects.len != 0 or
                options.c_source_files.len != 0 or
                options.frameworks.count() != 0 or
                options.system_lib_names.len != 0 or
                options.link_libc or options.link_libcpp or
                link_eh_frame_hdr or
                options.link_emit_relocs or
                options.output_mode == .Lib or
                options.linker_script != null or options.version_script != null or
                options.emit_implib != null or
                build_id)
            {
                break :blk true;
            }

            if (use_llvm) {
                // If stage1 generates an object file, self-hosted linker is not
                // yet sophisticated enough to handle that.
                break :blk options.main_pkg != null;
            }

            break :blk false;
        };

        const sysroot = blk: {
            if (options.sysroot) |sysroot| {
                break :blk sysroot;
            } else if (options.native_darwin_sdk) |sdk| {
                break :blk sdk.path;
            } else {
                break :blk null;
            }
        };

        const lto = blk: {
            if (options.want_lto) |explicit| {
                if (!use_lld and !options.target.isDarwin())
                    return error.LtoUnavailableWithoutLld;
                break :blk explicit;
            } else if (!use_lld) {
                // TODO zig ld LTO support
                // See https://github.com/ziglang/zig/issues/8680
                break :blk false;
            } else if (options.c_source_files.len == 0) {
                break :blk false;
            } else if (options.target.cpu.arch.isRISCV()) {
                // Clang and LLVM currently don't support RISC-V target-abi for LTO.
                // Compiling with LTO may fail or produce undesired results.
                // See https://reviews.llvm.org/D71387
                // See https://reviews.llvm.org/D102582
                break :blk false;
            } else switch (options.output_mode) {
                .Lib, .Obj => break :blk false,
                .Exe => switch (options.optimize_mode) {
                    .Debug => break :blk false,
                    .ReleaseSafe, .ReleaseFast, .ReleaseSmall => break :blk true,
                },
            }
        };

        const must_dynamic_link = dl: {
            if (target_util.cannotDynamicLink(options.target))
                break :dl false;
            if (is_exe_or_dyn_lib and link_libc and
                (options.target.isGnuLibC() or target_util.osRequiresLibC(options.target)))
            {
                break :dl true;
            }
            const any_dyn_libs: bool = x: {
                if (options.system_lib_names.len != 0)
                    break :x true;
                for (options.link_objects) |obj| {
                    switch (classifyFileExt(obj.path)) {
                        .shared_library => break :x true,
                        else => continue,
                    }
                }
                break :x false;
            };
            if (any_dyn_libs) {
                // When creating a executable that links to system libraries,
                // we require dynamic linking, but we must not link static libraries
                // or object files dynamically!
                break :dl (options.output_mode == .Exe);
            }

            break :dl false;
        };
        const default_link_mode: std.builtin.LinkMode = blk: {
            if (must_dynamic_link) {
                break :blk .Dynamic;
            } else if (is_exe_or_dyn_lib and link_libc and
                options.is_native_abi and options.target.abi.isMusl())
            {
                // If targeting the system's native ABI and the system's
                // libc is musl, link dynamically by default.
                break :blk .Dynamic;
            } else {
                break :blk .Static;
            }
        };
        const link_mode: std.builtin.LinkMode = if (options.link_mode) |lm| blk: {
            if (lm == .Static and must_dynamic_link) {
                return error.UnableToStaticLink;
            }
            break :blk lm;
        } else default_link_mode;

        const dll_export_fns = options.dll_export_fns orelse (is_dyn_lib or options.rdynamic);

        const libc_dirs = try detectLibCIncludeDirs(
            arena,
            options.zig_lib_directory.path.?,
            options.target,
            options.is_native_abi,
            link_libc,
            options.libc_installation,
            options.native_darwin_sdk != null,
        );

        const must_pie = target_util.requiresPIE(options.target);
        const pie: bool = if (options.want_pie) |explicit| pie: {
            if (!explicit and must_pie) {
                return error.TargetRequiresPIE;
            }
            break :pie explicit;
        } else must_pie or tsan;

        const must_pic: bool = b: {
            if (target_util.requiresPIC(options.target, link_libc))
                break :b true;
            break :b link_mode == .Dynamic;
        };
        const pic = if (options.want_pic) |explicit| pic: {
            if (!explicit) {
                if (must_pic) {
                    return error.TargetRequiresPIC;
                }
                if (pie) {
                    return error.PIERequiresPIC;
                }
            }
            break :pic explicit;
        } else pie or must_pic;

        // Make a decision on whether to use Clang for translate-c and compiling C files.
        const use_clang = if (options.use_clang) |explicit| explicit else blk: {
            if (build_options.have_llvm) {
                // Can't use it if we don't have it!
                break :blk false;
            }
            // It's not planned to do our own translate-c or C compilation.
            break :blk true;
        };

        const is_safe_mode = switch (options.optimize_mode) {
            .Debug, .ReleaseSafe => true,
            .ReleaseFast, .ReleaseSmall => false,
        };

        const sanitize_c = options.want_sanitize_c orelse is_safe_mode;

        const stack_check: bool = options.want_stack_check orelse b: {
            if (!target_util.supportsStackProbing(options.target)) break :b false;
            break :b is_safe_mode;
        };
        if (stack_check and !target_util.supportsStackProbing(options.target))
            return error.StackCheckUnsupportedByTarget;

        const stack_protector: u32 = options.want_stack_protector orelse b: {
            if (!target_util.supportsStackProtector(options.target)) break :b @as(u32, 0);

            // This logic is checking for linking libc because otherwise our start code
            // which is trying to set up TLS (i.e. the fs/gs registers) but the stack
            // protection code depends on fs/gs registers being already set up.
            // If we were able to annotate start code, or perhaps the entire std lib,
            // as being exempt from stack protection checks, we could change this logic
            // to supporting stack protection even when not linking libc.
            // TODO file issue about this
            if (!link_libc) break :b 0;
            if (!capable_of_building_ssp) break :b 0;
            if (is_safe_mode) break :b default_stack_protector_buffer_size;
            break :b 0;
        };
        if (stack_protector != 0) {
            if (!target_util.supportsStackProtector(options.target))
                return error.StackProtectorUnsupportedByTarget;
            if (!capable_of_building_ssp)
                return error.StackProtectorUnsupportedByBackend;
            if (!link_libc)
                return error.StackProtectorUnavailableWithoutLibC;
        }

        const valgrind: bool = b: {
            if (!target_util.hasValgrindSupport(options.target))
                break :b false;
            break :b options.want_valgrind orelse (options.optimize_mode == .Debug);
        };

        const include_compiler_rt = options.want_compiler_rt orelse needs_c_symbols;

        const must_single_thread = target_util.isSingleThreaded(options.target);
        const single_threaded = options.single_threaded orelse must_single_thread;
        if (must_single_thread and !single_threaded) {
            return error.TargetRequiresSingleThreaded;
        }
        if (!single_threaded and options.link_libcpp) {
            if (options.target.cpu.arch.isARM()) {
                log.warn(
                    \\libc++ does not work on multi-threaded ARM yet.
                    \\For more details: https://github.com/ziglang/zig/issues/6573
                , .{});
                return error.TargetRequiresSingleThreaded;
            }
        }

        const llvm_cpu_features: ?[*:0]const u8 = if (build_options.have_llvm and use_llvm) blk: {
            var buf = std.ArrayList(u8).init(arena);
            for (options.target.cpu.arch.allFeaturesList(), 0..) |feature, index_usize| {
                const index = @intCast(Target.Cpu.Feature.Set.Index, index_usize);
                const is_enabled = options.target.cpu.features.isEnabled(index);

                if (feature.llvm_name) |llvm_name| {
                    const plus_or_minus = "-+"[@boolToInt(is_enabled)];
                    try buf.ensureUnusedCapacity(2 + llvm_name.len);
                    buf.appendAssumeCapacity(plus_or_minus);
                    buf.appendSliceAssumeCapacity(llvm_name);
                    buf.appendSliceAssumeCapacity(",");
                }
            }
            assert(mem.endsWith(u8, buf.items, ","));
            buf.items[buf.items.len - 1] = 0;
            buf.shrinkAndFree(buf.items.len);
            break :blk buf.items[0 .. buf.items.len - 1 :0].ptr;
        } else null;

        const strip = options.strip orelse !target_util.hasDebugInfo(options.target);
        const red_zone = options.want_red_zone orelse target_util.hasRedZone(options.target);
        const omit_frame_pointer = options.omit_frame_pointer orelse (options.optimize_mode != .Debug);
        const linker_optimization: u8 = options.linker_optimization orelse switch (options.optimize_mode) {
            .Debug => @as(u8, 0),
            else => @as(u8, 3),
        };
        const formatted_panics = options.formatted_panics orelse (options.optimize_mode == .Debug);

        // We put everything into the cache hash that *cannot be modified
        // during an incremental update*. For example, one cannot change the
        // target between updates, but one can change source files, so the
        // target goes into the cache hash, but source files do not. This is so
        // that we can find the same binary and incrementally update it even if
        // there are modified source files. We do this even if outputting to
        // the current directory because we need somewhere to store incremental
        // compilation metadata.
        const cache = try arena.create(Cache);
        cache.* = .{
            .gpa = gpa,
            .manifest_dir = try options.local_cache_directory.handle.makeOpenPath("h", .{}),
        };
        cache.addPrefix(.{ .path = null, .handle = std.fs.cwd() });
        cache.addPrefix(options.zig_lib_directory);
        cache.addPrefix(options.local_cache_directory);
        errdefer cache.manifest_dir.close();

        // This is shared hasher state common to zig source and all C source files.
        cache.hash.addBytes(build_options.version);
        cache.hash.add(builtin.zig_backend);
        cache.hash.add(options.optimize_mode);
        cache.hash.add(options.target.cpu.arch);
        cache.hash.addBytes(options.target.cpu.model.name);
        cache.hash.add(options.target.cpu.features.ints);
        cache.hash.add(options.target.os.tag);
        cache.hash.add(options.target.os.getVersionRange());
        cache.hash.add(options.is_native_os);
        cache.hash.add(options.target.abi);
        cache.hash.add(options.target.ofmt);
        cache.hash.add(pic);
        cache.hash.add(pie);
        cache.hash.add(lto);
        cache.hash.add(unwind_tables);
        cache.hash.add(tsan);
        cache.hash.add(stack_check);
        cache.hash.add(stack_protector);
        cache.hash.add(red_zone);
        cache.hash.add(omit_frame_pointer);
        cache.hash.add(link_mode);
        cache.hash.add(options.function_sections);
        cache.hash.add(options.no_builtin);
        cache.hash.add(strip);
        cache.hash.add(link_libc);
        cache.hash.add(link_libcpp);
        cache.hash.add(link_libunwind);
        cache.hash.add(options.output_mode);
        cache.hash.add(options.machine_code_model);
        cache_helpers.addOptionalEmitLoc(&cache.hash, options.emit_bin);
        cache_helpers.addOptionalEmitLoc(&cache.hash, options.emit_implib);
        cache.hash.addBytes(options.root_name);
        if (options.target.os.tag == .wasi) cache.hash.add(wasi_exec_model);
        // TODO audit this and make sure everything is in it

        const module: ?*Module = if (options.main_pkg) |main_pkg| blk: {
            // Options that are specific to zig source files, that cannot be
            // modified between incremental updates.
            var hash = cache.hash;

            switch (cache_mode) {
                .incremental => {
                    // Here we put the root source file path name, but *not* with addFile.
                    // We want the hash to be the same regardless of the contents of the
                    // source file, because incremental compilation will handle it, but we
                    // do want to namespace different source file names because they are
                    // likely different compilations and therefore this would be likely to
                    // cause cache hits.
                    hash.addBytes(main_pkg.root_src_path);
                    hash.addOptionalBytes(main_pkg.root_src_directory.path);
                    {
                        var seen_table = std.AutoHashMap(*Package, void).init(arena);
                        try addPackageTableToCacheHash(&hash, &arena_allocator, main_pkg.table, &seen_table, .path_bytes);
                    }
                },
                .whole => {
                    // In this case, we postpone adding the input source file until
                    // we create the cache manifest, in update(), because we want to
                    // track it and packages as files.
                },
            }

            // Synchronize with other matching comments: ZigOnlyHashStuff
            hash.add(valgrind);
            hash.add(single_threaded);
            hash.add(use_llvm);
            hash.add(dll_export_fns);
            hash.add(options.is_test);
            hash.add(options.test_evented_io);
            hash.addOptionalBytes(options.test_filter);
            hash.addOptionalBytes(options.test_name_prefix);
            hash.add(options.skip_linker_dependencies);
            hash.add(options.parent_compilation_link_libc);
            hash.add(formatted_panics);

            // In the case of incremental cache mode, this `zig_cache_artifact_directory`
            // is computed based on a hash of non-linker inputs, and it is where all
            // build artifacts are stored (even while in-progress).
            //
            // For whole cache mode, it is still used for builtin.zig so that the file
            // path to builtin.zig can remain consistent during a debugging session at
            // runtime. However, we don't know where to put outputs from the linker
            // or stage1 backend object files until the final cache hash, which is available
            // after the compilation is complete.
            //
            // Therefore, in whole cache mode, we additionally create a temporary cache
            // directory for these two kinds of build artifacts, and then rename it
            // into place after the final hash is known. However, we don't want
            // to create the temporary directory here, because in the case of a cache hit,
            // this would have been wasted syscalls to make the directory and then not
            // use it (or delete it).
            //
            // In summary, for whole cache mode, we simulate `-fno-emit-bin` in this
            // function, and `zig_cache_artifact_directory` is *wrong* except for builtin.zig,
            // and then at the beginning of `update()` when we find out whether we need
            // a temporary directory, we patch up all the places that the incorrect
            // `zig_cache_artifact_directory` was passed to various components of the compiler.

            const digest = hash.final();
            const artifact_sub_dir = try std.fs.path.join(arena, &[_][]const u8{ "o", &digest });
            var artifact_dir = try options.local_cache_directory.handle.makeOpenPath(artifact_sub_dir, .{});
            errdefer artifact_dir.close();
            const zig_cache_artifact_directory: Directory = .{
                .handle = artifact_dir,
                .path = try options.local_cache_directory.join(arena, &[_][]const u8{artifact_sub_dir}),
            };

            const builtin_pkg = try Package.createWithDir(
                gpa,
                zig_cache_artifact_directory,
                null,
                "builtin.zig",
            );
            errdefer builtin_pkg.destroy(gpa);

            // When you're testing std, the main module is std. In that case, we'll just set the std
            // module to the main one, since avoiding the errors caused by duplicating it is more
            // effort than it's worth.
            const main_pkg_is_std = m: {
                const std_path = try std.fs.path.resolve(arena, &[_][]const u8{
                    options.zig_lib_directory.path orelse ".",
                    "std",
                    "std.zig",
                });
                defer arena.free(std_path);
                const main_path = try std.fs.path.resolve(arena, &[_][]const u8{
                    main_pkg.root_src_directory.path orelse ".",
                    main_pkg.root_src_path,
                });
                defer arena.free(main_path);
                break :m mem.eql(u8, main_path, std_path);
            };

            const std_pkg = if (main_pkg_is_std)
                main_pkg
            else
                try Package.createWithDir(
                    gpa,
                    options.zig_lib_directory,
                    "std",
                    "std.zig",
                );

            errdefer if (!main_pkg_is_std) std_pkg.destroy(gpa);

            const root_pkg = if (options.is_test) root_pkg: {
                const test_pkg = if (options.test_runner_path) |test_runner| test_pkg: {
                    const test_dir = std.fs.path.dirname(test_runner);
                    const basename = std.fs.path.basename(test_runner);
                    const pkg = try Package.create(gpa, test_dir, basename);

                    // copy package table from main_pkg to root_pkg
                    pkg.table = try main_pkg.table.clone(gpa);
                    break :test_pkg pkg;
                } else try Package.createWithDir(
                    gpa,
                    options.zig_lib_directory,
                    null,
                    "test_runner.zig",
                );
                errdefer test_pkg.destroy(gpa);

                break :root_pkg test_pkg;
            } else main_pkg;
            errdefer if (options.is_test) root_pkg.destroy(gpa);

            const compiler_rt_pkg = if (include_compiler_rt and options.output_mode == .Obj) compiler_rt_pkg: {
                break :compiler_rt_pkg try Package.createWithDir(
                    gpa,
                    options.zig_lib_directory,
                    null,
                    "compiler_rt.zig",
                );
            } else null;
            errdefer if (compiler_rt_pkg) |p| p.destroy(gpa);

            try main_pkg.add(gpa, "builtin", builtin_pkg);
            try main_pkg.add(gpa, "root", root_pkg);
            try main_pkg.add(gpa, "std", std_pkg);

            if (compiler_rt_pkg) |p| {
                try main_pkg.add(gpa, "compiler_rt", p);
            }

            // Pre-open the directory handles for cached ZIR code so that it does not need
            // to redundantly happen for each AstGen operation.
            const zir_sub_dir = "z";

            var local_zir_dir = try options.local_cache_directory.handle.makeOpenPath(zir_sub_dir, .{});
            errdefer local_zir_dir.close();
            const local_zir_cache: Directory = .{
                .handle = local_zir_dir,
                .path = try options.local_cache_directory.join(arena, &[_][]const u8{zir_sub_dir}),
            };
            var global_zir_dir = try options.global_cache_directory.handle.makeOpenPath(zir_sub_dir, .{});
            errdefer global_zir_dir.close();
            const global_zir_cache: Directory = .{
                .handle = global_zir_dir,
                .path = try options.global_cache_directory.join(arena, &[_][]const u8{zir_sub_dir}),
            };

            const emit_h: ?*Module.GlobalEmitH = if (options.emit_h) |loc| eh: {
                const eh = try gpa.create(Module.GlobalEmitH);
                eh.* = .{ .loc = loc };
                break :eh eh;
            } else null;
            errdefer if (emit_h) |eh| gpa.destroy(eh);

            // TODO when we implement serialization and deserialization of incremental
            // compilation metadata, this is where we would load it. We have open a handle
            // to the directory where the output either already is, or will be.
            // However we currently do not have serialization of such metadata, so for now
            // we set up an empty Module that does the entire compilation fresh.

            const module = try arena.create(Module);
            errdefer module.deinit();
            module.* = .{
                .gpa = gpa,
                .comp = comp,
                .main_pkg = main_pkg,
                .root_pkg = root_pkg,
                .zig_cache_artifact_directory = zig_cache_artifact_directory,
                .global_zir_cache = global_zir_cache,
                .local_zir_cache = local_zir_cache,
                .emit_h = emit_h,
                .error_name_list = .{},
            };
            try module.error_name_list.append(gpa, "(no error)");

            break :blk module;
        } else blk: {
            if (options.emit_h != null) return error.NoZigModuleForCHeader;
            break :blk null;
        };
        errdefer if (module) |zm| zm.deinit();

        const error_return_tracing = !strip and switch (options.optimize_mode) {
            .Debug, .ReleaseSafe => (!options.target.isWasm() or options.target.os.tag == .emscripten) and
                !options.target.cpu.arch.isBpf() and (options.error_tracing orelse true),
            .ReleaseFast => options.error_tracing orelse false,
            .ReleaseSmall => false,
        };

        // For resource management purposes.
        var owned_link_dir: ?std.fs.Dir = null;
        errdefer if (owned_link_dir) |*dir| dir.close();

        const bin_file_emit: ?link.Emit = blk: {
            const emit_bin = options.emit_bin orelse break :blk null;

            if (emit_bin.directory) |directory| {
                break :blk link.Emit{
                    .directory = directory,
                    .sub_path = emit_bin.basename,
                };
            }

            switch (cache_mode) {
                .whole => break :blk null,
                .incremental => {},
            }

            if (module) |zm| {
                break :blk link.Emit{
                    .directory = zm.zig_cache_artifact_directory,
                    .sub_path = emit_bin.basename,
                };
            }

            // We could use the cache hash as is no problem, however, we increase
            // the likelihood of cache hits by adding the first C source file
            // path name (not contents) to the hash. This way if the user is compiling
            // foo.c and bar.c as separate compilations, they get different cache
            // directories.
            var hash = cache.hash;
            if (options.c_source_files.len >= 1) {
                hash.addBytes(options.c_source_files[0].src_path);
            } else if (options.link_objects.len >= 1) {
                hash.addBytes(options.link_objects[0].path);
            }

            const digest = hash.final();
            const artifact_sub_dir = try std.fs.path.join(arena, &[_][]const u8{ "o", &digest });
            var artifact_dir = try options.local_cache_directory.handle.makeOpenPath(artifact_sub_dir, .{});
            owned_link_dir = artifact_dir;
            const link_artifact_directory: Directory = .{
                .handle = artifact_dir,
                .path = try options.local_cache_directory.join(arena, &[_][]const u8{artifact_sub_dir}),
            };
            break :blk link.Emit{
                .directory = link_artifact_directory,
                .sub_path = emit_bin.basename,
            };
        };

        const implib_emit: ?link.Emit = blk: {
            const emit_implib = options.emit_implib orelse break :blk null;

            if (emit_implib.directory) |directory| {
                break :blk link.Emit{
                    .directory = directory,
                    .sub_path = emit_implib.basename,
                };
            }

            // This is here for the same reason as in `bin_file_emit` above.
            switch (cache_mode) {
                .whole => break :blk null,
                .incremental => {},
            }

            // Use the same directory as the bin. The CLI already emits an
            // error if -fno-emit-bin is combined with -femit-implib.
            break :blk link.Emit{
                .directory = bin_file_emit.?.directory,
                .sub_path = emit_implib.basename,
            };
        };

        // This is so that when doing `CacheMode.whole`, the mechanism in update()
        // can use it for communicating the result directory via `bin_file.emit`.
        // This is used to distinguish between -fno-emit-bin and -femit-bin
        // for `CacheMode.whole`.
        // This memory will be overwritten with the real digest in update() but
        // the basename will be preserved.
        const whole_bin_sub_path: ?[]u8 = try prepareWholeEmitSubPath(arena, options.emit_bin);
        // Same thing but for implibs.
        const whole_implib_sub_path: ?[]u8 = try prepareWholeEmitSubPath(arena, options.emit_implib);

        var system_libs: std.StringArrayHashMapUnmanaged(SystemLib) = .{};
        errdefer system_libs.deinit(gpa);
        try system_libs.ensureTotalCapacity(gpa, options.system_lib_names.len);
        for (options.system_lib_names, 0..) |lib_name, i| {
            system_libs.putAssumeCapacity(lib_name, options.system_lib_infos[i]);
        }

        const bin_file = try link.File.openPath(gpa, .{
            .emit = bin_file_emit,
            .implib_emit = implib_emit,
            .root_name = root_name,
            .module = module,
            .target = options.target,
            .dynamic_linker = options.dynamic_linker,
            .sysroot = sysroot,
            .output_mode = options.output_mode,
            .link_mode = link_mode,
            .optimize_mode = options.optimize_mode,
            .use_lld = use_lld,
            .use_llvm = use_llvm,
            .link_libc = link_libc,
            .link_libcpp = link_libcpp,
            .link_libunwind = link_libunwind,
            .objects = options.link_objects,
            .frameworks = options.frameworks,
            .framework_dirs = options.framework_dirs,
            .system_libs = system_libs,
            .wasi_emulated_libs = options.wasi_emulated_libs,
            .lib_dirs = options.lib_dirs,
            .rpath_list = options.rpath_list,
            .strip = strip,
            .is_native_os = options.is_native_os,
            .is_native_abi = options.is_native_abi,
            .function_sections = options.function_sections,
            .no_builtin = options.no_builtin,
            .allow_shlib_undefined = options.linker_allow_shlib_undefined,
            .bind_global_refs_locally = options.linker_bind_global_refs_locally orelse false,
            .compress_debug_sections = options.linker_compress_debug_sections orelse .none,
            .module_definition_file = options.linker_module_definition_file,
            .sort_section = options.linker_sort_section,
            .import_memory = options.linker_import_memory orelse false,
            .import_symbols = options.linker_import_symbols,
            .import_table = options.linker_import_table,
            .export_table = options.linker_export_table,
            .initial_memory = options.linker_initial_memory,
            .max_memory = options.linker_max_memory,
            .shared_memory = options.linker_shared_memory,
            .global_base = options.linker_global_base,
            .export_symbol_names = options.linker_export_symbol_names,
            .print_gc_sections = options.linker_print_gc_sections,
            .print_icf_sections = options.linker_print_icf_sections,
            .print_map = options.linker_print_map,
            .opt_bisect_limit = options.linker_opt_bisect_limit,
            .z_nodelete = options.linker_z_nodelete,
            .z_notext = options.linker_z_notext,
            .z_defs = options.linker_z_defs,
            .z_origin = options.linker_z_origin,
            .z_nocopyreloc = options.linker_z_nocopyreloc,
            .z_now = options.linker_z_now,
            .z_relro = options.linker_z_relro,
            .z_common_page_size = options.linker_z_common_page_size,
            .z_max_page_size = options.linker_z_max_page_size,
            .tsaware = options.linker_tsaware,
            .nxcompat = options.linker_nxcompat,
            .dynamicbase = options.linker_dynamicbase,
            .linker_optimization = linker_optimization,
            .major_subsystem_version = options.major_subsystem_version,
            .minor_subsystem_version = options.minor_subsystem_version,
            .entry = options.entry,
            .stack_size_override = options.stack_size_override,
            .image_base_override = options.image_base_override,
            .include_compiler_rt = include_compiler_rt,
            .linker_script = options.linker_script,
            .version_script = options.version_script,
            .gc_sections = options.linker_gc_sections,
            .eh_frame_hdr = link_eh_frame_hdr,
            .emit_relocs = options.link_emit_relocs,
            .rdynamic = options.rdynamic,
            .soname = options.soname,
            .version = options.version,
            .compatibility_version = options.compatibility_version,
            .libc_installation = libc_dirs.libc_installation,
            .pic = pic,
            .pie = pie,
            .lto = lto,
            .valgrind = valgrind,
            .tsan = tsan,
            .stack_check = stack_check,
            .stack_protector = stack_protector,
            .red_zone = red_zone,
            .omit_frame_pointer = omit_frame_pointer,
            .single_threaded = single_threaded,
            .verbose_link = options.verbose_link,
            .machine_code_model = options.machine_code_model,
            .dll_export_fns = dll_export_fns,
            .error_return_tracing = error_return_tracing,
            .llvm_cpu_features = llvm_cpu_features,
            .skip_linker_dependencies = options.skip_linker_dependencies,
            .parent_compilation_link_libc = options.parent_compilation_link_libc,
            .each_lib_rpath = options.each_lib_rpath orelse options.is_native_os,
            .build_id = build_id,
            .cache_mode = cache_mode,
            .disable_lld_caching = options.disable_lld_caching or cache_mode == .whole,
            .subsystem = options.subsystem,
            .is_test = options.is_test,
            .wasi_exec_model = wasi_exec_model,
            .hash_style = options.hash_style,
            .enable_link_snapshots = options.enable_link_snapshots,
            .native_darwin_sdk = options.native_darwin_sdk,
            .install_name = options.install_name,
            .entitlements = options.entitlements,
            .pagezero_size = options.pagezero_size,
            .search_strategy = options.search_strategy,
            .headerpad_size = options.headerpad_size,
            .headerpad_max_install_names = options.headerpad_max_install_names,
            .dead_strip_dylibs = options.dead_strip_dylibs,
            .force_undefined_symbols = .{},
            .pdb_source_path = options.pdb_source_path,
            .pdb_out_path = options.pdb_out_path,
        });
        errdefer bin_file.destroy();
        comp.* = .{
            .gpa = gpa,
            .arena_state = arena_allocator.state,
            .zig_lib_directory = options.zig_lib_directory,
            .local_cache_directory = options.local_cache_directory,
            .global_cache_directory = options.global_cache_directory,
            .bin_file = bin_file,
            .whole_bin_sub_path = whole_bin_sub_path,
            .whole_implib_sub_path = whole_implib_sub_path,
            .emit_asm = options.emit_asm,
            .emit_llvm_ir = options.emit_llvm_ir,
            .emit_llvm_bc = options.emit_llvm_bc,
            .emit_analysis = options.emit_analysis,
            .emit_docs = options.emit_docs,
            .work_queue = std.fifo.LinearFifo(Job, .Dynamic).init(gpa),
            .anon_work_queue = std.fifo.LinearFifo(Job, .Dynamic).init(gpa),
            .c_object_work_queue = std.fifo.LinearFifo(*CObject, .Dynamic).init(gpa),
            .astgen_work_queue = std.fifo.LinearFifo(*Module.File, .Dynamic).init(gpa),
            .embed_file_work_queue = std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic).init(gpa),
            .keep_source_files_loaded = options.keep_source_files_loaded,
            .use_clang = use_clang,
            .clang_argv = options.clang_argv,
            .c_source_files = options.c_source_files,
            .cache_parent = cache,
            .self_exe_path = options.self_exe_path,
            .libc_include_dir_list = libc_dirs.libc_include_dir_list,
            .sanitize_c = sanitize_c,
            .thread_pool = options.thread_pool,
            .clang_passthrough_mode = options.clang_passthrough_mode,
            .clang_preprocessor_mode = options.clang_preprocessor_mode,
            .verbose_cc = options.verbose_cc,
            .verbose_air = options.verbose_air,
            .verbose_llvm_ir = options.verbose_llvm_ir,
            .verbose_cimport = options.verbose_cimport,
            .verbose_llvm_cpu_features = options.verbose_llvm_cpu_features,
            .disable_c_depfile = options.disable_c_depfile,
            .owned_link_dir = owned_link_dir,
            .color = options.color,
            .reference_trace = options.reference_trace,
            .formatted_panics = formatted_panics,
            .time_report = options.time_report,
            .stack_report = options.stack_report,
            .unwind_tables = unwind_tables,
            .test_filter = options.test_filter,
            .test_name_prefix = options.test_name_prefix,
            .test_evented_io = options.test_evented_io,
            .debug_compiler_runtime_libs = options.debug_compiler_runtime_libs,
            .debug_compile_errors = options.debug_compile_errors,
            .libcxx_abi_version = options.libcxx_abi_version,
        };
        break :comp comp;
    };
    errdefer comp.destroy();

    const target = comp.getTarget();

    // Add a `CObject` for each `c_source_files`.
    try comp.c_object_table.ensureTotalCapacity(gpa, options.c_source_files.len);
    for (options.c_source_files) |c_source_file| {
        const c_object = try gpa.create(CObject);
        errdefer gpa.destroy(c_object);

        c_object.* = .{
            .status = .{ .new = {} },
            .src = c_source_file,
        };
        comp.c_object_table.putAssumeCapacityNoClobber(c_object, {});
    }

    const have_bin_emit = comp.bin_file.options.emit != null or comp.whole_bin_sub_path != null;

    if (have_bin_emit and !comp.bin_file.options.skip_linker_dependencies and target.ofmt != .c) {
        if (target.isDarwin()) {
            switch (target.abi) {
                .none,
                .simulator,
                .macabi,
                => {},
                else => return error.LibCUnavailable,
            }
        }
        // If we need to build glibc for the target, add work items for it.
        // We go through the work queue so that building can be done in parallel.
        if (comp.wantBuildGLibCFromSource()) {
            if (!target_util.canBuildLibC(target)) return error.LibCUnavailable;

            if (glibc.needsCrtiCrtn(target)) {
                try comp.work_queue.write(&[_]Job{
                    .{ .glibc_crt_file = .crti_o },
                    .{ .glibc_crt_file = .crtn_o },
                });
            }
            try comp.work_queue.write(&[_]Job{
                .{ .glibc_crt_file = .scrt1_o },
                .{ .glibc_crt_file = .libc_nonshared_a },
                .{ .glibc_shared_objects = {} },
            });
        }
        if (comp.wantBuildMuslFromSource()) {
            if (!target_util.canBuildLibC(target)) return error.LibCUnavailable;

            try comp.work_queue.ensureUnusedCapacity(6);
            if (musl.needsCrtiCrtn(target)) {
                comp.work_queue.writeAssumeCapacity(&[_]Job{
                    .{ .musl_crt_file = .crti_o },
                    .{ .musl_crt_file = .crtn_o },
                });
            }
            comp.work_queue.writeAssumeCapacity(&[_]Job{
                .{ .musl_crt_file = .crt1_o },
                .{ .musl_crt_file = .scrt1_o },
                .{ .musl_crt_file = .rcrt1_o },
                switch (comp.bin_file.options.link_mode) {
                    .Static => .{ .musl_crt_file = .libc_a },
                    .Dynamic => .{ .musl_crt_file = .libc_so },
                },
            });
        }
        if (comp.wantBuildWasiLibcFromSource()) {
            if (!target_util.canBuildLibC(target)) return error.LibCUnavailable;

            const wasi_emulated_libs = comp.bin_file.options.wasi_emulated_libs;
            try comp.work_queue.ensureUnusedCapacity(wasi_emulated_libs.len + 2); // worst-case we need all components
            for (wasi_emulated_libs) |crt_file| {
                comp.work_queue.writeItemAssumeCapacity(.{
                    .wasi_libc_crt_file = crt_file,
                });
            }
            comp.work_queue.writeAssumeCapacity(&[_]Job{
                .{ .wasi_libc_crt_file = wasi_libc.execModelCrtFile(wasi_exec_model) },
                .{ .wasi_libc_crt_file = .libc_a },
            });
        }
        if (comp.wantBuildMinGWFromSource()) {
            if (!target_util.canBuildLibC(target)) return error.LibCUnavailable;

            const static_lib_jobs = [_]Job{
                .{ .mingw_crt_file = .mingw32_lib },
                .{ .mingw_crt_file = .msvcrt_os_lib },
                .{ .mingw_crt_file = .mingwex_lib },
                .{ .mingw_crt_file = .uuid_lib },
            };
            const crt_job: Job = .{ .mingw_crt_file = if (is_dyn_lib) .dllcrt2_o else .crt2_o };
            try comp.work_queue.ensureUnusedCapacity(static_lib_jobs.len + 1);
            comp.work_queue.writeAssumeCapacity(&static_lib_jobs);
            comp.work_queue.writeItemAssumeCapacity(crt_job);

            // When linking mingw-w64 there are some import libs we always need.
            for (mingw.always_link_libs) |name| {
                try comp.bin_file.options.system_libs.put(comp.gpa, name, .{});
            }
        }
        // Generate Windows import libs.
        if (target.os.tag == .windows) {
            const count = comp.bin_file.options.system_libs.count();
            try comp.work_queue.ensureUnusedCapacity(count);
            var i: usize = 0;
            while (i < count) : (i += 1) {
                comp.work_queue.writeItemAssumeCapacity(.{ .windows_import_lib = i });
            }
        }
        if (comp.wantBuildLibUnwindFromSource()) {
            try comp.work_queue.writeItem(.{ .libunwind = {} });
        }
        if (build_options.have_llvm and is_exe_or_dyn_lib and comp.bin_file.options.link_libcpp) {
            try comp.work_queue.writeItem(.libcxx);
            try comp.work_queue.writeItem(.libcxxabi);
        }
        if (build_options.have_llvm and comp.bin_file.options.tsan) {
            try comp.work_queue.writeItem(.libtsan);
        }

        if (comp.getTarget().isMinGW() and !comp.bin_file.options.single_threaded) {
            // LLD might drop some symbols as unused during LTO and GCing, therefore,
            // we force mark them for resolution here.

            var tls_index_sym = switch (comp.getTarget().cpu.arch) {
                .x86 => "__tls_index",
                else => "_tls_index",
            };

            try comp.bin_file.options.force_undefined_symbols.put(comp.gpa, tls_index_sym, {});
        }

        if (comp.bin_file.options.include_compiler_rt and capable_of_building_compiler_rt) {
            if (is_exe_or_dyn_lib) {
                log.debug("queuing a job to build compiler_rt_lib", .{});
                comp.job_queued_compiler_rt_lib = true;
            } else if (options.output_mode != .Obj) {
                log.debug("queuing a job to build compiler_rt_obj", .{});
                // If build-obj with -fcompiler-rt is requested, that is handled specially
                // elsewhere. In this case we are making a static library, so we ask
                // for a compiler-rt object to put in it.
                comp.job_queued_compiler_rt_obj = true;
            }
        }
        if (needs_c_symbols) {
            // Related: https://github.com/ziglang/zig/issues/7265.
            if (comp.bin_file.options.stack_protector != 0 and
                (!comp.bin_file.options.link_libc or
                !target_util.libcProvidesStackProtector(target)))
            {
                try comp.work_queue.writeItem(.{ .libssp = {} });
            }

            if (!comp.bin_file.options.link_libc and capable_of_building_zig_libc) {
                try comp.work_queue.writeItem(.{ .zig_libc = {} });
            }
        }
    }

    return comp;
}

pub fn destroy(self: *Compilation) void {
    const optional_module = self.bin_file.options.module;
    self.bin_file.destroy();
    if (optional_module) |module| module.deinit();

    const gpa = self.gpa;
    self.work_queue.deinit();
    self.anon_work_queue.deinit();
    self.c_object_work_queue.deinit();
    self.astgen_work_queue.deinit();
    self.embed_file_work_queue.deinit();

    {
        var it = self.crt_files.iterator();
        while (it.next()) |entry| {
            gpa.free(entry.key_ptr.*);
            entry.value_ptr.deinit(gpa);
        }
        self.crt_files.deinit(gpa);
    }

    if (self.libunwind_static_lib) |*crt_file| {
        crt_file.deinit(gpa);
    }
    if (self.libcxx_static_lib) |*crt_file| {
        crt_file.deinit(gpa);
    }
    if (self.libcxxabi_static_lib) |*crt_file| {
        crt_file.deinit(gpa);
    }
    if (self.compiler_rt_lib) |*crt_file| {
        crt_file.deinit(gpa);
    }
    if (self.compiler_rt_obj) |*crt_file| {
        crt_file.deinit(gpa);
    }
    if (self.libssp_static_lib) |*crt_file| {
        crt_file.deinit(gpa);
    }
    if (self.libc_static_lib) |*crt_file| {
        crt_file.deinit(gpa);
    }

    if (self.glibc_so_files) |*glibc_file| {
        glibc_file.deinit(gpa);
    }

    for (self.c_object_table.keys()) |key| {
        key.destroy(gpa);
    }
    self.c_object_table.deinit(gpa);

    for (self.failed_c_objects.values()) |value| {
        value.destroy(gpa);
    }
    self.failed_c_objects.deinit(gpa);

    for (self.lld_errors.items) |*lld_error| {
        lld_error.deinit(gpa);
    }
    self.lld_errors.deinit(gpa);

    self.clearMiscFailures();

    self.cache_parent.manifest_dir.close();
    if (self.owned_link_dir) |*dir| dir.close();

    // This destroys `self`.
    self.arena_state.promote(gpa).deinit();
}

pub fn clearMiscFailures(comp: *Compilation) void {
    comp.alloc_failure_occurred = false;
    for (comp.misc_failures.values()) |*value| {
        value.deinit(comp.gpa);
    }
    comp.misc_failures.deinit(comp.gpa);
    comp.misc_failures = .{};
}

pub fn getTarget(self: Compilation) Target {
    return self.bin_file.options.target;
}

fn restorePrevZigCacheArtifactDirectory(comp: *Compilation, directory: *Directory) void {
    if (directory.path) |p| comp.gpa.free(p);

    // Restore the Module's previous zig_cache_artifact_directory
    // This is only for cleanup purposes; Module.deinit calls close
    // on the handle of zig_cache_artifact_directory.
    if (comp.bin_file.options.module) |module| {
        const builtin_pkg = module.main_pkg.table.get("builtin").?;
        module.zig_cache_artifact_directory = builtin_pkg.root_src_directory;
    }
}

fn cleanupTmpArtifactDirectory(
    comp: *Compilation,
    tmp_artifact_directory: *?Directory,
    tmp_dir_sub_path: []const u8,
) void {
    comp.gpa.free(tmp_dir_sub_path);
    if (tmp_artifact_directory.*) |*directory| {
        directory.handle.close();
        restorePrevZigCacheArtifactDirectory(comp, directory);
    }
}

/// Detect changes to source files, perform semantic analysis, and update the output files.
pub fn update(comp: *Compilation) !void {
    const tracy_trace = trace(@src());
    defer tracy_trace.end();

    comp.clearMiscFailures();

    var man: Cache.Manifest = undefined;
    defer if (comp.whole_cache_manifest != null) man.deinit();

    var tmp_dir_sub_path: []const u8 = &.{};
    var tmp_artifact_directory: ?Directory = null;
    defer cleanupTmpArtifactDirectory(comp, &tmp_artifact_directory, tmp_dir_sub_path);

    // If using the whole caching strategy, we check for *everything* up front, including
    // C source files.
    if (comp.bin_file.options.cache_mode == .whole) {
        // We are about to obtain this lock, so here we give other processes a chance first.
        comp.bin_file.releaseLock();

        man = comp.cache_parent.obtain();
        comp.whole_cache_manifest = &man;
        try comp.addNonIncrementalStuffToCacheManifest(&man);

        const is_hit = man.hit() catch |err| {
            // TODO properly bubble these up instead of emitting a warning
            const i = man.failed_file_index orelse return err;
            const pp = man.files.items[i].prefixed_path orelse return err;
            const prefix = man.cache.prefixes()[pp.prefix].path orelse "";
            std.log.warn("{s}: {s}{s}", .{ @errorName(err), prefix, pp.sub_path });
            return err;
        };
        if (is_hit) {
            log.debug("CacheMode.whole cache hit for {s}", .{comp.bin_file.options.root_name});
            const digest = man.final();

            comp.wholeCacheModeSetBinFilePath(&digest);

            assert(comp.bin_file.lock == null);
            comp.bin_file.lock = man.toOwnedLock();
            return;
        }
        log.debug("CacheMode.whole cache miss for {s}", .{comp.bin_file.options.root_name});

        // Initialize `bin_file.emit` with a temporary Directory so that compilation can
        // continue on the same path as incremental, using the temporary Directory.
        tmp_artifact_directory = d: {
            const s = std.fs.path.sep_str;
            const rand_int = std.crypto.random.int(u64);

            tmp_dir_sub_path = try std.fmt.allocPrint(comp.gpa, "tmp" ++ s ++ "{x}", .{rand_int});

            const path = try comp.local_cache_directory.join(comp.gpa, &.{tmp_dir_sub_path});
            errdefer comp.gpa.free(path);

            const handle = try comp.local_cache_directory.handle.makeOpenPath(tmp_dir_sub_path, .{});
            errdefer handle.close();

            break :d .{
                .path = path,
                .handle = handle,
            };
        };

        // This updates the output directory for stage1 backend and linker outputs.
        if (comp.bin_file.options.module) |module| {
            module.zig_cache_artifact_directory = tmp_artifact_directory.?;
        }

        // This resets the link.File to operate as if we called openPath() in create()
        // instead of simulating -fno-emit-bin.
        var options = comp.bin_file.options.move();
        if (comp.whole_bin_sub_path) |sub_path| {
            options.emit = .{
                .directory = tmp_artifact_directory.?,
                .sub_path = std.fs.path.basename(sub_path),
            };
        }
        if (comp.whole_implib_sub_path) |sub_path| {
            options.implib_emit = .{
                .directory = tmp_artifact_directory.?,
                .sub_path = std.fs.path.basename(sub_path),
            };
        }
        comp.bin_file.destroy();
        comp.bin_file = try link.File.openPath(comp.gpa, options);
    }

    // For compiling C objects, we rely on the cache hash system to avoid duplicating work.
    // Add a Job for each C object.
    try comp.c_object_work_queue.ensureUnusedCapacity(comp.c_object_table.count());
    for (comp.c_object_table.keys()) |key| {
        comp.c_object_work_queue.writeItemAssumeCapacity(key);
    }

    if (comp.bin_file.options.module) |module| {
        module.compile_log_text.shrinkAndFree(module.gpa, 0);
        module.generation += 1;

        // Make sure std.zig is inside the import_table. We unconditionally need
        // it for start.zig.
        const std_pkg = module.main_pkg.table.get("std").?;
        _ = try module.importPkg(std_pkg);

        // Normally we rely on importing std to in turn import the root source file
        // in the start code, but when using the stage1 backend that won't happen,
        // so in order to run AstGen on the root source file we put it into the
        // import_table here.
        // Likewise, in the case of `zig test`, the test runner is the root source file,
        // and so there is nothing to import the main file.
        if (comp.bin_file.options.is_test) {
            _ = try module.importPkg(module.main_pkg);
        }

        if (module.main_pkg.table.get("compiler_rt")) |compiler_rt_pkg| {
            _ = try module.importPkg(compiler_rt_pkg);
        }

        // Put a work item in for every known source file to detect if
        // it changed, and, if so, re-compute ZIR and then queue the job
        // to update it.
        // We still want AstGen work items for stage1 so that we expose compile errors
        // that are implemented in stage2 but not stage1.
        try comp.astgen_work_queue.ensureUnusedCapacity(module.import_table.count());
        for (module.import_table.values()) |value| {
            comp.astgen_work_queue.writeItemAssumeCapacity(value);
        }

        // Put a work item in for checking if any files used with `@embedFile` changed.
        {
            try comp.embed_file_work_queue.ensureUnusedCapacity(module.embed_table.count());
            var it = module.embed_table.iterator();
            while (it.next()) |entry| {
                const embed_file = entry.value_ptr.*;
                comp.embed_file_work_queue.writeItemAssumeCapacity(embed_file);
            }
        }

        try comp.work_queue.writeItem(.{ .analyze_pkg = std_pkg });
        if (comp.bin_file.options.is_test) {
            try comp.work_queue.writeItem(.{ .analyze_pkg = module.main_pkg });
        }

        if (module.main_pkg.table.get("compiler_rt")) |compiler_rt_pkg| {
            try comp.work_queue.writeItem(.{ .analyze_pkg = compiler_rt_pkg });
        }
    }

    // If the terminal is dumb, we dont want to show the user all the output.
    var progress: std.Progress = .{ .dont_print_on_dumb = true };
    const main_progress_node = progress.start("", 0);
    defer main_progress_node.end();
    switch (comp.color) {
        .off => {
            progress.terminal = null;
        },
        .on => {
            progress.terminal = std.io.getStdErr();
            progress.supports_ansi_escape_codes = true;
        },
        .auto => {},
    }

    try comp.performAllTheWork(main_progress_node);

    if (comp.bin_file.options.module) |module| {
        if (comp.bin_file.options.is_test and comp.totalErrorCount() == 0) {
            // The `test_functions` decl has been intentionally postponed until now,
            // at which point we must populate it with the list of test functions that
            // have been discovered and not filtered out.
            try module.populateTestFunctions(main_progress_node);
        }

        // Process the deletion set. We use a while loop here because the
        // deletion set may grow as we call `clearDecl` within this loop,
        // and more unreferenced Decls are revealed.
        while (module.deletion_set.count() != 0) {
            const decl_index = module.deletion_set.keys()[0];
            const decl = module.declPtr(decl_index);
            assert(decl.deletion_flag);
            assert(decl.dependants.count() == 0);
            const is_anon = if (decl.zir_decl_index == 0) blk: {
                break :blk decl.src_namespace.anon_decls.swapRemove(decl_index);
            } else false;

            try module.clearDecl(decl_index, null);

            if (is_anon) {
                module.destroyDecl(decl_index);
            }
        }

        try module.processExports();
    }

    if (comp.totalErrorCount() != 0) {
        // Skip flushing and keep source files loaded for error reporting.
        comp.link_error_flags = .{};
        return;
    }

    if (!build_options.only_c) {
        if (comp.emit_docs) |doc_location| {
            if (comp.bin_file.options.module) |module| {
                var autodoc = Autodoc.init(module, doc_location);
                defer autodoc.deinit();
                try autodoc.generateZirData();
            }
        }
    }

    // Flush takes care of -femit-bin, but we still have -femit-llvm-ir, -femit-llvm-bc, and
    // -femit-asm to handle, in the case of C objects.
    comp.emitOthers();

    if (comp.whole_cache_manifest != null) {
        const digest = man.final();

        // Rename the temporary directory into place.
        var directory = tmp_artifact_directory.?;
        tmp_artifact_directory = null;

        directory.handle.close();
        defer restorePrevZigCacheArtifactDirectory(comp, &directory);

        const o_sub_path = try std.fs.path.join(comp.gpa, &[_][]const u8{ "o", &digest });
        defer comp.gpa.free(o_sub_path);

        // Work around windows `AccessDenied` if any files within this directory are open
        // by doing the makeExecutable/makeWritable dance.
        const need_writable_dance = builtin.os.tag == .windows and comp.bin_file.file != null;
        if (need_writable_dance) {
            try comp.bin_file.makeExecutable();
        }

        try comp.bin_file.renameTmpIntoCache(comp.local_cache_directory, tmp_dir_sub_path, o_sub_path);
        comp.wholeCacheModeSetBinFilePath(&digest);

        // Has to be after the `wholeCacheModeSetBinFilePath` above.
        if (need_writable_dance) {
            try comp.bin_file.makeWritable();
        }

        // This is intentionally sandwiched between renameTmpIntoCache() and writeManifest().
        if (comp.bin_file.options.module) |module| {
            // We need to set the zig_cache_artifact_directory for -femit-asm, -femit-llvm-ir,
            // etc to know where to output to.
            var artifact_dir = try comp.local_cache_directory.handle.openDir(o_sub_path, .{});
            defer artifact_dir.close();

            var dir_path = try comp.local_cache_directory.join(comp.gpa, &.{o_sub_path});
            defer comp.gpa.free(dir_path);

            module.zig_cache_artifact_directory = .{
                .handle = artifact_dir,
                .path = dir_path,
            };

            try comp.flush(main_progress_node);
        } else {
            try comp.flush(main_progress_node);
        }

        if (comp.totalErrorCount() != 0) {
            return;
        }

        // Failure here only means an unnecessary cache miss.
        man.writeManifest() catch |err| {
            log.warn("failed to write cache manifest: {s}", .{@errorName(err)});
        };

        assert(comp.bin_file.lock == null);
        comp.bin_file.lock = man.toOwnedLock();
    } else {
        try comp.flush(main_progress_node);
    }

    // Unload all source files to save memory.
    // The ZIR needs to stay loaded in memory because (1) Decl objects contain references
    // to it, and (2) generic instantiations, comptime calls, inline calls will need
    // to reference the ZIR.
    if (!comp.keep_source_files_loaded) {
        if (comp.bin_file.options.module) |module| {
            for (module.import_table.values()) |file| {
                file.unloadTree(comp.gpa);
                file.unloadSource(comp.gpa);
            }
        }
    }
}

fn flush(comp: *Compilation, prog_node: *std.Progress.Node) !void {
    // This is needed before reading the error flags.
    comp.bin_file.flush(comp, prog_node) catch |err| switch (err) {
        error.FlushFailure => {}, // error reported through link_error_flags
        error.LLDReportedFailure => {}, // error reported via lockAndParseLldStderr
        else => |e| return e,
    };
    comp.link_error_flags = comp.bin_file.errorFlags();

    if (comp.bin_file.options.module) |module| {
        try link.File.C.flushEmitH(module);
    }
}

/// Communicate the output binary location to parent Compilations.
fn wholeCacheModeSetBinFilePath(comp: *Compilation, digest: *const [Cache.hex_digest_len]u8) void {
    const digest_start = 2; // "o/[digest]/[basename]"

    if (comp.whole_bin_sub_path) |sub_path| {
        mem.copy(u8, sub_path[digest_start..], digest);

        comp.bin_file.options.emit = .{
            .directory = comp.local_cache_directory,
            .sub_path = sub_path,
        };
    }

    if (comp.whole_implib_sub_path) |sub_path| {
        mem.copy(u8, sub_path[digest_start..], digest);

        comp.bin_file.options.implib_emit = .{
            .directory = comp.local_cache_directory,
            .sub_path = sub_path,
        };
    }
}

fn prepareWholeEmitSubPath(arena: Allocator, opt_emit: ?EmitLoc) error{OutOfMemory}!?[]u8 {
    const emit = opt_emit orelse return null;
    if (emit.directory != null) return null;
    const s = std.fs.path.sep_str;
    const format = "o" ++ s ++ ("x" ** Cache.hex_digest_len) ++ s ++ "{s}";
    return try std.fmt.allocPrint(arena, format, .{emit.basename});
}

/// This is only observed at compile-time and used to emit a compile error
/// to remind the programmer to update multiple related pieces of code that
/// are in different locations. Bump this number when adding or deleting
/// anything from the link cache manifest.
pub const link_hash_implementation_version = 7;

fn addNonIncrementalStuffToCacheManifest(comp: *Compilation, man: *Cache.Manifest) !void {
    const gpa = comp.gpa;
    const target = comp.getTarget();

    var arena_allocator = std.heap.ArenaAllocator.init(gpa);
    defer arena_allocator.deinit();
    const arena = arena_allocator.allocator();

    comptime assert(link_hash_implementation_version == 7);

    if (comp.bin_file.options.module) |mod| {
        const main_zig_file = try mod.main_pkg.root_src_directory.join(arena, &[_][]const u8{
            mod.main_pkg.root_src_path,
        });
        _ = try man.addFile(main_zig_file, null);
        {
            var seen_table = std.AutoHashMap(*Package, void).init(arena);

            // Skip builtin.zig; it is useless as an input, and we don't want to have to
            // write it before checking for a cache hit.
            const builtin_pkg = mod.main_pkg.table.get("builtin").?;
            try seen_table.put(builtin_pkg, {});

            try addPackageTableToCacheHash(&man.hash, &arena_allocator, mod.main_pkg.table, &seen_table, .{ .files = man });
        }

        // Synchronize with other matching comments: ZigOnlyHashStuff
        man.hash.add(comp.bin_file.options.valgrind);
        man.hash.add(comp.bin_file.options.single_threaded);
        man.hash.add(comp.bin_file.options.use_llvm);
        man.hash.add(comp.bin_file.options.dll_export_fns);
        man.hash.add(comp.bin_file.options.is_test);
        man.hash.add(comp.test_evented_io);
        man.hash.addOptionalBytes(comp.test_filter);
        man.hash.addOptionalBytes(comp.test_name_prefix);
        man.hash.add(comp.bin_file.options.skip_linker_dependencies);
        man.hash.add(comp.bin_file.options.parent_compilation_link_libc);
        man.hash.add(mod.emit_h != null);
    }

    try man.addOptionalFile(comp.bin_file.options.linker_script);
    try man.addOptionalFile(comp.bin_file.options.version_script);

    for (comp.bin_file.options.objects) |obj| {
        _ = try man.addFile(obj.path, null);
        man.hash.add(obj.must_link);
    }

    for (comp.c_object_table.keys()) |key| {
        _ = try man.addFile(key.src.src_path, null);
        man.hash.addOptional(key.src.ext);
        man.hash.addListOfBytes(key.src.extra_flags);
    }

    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_asm);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_llvm_ir);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_llvm_bc);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_analysis);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_docs);

    man.hash.addListOfBytes(comp.clang_argv);

    man.hash.addOptional(comp.bin_file.options.stack_size_override);
    man.hash.addOptional(comp.bin_file.options.image_base_override);
    man.hash.addOptional(comp.bin_file.options.gc_sections);
    man.hash.add(comp.bin_file.options.eh_frame_hdr);
    man.hash.add(comp.bin_file.options.emit_relocs);
    man.hash.add(comp.bin_file.options.rdynamic);
    man.hash.addListOfBytes(comp.bin_file.options.lib_dirs);
    man.hash.addListOfBytes(comp.bin_file.options.rpath_list);
    man.hash.add(comp.bin_file.options.each_lib_rpath);
    man.hash.add(comp.bin_file.options.build_id);
    man.hash.add(comp.bin_file.options.skip_linker_dependencies);
    man.hash.add(comp.bin_file.options.z_nodelete);
    man.hash.add(comp.bin_file.options.z_notext);
    man.hash.add(comp.bin_file.options.z_defs);
    man.hash.add(comp.bin_file.options.z_origin);
    man.hash.add(comp.bin_file.options.z_nocopyreloc);
    man.hash.add(comp.bin_file.options.z_now);
    man.hash.add(comp.bin_file.options.z_relro);
    man.hash.add(comp.bin_file.options.z_common_page_size orelse 0);
    man.hash.add(comp.bin_file.options.z_max_page_size orelse 0);
    man.hash.add(comp.bin_file.options.hash_style);
    man.hash.add(comp.bin_file.options.compress_debug_sections);
    man.hash.add(comp.bin_file.options.include_compiler_rt);
    man.hash.addOptional(comp.bin_file.options.sort_section);
    if (comp.bin_file.options.link_libc) {
        man.hash.add(comp.bin_file.options.libc_installation != null);
        if (comp.bin_file.options.libc_installation) |libc_installation| {
            man.hash.addBytes(libc_installation.crt_dir.?);
            if (target.abi == .msvc) {
                man.hash.addBytes(libc_installation.msvc_lib_dir.?);
                man.hash.addBytes(libc_installation.kernel32_lib_dir.?);
            }
        }
        man.hash.addOptionalBytes(comp.bin_file.options.dynamic_linker);
    }
    man.hash.addOptionalBytes(comp.bin_file.options.soname);
    man.hash.addOptional(comp.bin_file.options.version);
    link.hashAddSystemLibs(&man.hash, comp.bin_file.options.system_libs);
    man.hash.addListOfBytes(comp.bin_file.options.force_undefined_symbols.keys());
    man.hash.addOptional(comp.bin_file.options.allow_shlib_undefined);
    man.hash.add(comp.bin_file.options.bind_global_refs_locally);
    man.hash.add(comp.bin_file.options.tsan);
    man.hash.addOptionalBytes(comp.bin_file.options.sysroot);
    man.hash.add(comp.bin_file.options.linker_optimization);

    // WASM specific stuff
    man.hash.add(comp.bin_file.options.import_memory);
    man.hash.addOptional(comp.bin_file.options.initial_memory);
    man.hash.addOptional(comp.bin_file.options.max_memory);
    man.hash.add(comp.bin_file.options.shared_memory);
    man.hash.addOptional(comp.bin_file.options.global_base);

    // Mach-O specific stuff
    man.hash.addListOfBytes(comp.bin_file.options.framework_dirs);
    link.hashAddSystemLibs(&man.hash, comp.bin_file.options.frameworks);
    try man.addOptionalFile(comp.bin_file.options.entitlements);
    man.hash.addOptional(comp.bin_file.options.pagezero_size);
    man.hash.addOptional(comp.bin_file.options.search_strategy);
    man.hash.addOptional(comp.bin_file.options.headerpad_size);
    man.hash.add(comp.bin_file.options.headerpad_max_install_names);
    man.hash.add(comp.bin_file.options.dead_strip_dylibs);

    // COFF specific stuff
    man.hash.addOptional(comp.bin_file.options.subsystem);
    man.hash.add(comp.bin_file.options.tsaware);
    man.hash.add(comp.bin_file.options.nxcompat);
    man.hash.add(comp.bin_file.options.dynamicbase);
    man.hash.addOptional(comp.bin_file.options.major_subsystem_version);
    man.hash.addOptional(comp.bin_file.options.minor_subsystem_version);
}

fn emitOthers(comp: *Compilation) void {
    if (comp.bin_file.options.output_mode != .Obj or comp.bin_file.options.module != null or
        comp.c_object_table.count() == 0)
    {
        return;
    }
    const obj_path = comp.c_object_table.keys()[0].status.success.object_path;
    const cwd = std.fs.cwd();
    const ext = std.fs.path.extension(obj_path);
    const basename = obj_path[0 .. obj_path.len - ext.len];
    // This obj path always ends with the object file extension, but if we change the
    // extension to .ll, .bc, or .s, then it will be the path to those things.
    const outs = [_]struct {
        emit: ?EmitLoc,
        ext: []const u8,
    }{
        .{ .emit = comp.emit_asm, .ext = ".s" },
        .{ .emit = comp.emit_llvm_ir, .ext = ".ll" },
        .{ .emit = comp.emit_llvm_bc, .ext = ".bc" },
    };
    for (outs) |out| {
        if (out.emit) |loc| {
            if (loc.directory) |directory| {
                const src_path = std.fmt.allocPrint(comp.gpa, "{s}{s}", .{
                    basename, out.ext,
                }) catch |err| {
                    log.err("unable to copy {s}{s}: {s}", .{ basename, out.ext, @errorName(err) });
                    continue;
                };
                defer comp.gpa.free(src_path);
                cwd.copyFile(src_path, directory.handle, loc.basename, .{}) catch |err| {
                    log.err("unable to copy {s}: {s}", .{ src_path, @errorName(err) });
                };
            }
        }
    }
}

fn reportMultiModuleErrors(mod: *Module) !void {
    // Some cases can give you a whole bunch of multi-module errors, which it's not helpful to
    // print all of, so we'll cap the number of these to emit.
    var num_errors: u32 = 0;
    const max_errors = 5;
    // Attach the "some omitted" note to the final error message
    var last_err: ?*Module.ErrorMsg = null;

    for (mod.import_table.values()) |file| {
        if (!file.multi_pkg) continue;

        num_errors += 1;
        if (num_errors > max_errors) continue;

        const err = err_blk: {
            // Like with errors, let's cap the number of notes to prevent a huge error spew.
            const max_notes = 5;
            const omitted = file.references.items.len -| max_notes;
            const num_notes = file.references.items.len - omitted;

            const notes = try mod.gpa.alloc(Module.ErrorMsg, if (omitted > 0) num_notes + 1 else num_notes);
            errdefer mod.gpa.free(notes);

            for (notes[0..num_notes], file.references.items[0..num_notes], 0..) |*note, ref, i| {
                errdefer for (notes[0..i]) |*n| n.deinit(mod.gpa);
                note.* = switch (ref) {
                    .import => |loc| blk: {
                        const name = try loc.file_scope.pkg.getName(mod.gpa, mod.*);
                        defer mod.gpa.free(name);
                        break :blk try Module.ErrorMsg.init(
                            mod.gpa,
                            loc,
                            "imported from module {s}",
                            .{name},
                        );
                    },
                    .root => |pkg| blk: {
                        const name = try pkg.getName(mod.gpa, mod.*);
                        defer mod.gpa.free(name);
                        break :blk try Module.ErrorMsg.init(
                            mod.gpa,
                            .{ .file_scope = file, .parent_decl_node = 0, .lazy = .entire_file },
                            "root of module {s}",
                            .{name},
                        );
                    },
                };
            }
            errdefer for (notes[0..num_notes]) |*n| n.deinit(mod.gpa);

            if (omitted > 0) {
                notes[num_notes] = try Module.ErrorMsg.init(
                    mod.gpa,
                    .{ .file_scope = file, .parent_decl_node = 0, .lazy = .entire_file },
                    "{} more references omitted",
                    .{omitted},
                );
            }
            errdefer if (omitted > 0) notes[num_notes].deinit(mod.gpa);

            const err = try Module.ErrorMsg.create(
                mod.gpa,
                .{ .file_scope = file, .parent_decl_node = 0, .lazy = .entire_file },
                "file exists in multiple modules",
                .{},
            );
            err.notes = notes;
            break :err_blk err;
        };
        errdefer err.destroy(mod.gpa);
        try mod.failed_files.putNoClobber(mod.gpa, file, err);
        last_err = err;
    }

    // If we omitted any errors, add a note saying that
    if (num_errors > max_errors) {
        const err = last_err.?;

        // There isn't really any meaningful place to put this note, so just attach it to the
        // last failed file
        var note = try Module.ErrorMsg.init(
            mod.gpa,
            err.src_loc,
            "{} more errors omitted",
            .{num_errors - max_errors},
        );
        errdefer note.deinit(mod.gpa);

        const i = err.notes.len;
        err.notes = try mod.gpa.realloc(err.notes, i + 1);
        err.notes[i] = note;
    }

    // Now that we've reported the errors, we need to deal with
    // dependencies. Any file referenced by a multi_pkg file should also be
    // marked multi_pkg and have its status set to astgen_failure, as it's
    // ambiguous which package they should be analyzed as a part of. We need
    // to add this flag after reporting the errors however, as otherwise
    // we'd get an error for every single downstream file, which wouldn't be
    // very useful.
    for (mod.import_table.values()) |file| {
        if (file.multi_pkg) file.recursiveMarkMultiPkg(mod);
    }
}

/// Having the file open for writing is problematic as far as executing the
/// binary is concerned. This will remove the write flag, or close the file,
/// or whatever is needed so that it can be executed.
/// After this, one must call` makeFileWritable` before calling `update`.
pub fn makeBinFileExecutable(self: *Compilation) !void {
    return self.bin_file.makeExecutable();
}

pub fn makeBinFileWritable(self: *Compilation) !void {
    return self.bin_file.makeWritable();
}

/// This function is temporally single-threaded.
pub fn totalErrorCount(self: *Compilation) usize {
    var total: usize = self.failed_c_objects.count() + self.misc_failures.count() +
        @boolToInt(self.alloc_failure_occurred) + self.lld_errors.items.len;

    if (self.bin_file.options.module) |module| {
        total += module.failed_exports.count();
        total += module.failed_embed_files.count();

        {
            var it = module.failed_files.iterator();
            while (it.next()) |entry| {
                if (entry.value_ptr.*) |_| {
                    total += 1;
                } else {
                    const file = entry.key_ptr.*;
                    assert(file.zir_loaded);
                    const payload_index = file.zir.extra[@enumToInt(Zir.ExtraIndex.compile_errors)];
                    assert(payload_index != 0);
                    const header = file.zir.extraData(Zir.Inst.CompileErrors, payload_index);
                    total += header.data.items_len;
                }
            }
        }

        // Skip errors for Decls within files that failed parsing.
        // When a parse error is introduced, we keep all the semantic analysis for
        // the previous parse success, including compile errors, but we cannot
        // emit them until the file succeeds parsing.
        for (module.failed_decls.keys()) |key| {
            const decl = module.declPtr(key);
            if (decl.getFileScope().okToReportErrors()) {
                total += 1;
                if (module.cimport_errors.get(key)) |errors| {
                    total += errors.len;
                }
            }
        }
        if (module.emit_h) |emit_h| {
            for (emit_h.failed_decls.keys()) |key| {
                const decl = module.declPtr(key);
                if (decl.getFileScope().okToReportErrors()) {
                    total += 1;
                }
            }
        }
    }

    // The "no entry point found" error only counts if there are no semantic analysis errors.
    if (total == 0) {
        total += @boolToInt(self.link_error_flags.no_entry_point_found);
    }
    total += @boolToInt(self.link_error_flags.missing_libc);

    // Compile log errors only count if there are no other errors.
    if (total == 0) {
        if (self.bin_file.options.module) |module| {
            total += @boolToInt(module.compile_log_decls.count() != 0);
        }
    }

    return total;
}

/// This function is temporally single-threaded.
pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
    var arena = std.heap.ArenaAllocator.init(self.gpa);
    errdefer arena.deinit();
    const arena_allocator = arena.allocator();

    var errors = std.ArrayList(AllErrors.Message).init(self.gpa);
    defer errors.deinit();

    {
        var it = self.failed_c_objects.iterator();
        while (it.next()) |entry| {
            const c_object = entry.key_ptr.*;
            const err_msg = entry.value_ptr.*;
            // TODO these fields will need to be adjusted when we have proper
            // C error reporting bubbling up.
            try errors.append(.{
                .src = .{
                    .src_path = try arena_allocator.dupe(u8, c_object.src.src_path),
                    .msg = try std.fmt.allocPrint(arena_allocator, "unable to build C object: {s}", .{
                        err_msg.msg,
                    }),
                    .span = .{ .start = 0, .end = 1, .main = 0 },
                    .line = err_msg.line,
                    .column = err_msg.column,
                    .source_line = null, // TODO
                },
            });
        }
    }
    for (self.lld_errors.items) |lld_error| {
        const notes = try arena_allocator.alloc(AllErrors.Message, lld_error.context_lines.len);
        for (lld_error.context_lines, 0..) |context_line, i| {
            notes[i] = .{ .plain = .{
                .msg = try arena_allocator.dupe(u8, context_line),
            } };
        }

        try errors.append(.{
            .plain = .{
                .msg = try arena_allocator.dupe(u8, lld_error.msg),
                .notes = notes,
            },
        });
    }
    for (self.misc_failures.values()) |*value| {
        try AllErrors.addPlainWithChildren(&arena, &errors, value.msg, value.children);
    }
    if (self.alloc_failure_occurred) {
        try AllErrors.addPlain(&arena, &errors, "memory allocation failure");
    }
    if (self.bin_file.options.module) |module| {
        {
            var it = module.failed_files.iterator();
            while (it.next()) |entry| {
                if (entry.value_ptr.*) |msg| {
                    try AllErrors.add(module, &arena, &errors, msg.*);
                } else {
                    // Must be ZIR errors. In order for ZIR errors to exist, the parsing
                    // must have completed successfully.
                    const tree = try entry.key_ptr.*.getTree(module.gpa);
                    assert(tree.errors.len == 0);
                    try AllErrors.addZir(arena_allocator, &errors, entry.key_ptr.*);
                }
            }
        }
        {
            var it = module.failed_embed_files.iterator();
            while (it.next()) |entry| {
                const msg = entry.value_ptr.*;
                try AllErrors.add(module, &arena, &errors, msg.*);
            }
        }
        {
            var it = module.failed_decls.iterator();
            while (it.next()) |entry| {
                const decl = module.declPtr(entry.key_ptr.*);
                // Skip errors for Decls within files that had a parse failure.
                // We'll try again once parsing succeeds.
                if (decl.getFileScope().okToReportErrors()) {
                    try AllErrors.add(module, &arena, &errors, entry.value_ptr.*.*);
                    if (module.cimport_errors.get(entry.key_ptr.*)) |cimport_errors| for (cimport_errors) |c_error| {
                        if (c_error.path) |some|
                            try errors.append(.{
                                .src = .{
                                    .src_path = try arena_allocator.dupe(u8, std.mem.span(some)),
                                    .span = .{ .start = c_error.offset, .end = c_error.offset + 1, .main = c_error.offset },
                                    .msg = try arena_allocator.dupe(u8, std.mem.span(c_error.msg)),
                                    .line = c_error.line,
                                    .column = c_error.column,
                                    .source_line = if (c_error.source_line) |line| try arena_allocator.dupe(u8, std.mem.span(line)) else null,
                                },
                            })
                        else
                            try errors.append(.{
                                .plain = .{ .msg = try arena_allocator.dupe(u8, std.mem.span(c_error.msg)) },
                            });
                    };
                }
            }
        }
        if (module.emit_h) |emit_h| {
            var it = emit_h.failed_decls.iterator();
            while (it.next()) |entry| {
                const decl = module.declPtr(entry.key_ptr.*);
                // Skip errors for Decls within files that had a parse failure.
                // We'll try again once parsing succeeds.
                if (decl.getFileScope().okToReportErrors()) {
                    try AllErrors.add(module, &arena, &errors, entry.value_ptr.*.*);
                }
            }
        }
        for (module.failed_exports.values()) |value| {
            try AllErrors.add(module, &arena, &errors, value.*);
        }
    }

    if (errors.items.len == 0) {
        if (self.link_error_flags.no_entry_point_found) {
            try errors.append(.{
                .plain = .{
                    .msg = try std.fmt.allocPrint(arena_allocator, "no entry point found", .{}),
                },
            });
        }
    }

    if (self.link_error_flags.missing_libc) {
        const notes = try arena_allocator.create([2]AllErrors.Message);
        notes.* = .{
            .{ .plain = .{
                .msg = try arena_allocator.dupe(u8, "run 'zig libc -h' to learn about libc installations"),
            } },
            .{ .plain = .{
                .msg = try arena_allocator.dupe(u8, "run 'zig targets' to see the targets for which zig can always provide libc"),
            } },
        };
        try errors.append(.{
            .plain = .{
                .msg = try std.fmt.allocPrint(arena_allocator, "libc not available", .{}),
                .notes = notes,
            },
        });
    }

    if (self.bin_file.options.module) |module| {
        if (errors.items.len == 0 and module.compile_log_decls.count() != 0) {
            const keys = module.compile_log_decls.keys();
            const values = module.compile_log_decls.values();
            // First one will be the error; subsequent ones will be notes.
            const err_decl = module.declPtr(keys[0]);
            const src_loc = err_decl.nodeOffsetSrcLoc(values[0]);
            const err_msg = Module.ErrorMsg{
                .src_loc = src_loc,
                .msg = "found compile log statement",
                .notes = try self.gpa.alloc(Module.ErrorMsg, module.compile_log_decls.count() - 1),
            };
            defer self.gpa.free(err_msg.notes);

            for (keys[1..], 0..) |key, i| {
                const note_decl = module.declPtr(key);
                err_msg.notes[i] = .{
                    .src_loc = note_decl.nodeOffsetSrcLoc(values[i + 1]),
                    .msg = "also here",
                };
            }

            try AllErrors.add(module, &arena, &errors, err_msg);
        }
    }

    assert(errors.items.len == self.totalErrorCount());

    return AllErrors{
        .list = try arena_allocator.dupe(AllErrors.Message, errors.items),
        .arena = arena.state,
    };
}

pub fn getCompileLogOutput(self: *Compilation) []const u8 {
    const module = self.bin_file.options.module orelse return &[0]u8{};
    return module.compile_log_text.items;
}

pub fn performAllTheWork(
    comp: *Compilation,
    main_progress_node: *std.Progress.Node,
) error{ TimerUnsupported, OutOfMemory }!void {
    // Here we queue up all the AstGen tasks first, followed by C object compilation.
    // We wait until the AstGen tasks are all completed before proceeding to the
    // (at least for now) single-threaded main work queue. However, C object compilation
    // only needs to be finished by the end of this function.

    var zir_prog_node = main_progress_node.start("AST Lowering", 0);
    defer zir_prog_node.end();

    var c_obj_prog_node = main_progress_node.start("Compile C Objects", comp.c_source_files.len);
    defer c_obj_prog_node.end();

    var embed_file_prog_node = main_progress_node.start("Detect @embedFile updates", comp.embed_file_work_queue.count);
    defer embed_file_prog_node.end();

    comp.work_queue_wait_group.reset();
    defer comp.work_queue_wait_group.wait();

    {
        const astgen_frame = tracy.namedFrame("astgen");
        defer astgen_frame.end();

        comp.astgen_wait_group.reset();
        defer comp.astgen_wait_group.wait();

        // builtin.zig is handled specially for two reasons:
        // 1. to avoid race condition of zig processes truncating each other's builtin.zig files
        // 2. optimization; in the hot path it only incurs a stat() syscall, which happens
        //    in the `astgen_wait_group`.
        if (comp.bin_file.options.module) |mod| {
            if (mod.job_queued_update_builtin_zig) {
                mod.job_queued_update_builtin_zig = false;

                comp.astgen_wait_group.start();
                try comp.thread_pool.spawn(workerUpdateBuiltinZigFile, .{
                    comp, mod, &comp.astgen_wait_group,
                });
            }
        }

        while (comp.astgen_work_queue.readItem()) |file| {
            comp.astgen_wait_group.start();
            try comp.thread_pool.spawn(workerAstGenFile, .{
                comp, file, &zir_prog_node, &comp.astgen_wait_group, .root,
            });
        }

        while (comp.embed_file_work_queue.readItem()) |embed_file| {
            comp.astgen_wait_group.start();
            try comp.thread_pool.spawn(workerCheckEmbedFile, .{
                comp, embed_file, &embed_file_prog_node, &comp.astgen_wait_group,
            });
        }

        while (comp.c_object_work_queue.readItem()) |c_object| {
            comp.work_queue_wait_group.start();
            try comp.thread_pool.spawn(workerUpdateCObject, .{
                comp, c_object, &c_obj_prog_node, &comp.work_queue_wait_group,
            });
        }
    }

    if (comp.bin_file.options.module) |mod| {
        try reportMultiModuleErrors(mod);
    }

    {
        const outdated_and_deleted_decls_frame = tracy.namedFrame("outdated_and_deleted_decls");
        defer outdated_and_deleted_decls_frame.end();

        // Iterate over all the files and look for outdated and deleted declarations.
        if (comp.bin_file.options.module) |mod| {
            try mod.processOutdatedAndDeletedDecls();
        }
    }

    if (comp.bin_file.options.module) |mod| {
        mod.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
        mod.sema_prog_node.activate();
    }
    defer if (comp.bin_file.options.module) |mod| {
        mod.sema_prog_node.end();
        mod.sema_prog_node = undefined;
    };

    // In this main loop we give priority to non-anonymous Decls in the work queue, so
    // that they can establish references to anonymous Decls, setting alive=true in the
    // backend, preventing anonymous Decls from being prematurely destroyed.
    while (true) {
        if (comp.work_queue.readItem()) |work_item| {
            try processOneJob(comp, work_item);
            continue;
        }
        if (comp.anon_work_queue.readItem()) |work_item| {
            try processOneJob(comp, work_item);
            continue;
        }
        break;
    }

    if (comp.job_queued_compiler_rt_lib) {
        comp.job_queued_compiler_rt_lib = false;
        buildCompilerRtOneShot(comp, .Lib, &comp.compiler_rt_lib);
    }

    if (comp.job_queued_compiler_rt_obj) {
        comp.job_queued_compiler_rt_obj = false;
        buildCompilerRtOneShot(comp, .Obj, &comp.compiler_rt_obj);
    }
}

fn processOneJob(comp: *Compilation, job: Job) !void {
    switch (job) {
        .codegen_decl => |decl_index| {
            const module = comp.bin_file.options.module.?;
            const decl = module.declPtr(decl_index);

            switch (decl.analysis) {
                .unreferenced => unreachable,
                .in_progress => unreachable,
                .outdated => unreachable,

                .file_failure,
                .sema_failure,
                .codegen_failure,
                .dependency_failure,
                .sema_failure_retryable,
                => return,

                .complete, .codegen_failure_retryable => {
                    const named_frame = tracy.namedFrame("codegen_decl");
                    defer named_frame.end();

                    assert(decl.has_tv);

                    if (decl.alive) {
                        try module.linkerUpdateDecl(decl_index);
                        return;
                    }

                    // Instead of sending this decl to the linker, we actually will delete it
                    // because we found out that it in fact was never referenced.
                    module.deleteUnusedDecl(decl_index);
                    return;
                },
            }
        },
        .codegen_func => |func| {
            const named_frame = tracy.namedFrame("codegen_func");
            defer named_frame.end();

            const module = comp.bin_file.options.module.?;
            module.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
                error.OutOfMemory => return error.OutOfMemory,
                error.AnalysisFail => return,
            };
        },
        .emit_h_decl => |decl_index| {
            const module = comp.bin_file.options.module.?;
            const decl = module.declPtr(decl_index);

            switch (decl.analysis) {
                .unreferenced => unreachable,
                .in_progress => unreachable,
                .outdated => unreachable,

                .file_failure,
                .sema_failure,
                .dependency_failure,
                .sema_failure_retryable,
                => return,

                // emit-h only requires semantic analysis of the Decl to be complete,
                // it does not depend on machine code generation to succeed.
                .codegen_failure, .codegen_failure_retryable, .complete => {
                    const named_frame = tracy.namedFrame("emit_h_decl");
                    defer named_frame.end();

                    const gpa = comp.gpa;
                    const emit_h = module.emit_h.?;
                    _ = try emit_h.decl_table.getOrPut(gpa, decl_index);
                    const decl_emit_h = emit_h.declPtr(decl_index);
                    const fwd_decl = &decl_emit_h.fwd_decl;
                    fwd_decl.shrinkRetainingCapacity(0);
                    var ctypes_arena = std.heap.ArenaAllocator.init(gpa);
                    defer ctypes_arena.deinit();

                    var dg: c_codegen.DeclGen = .{
                        .gpa = gpa,
                        .module = module,
                        .error_msg = null,
                        .decl_index = decl_index.toOptional(),
                        .decl = decl,
                        .fwd_decl = fwd_decl.toManaged(gpa),
                        .ctypes = .{},
                    };
                    defer {
                        dg.ctypes.deinit(gpa);
                        dg.fwd_decl.deinit();
                    }

                    c_codegen.genHeader(&dg) catch |err| switch (err) {
                        error.AnalysisFail => {
                            try emit_h.failed_decls.put(gpa, decl_index, dg.error_msg.?);
                            return;
                        },
                        else => |e| return e,
                    };

                    fwd_decl.* = dg.fwd_decl.moveToUnmanaged();
                    fwd_decl.shrinkAndFree(gpa, fwd_decl.items.len);
                },
            }
        },
        .analyze_decl => |decl_index| {
            const module = comp.bin_file.options.module.?;
            module.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
                error.OutOfMemory => return error.OutOfMemory,
                error.AnalysisFail => return,
            };
        },
        .update_embed_file => |embed_file| {
            const named_frame = tracy.namedFrame("update_embed_file");
            defer named_frame.end();

            const module = comp.bin_file.options.module.?;
            module.updateEmbedFile(embed_file) catch |err| switch (err) {
                error.OutOfMemory => return error.OutOfMemory,
                error.AnalysisFail => return,
            };
        },
        .update_line_number => |decl_index| {
            const named_frame = tracy.namedFrame("update_line_number");
            defer named_frame.end();

            const gpa = comp.gpa;
            const module = comp.bin_file.options.module.?;
            const decl = module.declPtr(decl_index);
            comp.bin_file.updateDeclLineNumber(module, decl_index) catch |err| {
                try module.failed_decls.ensureUnusedCapacity(gpa, 1);
                module.failed_decls.putAssumeCapacityNoClobber(decl_index, try Module.ErrorMsg.create(
                    gpa,
                    decl.srcLoc(),
                    "unable to update line number: {s}",
                    .{@errorName(err)},
                ));
                decl.analysis = .codegen_failure_retryable;
            };
        },
        .analyze_pkg => |pkg| {
            const named_frame = tracy.namedFrame("analyze_pkg");
            defer named_frame.end();

            const module = comp.bin_file.options.module.?;
            module.semaPkg(pkg) catch |err| switch (err) {
                error.OutOfMemory => return error.OutOfMemory,
                error.AnalysisFail => return,
            };
        },
        .glibc_crt_file => |crt_file| {
            const named_frame = tracy.namedFrame("glibc_crt_file");
            defer named_frame.end();

            glibc.buildCRTFile(comp, crt_file) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(.glibc_crt_file, "unable to build glibc CRT file: {s}", .{
                    @errorName(err),
                });
            };
        },
        .glibc_shared_objects => {
            const named_frame = tracy.namedFrame("glibc_shared_objects");
            defer named_frame.end();

            glibc.buildSharedObjects(comp) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .glibc_shared_objects,
                    "unable to build glibc shared objects: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .musl_crt_file => |crt_file| {
            const named_frame = tracy.namedFrame("musl_crt_file");
            defer named_frame.end();

            musl.buildCRTFile(comp, crt_file) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .musl_crt_file,
                    "unable to build musl CRT file: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .mingw_crt_file => |crt_file| {
            const named_frame = tracy.namedFrame("mingw_crt_file");
            defer named_frame.end();

            mingw.buildCRTFile(comp, crt_file) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .mingw_crt_file,
                    "unable to build mingw-w64 CRT file {s}: {s}",
                    .{ @tagName(crt_file), @errorName(err) },
                );
            };
        },
        .windows_import_lib => |index| {
            const named_frame = tracy.namedFrame("windows_import_lib");
            defer named_frame.end();

            const link_lib = comp.bin_file.options.system_libs.keys()[index];
            mingw.buildImportLib(comp, link_lib) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .windows_import_lib,
                    "unable to generate DLL import .lib file for {s}: {s}",
                    .{ link_lib, @errorName(err) },
                );
            };
        },
        .libunwind => {
            const named_frame = tracy.namedFrame("libunwind");
            defer named_frame.end();

            libunwind.buildStaticLib(comp) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .libunwind,
                    "unable to build libunwind: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .libcxx => {
            const named_frame = tracy.namedFrame("libcxx");
            defer named_frame.end();

            libcxx.buildLibCXX(comp) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .libcxx,
                    "unable to build libcxx: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .libcxxabi => {
            const named_frame = tracy.namedFrame("libcxxabi");
            defer named_frame.end();

            libcxx.buildLibCXXABI(comp) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .libcxxabi,
                    "unable to build libcxxabi: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .libtsan => {
            const named_frame = tracy.namedFrame("libtsan");
            defer named_frame.end();

            libtsan.buildTsan(comp) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .libtsan,
                    "unable to build TSAN library: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .wasi_libc_crt_file => |crt_file| {
            const named_frame = tracy.namedFrame("wasi_libc_crt_file");
            defer named_frame.end();

            wasi_libc.buildCRTFile(comp, crt_file) catch |err| {
                // TODO Surface more error details.
                comp.lockAndSetMiscFailure(
                    .wasi_libc_crt_file,
                    "unable to build WASI libc CRT file: {s}",
                    .{@errorName(err)},
                );
            };
        },
        .libssp => {
            const named_frame = tracy.namedFrame("libssp");
            defer named_frame.end();

            comp.buildOutputFromZig(
                "ssp.zig",
                .Lib,
                &comp.libssp_static_lib,
                .libssp,
            ) catch |err| switch (err) {
                error.OutOfMemory => return error.OutOfMemory,
                error.SubCompilationFailed => return, // error reported already
                else => comp.lockAndSetMiscFailure(
                    .libssp,
                    "unable to build libssp: {s}",
                    .{@errorName(err)},
                ),
            };
        },
        .zig_libc => {
            const named_frame = tracy.namedFrame("zig_libc");
            defer named_frame.end();

            comp.buildOutputFromZig(
                "c.zig",
                .Lib,
                &comp.libc_static_lib,
                .zig_libc,
            ) catch |err| switch (err) {
                error.OutOfMemory => return error.OutOfMemory,
                error.SubCompilationFailed => return, // error reported already
                else => comp.lockAndSetMiscFailure(
                    .zig_libc,
                    "unable to build zig's multitarget libc: {s}",
                    .{@errorName(err)},
                ),
            };
        },
    }
}

const AstGenSrc = union(enum) {
    root,
    import: struct {
        importing_file: *Module.File,
        import_tok: std.zig.Ast.TokenIndex,
    },
};

fn workerAstGenFile(
    comp: *Compilation,
    file: *Module.File,
    prog_node: *std.Progress.Node,
    wg: *WaitGroup,
    src: AstGenSrc,
) void {
    defer wg.finish();

    var child_prog_node = prog_node.start(file.sub_file_path, 0);
    child_prog_node.activate();
    defer child_prog_node.end();

    const mod = comp.bin_file.options.module.?;
    mod.astGenFile(file) catch |err| switch (err) {
        error.AnalysisFail => return,
        else => {
            file.status = .retryable_failure;
            comp.reportRetryableAstGenError(src, file, err) catch |oom| switch (oom) {
                // Swallowing this error is OK because it's implied to be OOM when
                // there is a missing `failed_files` error message.
                error.OutOfMemory => {},
            };
            return;
        },
    };

    // Pre-emptively look for `@import` paths and queue them up.
    // If we experience an error preemptively fetching the
    // file, just ignore it and let it happen again later during Sema.
    assert(file.zir_loaded);
    const imports_index = file.zir.extra[@enumToInt(Zir.ExtraIndex.imports)];
    if (imports_index != 0) {
        const extra = file.zir.extraData(Zir.Inst.Imports, imports_index);
        var import_i: u32 = 0;
        var extra_index = extra.end;

        while (import_i < extra.data.imports_len) : (import_i += 1) {
            const item = file.zir.extraData(Zir.Inst.Imports.Item, extra_index);
            extra_index = item.end;

            const import_path = file.zir.nullTerminatedString(item.data.name);
            // `@import("builtin")` is handled specially.
            if (mem.eql(u8, import_path, "builtin")) continue;

            const import_result = blk: {
                comp.mutex.lock();
                defer comp.mutex.unlock();

                const res = mod.importFile(file, import_path) catch continue;
                if (!res.is_pkg) {
                    res.file.addReference(mod.*, .{ .import = .{
                        .file_scope = file,
                        .parent_decl_node = 0,
                        .lazy = .{ .token_abs = item.data.token },
                    } }) catch continue;
                }
                break :blk res;
            };
            if (import_result.is_new) {
                log.debug("AstGen of {s} has import '{s}'; queuing AstGen of {s}", .{
                    file.sub_file_path, import_path, import_result.file.sub_file_path,
                });
                const sub_src: AstGenSrc = .{ .import = .{
                    .importing_file = file,
                    .import_tok = item.data.token,
                } };
                wg.start();
                comp.thread_pool.spawn(workerAstGenFile, .{
                    comp, import_result.file, prog_node, wg, sub_src,
                }) catch {
                    wg.finish();
                    continue;
                };
            }
        }
    }
}

fn workerUpdateBuiltinZigFile(
    comp: *Compilation,
    mod: *Module,
    wg: *WaitGroup,
) void {
    defer wg.finish();

    mod.populateBuiltinFile() catch |err| {
        const dir_path: []const u8 = mod.zig_cache_artifact_directory.path orelse ".";

        comp.mutex.lock();
        defer comp.mutex.unlock();

        comp.setMiscFailure(.write_builtin_zig, "unable to write builtin.zig to {s}: {s}", .{
            dir_path, @errorName(err),
        });
    };
}

fn workerCheckEmbedFile(
    comp: *Compilation,
    embed_file: *Module.EmbedFile,
    prog_node: *std.Progress.Node,
    wg: *WaitGroup,
) void {
    defer wg.finish();

    var child_prog_node = prog_node.start(embed_file.sub_file_path, 0);
    child_prog_node.activate();
    defer child_prog_node.end();

    const mod = comp.bin_file.options.module.?;
    mod.detectEmbedFileUpdate(embed_file) catch |err| {
        comp.reportRetryableEmbedFileError(embed_file, err) catch |oom| switch (oom) {
            // Swallowing this error is OK because it's implied to be OOM when
            // there is a missing `failed_embed_files` error message.
            error.OutOfMemory => {},
        };
        return;
    };
}

pub fn obtainCObjectCacheManifest(comp: *const Compilation) Cache.Manifest {
    var man = comp.cache_parent.obtain();

    // Only things that need to be added on top of the base hash, and only things
    // that apply both to @cImport and compiling C objects. No linking stuff here!
    // Also nothing that applies only to compiling .zig code.
    man.hash.add(comp.sanitize_c);
    man.hash.addListOfBytes(comp.clang_argv);
    man.hash.add(comp.bin_file.options.link_libcpp);

    // When libc_installation is null it means that Zig generated this dir list
    // based on the zig library directory alone. The zig lib directory file
    // path is purposefully either in the cache or not in the cache. The
    // decision should not be overridden here.
    if (comp.bin_file.options.libc_installation != null) {
        man.hash.addListOfBytes(comp.libc_include_dir_list);
    }

    return man;
}

test "cImport" {
    _ = cImport;
}

const CImportResult = struct {
    out_zig_path: []u8,
    errors: []clang.ErrorMsg,
};

/// Caller owns returned memory.
/// This API is currently coupled pretty tightly to stage1's needs; it will need to be reworked
/// a bit when we want to start using it from self-hosted.
pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult {
    if (!build_options.have_llvm)
        return error.ZigCompilerNotBuiltWithLLVMExtensions;

    const tracy_trace = trace(@src());
    defer tracy_trace.end();

    const cimport_zig_basename = "cimport.zig";

    var man = comp.obtainCObjectCacheManifest();
    defer man.deinit();

    man.hash.add(@as(u16, 0xb945)); // Random number to distinguish translate-c from compiling C objects
    man.hash.addBytes(c_src);

    // If the previous invocation resulted in clang errors, we will see a hit
    // here with 0 files in the manifest, in which case it is actually a miss.
    // We need to "unhit" in this case, to keep the digests matching.
    const prev_hash_state = man.hash.peekBin();
    const actual_hit = hit: {
        _ = try man.hit();
        if (man.files.items.len == 0) {
            man.unhit(prev_hash_state, 0);
            break :hit false;
        }
        break :hit true;
    };
    const digest = if (!actual_hit) digest: {
        var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
        defer arena_allocator.deinit();
        const arena = arena_allocator.allocator();

        const tmp_digest = man.hash.peek();
        const tmp_dir_sub_path = try std.fs.path.join(arena, &[_][]const u8{ "o", &tmp_digest });
        var zig_cache_tmp_dir = try comp.local_cache_directory.handle.makeOpenPath(tmp_dir_sub_path, .{});
        defer zig_cache_tmp_dir.close();
        const cimport_basename = "cimport.h";
        const out_h_path = try comp.local_cache_directory.join(arena, &[_][]const u8{
            tmp_dir_sub_path, cimport_basename,
        });
        const out_dep_path = try std.fmt.allocPrint(arena, "{s}.d", .{out_h_path});

        try zig_cache_tmp_dir.writeFile(cimport_basename, c_src);
        if (comp.verbose_cimport) {
            log.info("C import source: {s}", .{out_h_path});
        }

        var argv = std.ArrayList([]const u8).init(comp.gpa);
        defer argv.deinit();

        try argv.append(""); // argv[0] is program name, actual args start at [1]
        try comp.addTranslateCCArgs(arena, &argv, .c, out_dep_path);

        try argv.append(out_h_path);

        if (comp.verbose_cc) {
            dump_argv(argv.items);
        }

        // Convert to null terminated args.
        const new_argv_with_sentinel = try arena.alloc(?[*:0]const u8, argv.items.len + 1);
        new_argv_with_sentinel[argv.items.len] = null;
        const new_argv = new_argv_with_sentinel[0..argv.items.len :null];
        for (argv.items, 0..) |arg, i| {
            new_argv[i] = try arena.dupeZ(u8, arg);
        }

        const c_headers_dir_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{"include"});
        const c_headers_dir_path_z = try arena.dupeZ(u8, c_headers_dir_path);
        var clang_errors: []clang.ErrorMsg = &[0]clang.ErrorMsg{};
        var tree = translate_c.translate(
            comp.gpa,
            new_argv.ptr,
            new_argv.ptr + new_argv.len,
            &clang_errors,
            c_headers_dir_path_z,
        ) catch |err| switch (err) {
            error.OutOfMemory => return error.OutOfMemory,
            error.ASTUnitFailure => {
                log.warn("clang API returned errors but due to a clang bug, it is not exposing the errors for zig to see. For more details: https://github.com/ziglang/zig/issues/4455", .{});
                return error.ASTUnitFailure;
            },
            error.SemanticAnalyzeFail => {
                return CImportResult{
                    .out_zig_path = "",
                    .errors = clang_errors,
                };
            },
        };
        defer tree.deinit(comp.gpa);

        if (comp.verbose_cimport) {
            log.info("C import .d file: {s}", .{out_dep_path});
        }

        const dep_basename = std.fs.path.basename(out_dep_path);
        try man.addDepFilePost(zig_cache_tmp_dir, dep_basename);
        if (comp.whole_cache_manifest) |whole_cache_manifest| {
            comp.whole_cache_manifest_mutex.lock();
            defer comp.whole_cache_manifest_mutex.unlock();
            try whole_cache_manifest.addDepFilePost(zig_cache_tmp_dir, dep_basename);
        }

        const digest = man.final();
        const o_sub_path = try std.fs.path.join(arena, &[_][]const u8{ "o", &digest });
        var o_dir = try comp.local_cache_directory.handle.makeOpenPath(o_sub_path, .{});
        defer o_dir.close();

        var out_zig_file = try o_dir.createFile(cimport_zig_basename, .{});
        defer out_zig_file.close();

        const formatted = try tree.render(comp.gpa);
        defer comp.gpa.free(formatted);

        try out_zig_file.writeAll(formatted);

        break :digest digest;
    } else man.final();

    if (man.have_exclusive_lock) {
        // Write the updated manifest. This is a no-op if the manifest is not dirty. Note that it is
        // possible we had a hit and the manifest is dirty, for example if the file mtime changed but
        // the contents were the same, we hit the cache but the manifest is dirty and we need to update
        // it to prevent doing a full file content comparison the next time around.
        man.writeManifest() catch |err| {
            log.warn("failed to write cache manifest for C import: {s}", .{@errorName(err)});
        };
    }

    const out_zig_path = try comp.local_cache_directory.join(comp.gpa, &[_][]const u8{
        "o", &digest, cimport_zig_basename,
    });
    if (comp.verbose_cimport) {
        log.info("C import output: {s}", .{out_zig_path});
    }
    return CImportResult{
        .out_zig_path = out_zig_path,
        .errors = &[0]clang.ErrorMsg{},
    };
}

fn workerUpdateCObject(
    comp: *Compilation,
    c_object: *CObject,
    progress_node: *std.Progress.Node,
    wg: *WaitGroup,
) void {
    defer wg.finish();

    comp.updateCObject(c_object, progress_node) catch |err| switch (err) {
        error.AnalysisFail => return,
        else => {
            comp.reportRetryableCObjectError(c_object, err) catch |oom| switch (oom) {
                // Swallowing this error is OK because it's implied to be OOM when
                // there is a missing failed_c_objects error message.
                error.OutOfMemory => {},
            };
        },
    };
}

fn buildCompilerRtOneShot(
    comp: *Compilation,
    output_mode: std.builtin.OutputMode,
    out: *?CRTFile,
) void {
    comp.buildOutputFromZig("compiler_rt.zig", output_mode, out, .compiler_rt) catch |err| switch (err) {
        error.SubCompilationFailed => return, // error reported already
        else => comp.lockAndSetMiscFailure(
            .compiler_rt,
            "unable to build compiler_rt: {s}",
            .{@errorName(err)},
        ),
    };
}

fn reportRetryableCObjectError(
    comp: *Compilation,
    c_object: *CObject,
    err: anyerror,
) error{OutOfMemory}!void {
    c_object.status = .failure_retryable;

    const c_obj_err_msg = try comp.gpa.create(CObject.ErrorMsg);
    errdefer comp.gpa.destroy(c_obj_err_msg);
    const msg = try std.fmt.allocPrint(comp.gpa, "{s}", .{@errorName(err)});
    errdefer comp.gpa.free(msg);
    c_obj_err_msg.* = .{
        .msg = msg,
        .line = 0,
        .column = 0,
    };
    {
        comp.mutex.lock();
        defer comp.mutex.unlock();
        try comp.failed_c_objects.putNoClobber(comp.gpa, c_object, c_obj_err_msg);
    }
}

fn reportRetryableAstGenError(
    comp: *Compilation,
    src: AstGenSrc,
    file: *Module.File,
    err: anyerror,
) error{OutOfMemory}!void {
    const mod = comp.bin_file.options.module.?;
    const gpa = mod.gpa;

    file.status = .retryable_failure;

    const src_loc: Module.SrcLoc = switch (src) {
        .root => .{
            .file_scope = file,
            .parent_decl_node = 0,
            .lazy = .entire_file,
        },
        .import => |info| blk: {
            const importing_file = info.importing_file;

            break :blk .{
                .file_scope = importing_file,
                .parent_decl_node = 0,
                .lazy = .{ .token_abs = info.import_tok },
            };
        },
    };

    const err_msg = if (file.pkg.root_src_directory.path) |dir_path|
        try Module.ErrorMsg.create(
            gpa,
            src_loc,
            "unable to load '{s}" ++ std.fs.path.sep_str ++ "{s}': {s}",
            .{ dir_path, file.sub_file_path, @errorName(err) },
        )
    else
        try Module.ErrorMsg.create(gpa, src_loc, "unable to load '{s}': {s}", .{
            file.sub_file_path, @errorName(err),
        });
    errdefer err_msg.destroy(gpa);

    {
        comp.mutex.lock();
        defer comp.mutex.unlock();
        try mod.failed_files.putNoClobber(gpa, file, err_msg);
    }
}

fn reportRetryableEmbedFileError(
    comp: *Compilation,
    embed_file: *Module.EmbedFile,
    err: anyerror,
) error{OutOfMemory}!void {
    const mod = comp.bin_file.options.module.?;
    const gpa = mod.gpa;

    const src_loc: Module.SrcLoc = mod.declPtr(embed_file.owner_decl).srcLoc();

    const err_msg = if (embed_file.pkg.root_src_directory.path) |dir_path|
        try Module.ErrorMsg.create(
            gpa,
            src_loc,
            "unable to load '{s}" ++ std.fs.path.sep_str ++ "{s}': {s}",
            .{ dir_path, embed_file.sub_file_path, @errorName(err) },
        )
    else
        try Module.ErrorMsg.create(gpa, src_loc, "unable to load '{s}': {s}", .{
            embed_file.sub_file_path, @errorName(err),
        });
    errdefer err_msg.destroy(gpa);

    {
        comp.mutex.lock();
        defer comp.mutex.unlock();
        try mod.failed_embed_files.putNoClobber(gpa, embed_file, err_msg);
    }
}

fn updateCObject(comp: *Compilation, c_object: *CObject, c_obj_prog_node: *std.Progress.Node) !void {
    if (!build_options.have_llvm) {
        return comp.failCObj(c_object, "clang not available: compiler built without LLVM extensions", .{});
    }
    const self_exe_path = comp.self_exe_path orelse
        return comp.failCObj(c_object, "clang compilation disabled", .{});

    const tracy_trace = trace(@src());
    defer tracy_trace.end();

    log.debug("updating C object: {s}", .{c_object.src.src_path});

    if (c_object.clearStatus(comp.gpa)) {
        // There was previous failure.
        comp.mutex.lock();
        defer comp.mutex.unlock();
        // If the failure was OOM, there will not be an entry here, so we do
        // not assert discard.
        _ = comp.failed_c_objects.swapRemove(c_object);
    }

    var man = comp.obtainCObjectCacheManifest();
    defer man.deinit();

    man.hash.add(comp.clang_preprocessor_mode);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_asm);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_llvm_ir);
    cache_helpers.addOptionalEmitLoc(&man.hash, comp.emit_llvm_bc);

    try cache_helpers.hashCSource(&man, c_object.src);

    var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
    defer arena_allocator.deinit();
    const arena = arena_allocator.allocator();

    const c_source_basename = std.fs.path.basename(c_object.src.src_path);

    c_obj_prog_node.activate();
    var child_progress_node = c_obj_prog_node.start(c_source_basename, 0);
    child_progress_node.activate();
    defer child_progress_node.end();

    // Special case when doing build-obj for just one C file. When there are more than one object
    // file and building an object we need to link them together, but with just one it should go
    // directly to the output file.
    const direct_o = comp.c_source_files.len == 1 and comp.bin_file.options.module == null and
        comp.bin_file.options.output_mode == .Obj and comp.bin_file.options.objects.len == 0;
    const o_basename_noext = if (direct_o)
        comp.bin_file.options.root_name
    else
        c_source_basename[0 .. c_source_basename.len - std.fs.path.extension(c_source_basename).len];

    const target = comp.getTarget();
    const o_ext = target.ofmt.fileExt(target.cpu.arch);
    const digest = if (!comp.disable_c_depfile and try man.hit()) man.final() else blk: {
        var argv = std.ArrayList([]const u8).init(comp.gpa);
        defer argv.deinit();

        // In case we are doing passthrough mode, we need to detect -S and -emit-llvm.
        const out_ext = e: {
            if (!comp.clang_passthrough_mode)
                break :e o_ext;
            if (comp.emit_asm != null)
                break :e ".s";
            if (comp.emit_llvm_ir != null)
                break :e ".ll";
            if (comp.emit_llvm_bc != null)
                break :e ".bc";

            break :e o_ext;
        };
        const o_basename = try std.fmt.allocPrint(arena, "{s}{s}", .{ o_basename_noext, out_ext });
        const ext = c_object.src.ext orelse classifyFileExt(c_object.src.src_path);

        try argv.appendSlice(&[_][]const u8{ self_exe_path, "clang" });
        // if "ext" is explicit, add "-x <lang>". Otherwise let clang do its thing.
        if (c_object.src.ext != null) {
            try argv.appendSlice(&[_][]const u8{ "-x", switch (ext) {
                .assembly => "assembler",
                .assembly_with_cpp => "assembler-with-cpp",
                .c => "c",
                .cpp => "c++",
                .cu => "cuda",
                .m => "objective-c",
                .mm => "objective-c++",
                else => fatal("language '{s}' is unsupported in this context", .{@tagName(ext)}),
            } });
        }
        try argv.append(c_object.src.src_path);

        // When all these flags are true, it means that the entire purpose of
        // this compilation is to perform a single zig cc operation. This means
        // that we could "tail call" clang by doing an execve, and any use of
        // the caching system would actually be problematic since the user is
        // presumably doing their own caching by using dep file flags.
        if (std.process.can_execv and direct_o and
            comp.disable_c_depfile and comp.clang_passthrough_mode)
        {
            try comp.addCCArgs(arena, &argv, ext, null);
            try argv.appendSlice(c_object.src.extra_flags);
            try argv.appendSlice(c_object.src.cache_exempt_flags);

            const out_obj_path = if (comp.bin_file.options.emit) |emit|
                try emit.directory.join(arena, &.{emit.sub_path})
            else
                "/dev/null";

            try argv.ensureUnusedCapacity(5);
            switch (comp.clang_preprocessor_mode) {
                .no => argv.appendSliceAssumeCapacity(&[_][]const u8{ "-c", "-o", out_obj_path }),
                .yes => argv.appendSliceAssumeCapacity(&[_][]const u8{ "-E", "-o", out_obj_path }),
                .stdout => argv.appendAssumeCapacity("-E"),
            }

            if (comp.emit_asm != null) {
                argv.appendAssumeCapacity("-S");
            } else if (comp.emit_llvm_ir != null) {
                argv.appendSliceAssumeCapacity(&[_][]const u8{ "-emit-llvm", "-S" });
            } else if (comp.emit_llvm_bc != null) {
                argv.appendAssumeCapacity("-emit-llvm");
            }

            if (comp.verbose_cc) {
                dump_argv(argv.items);
            }

            const err = std.process.execv(arena, argv.items);
            fatal("unable to execv clang: {s}", .{@errorName(err)});
        }

        // We can't know the digest until we do the C compiler invocation,
        // so we need a temporary filename.
        const out_obj_path = try comp.tmpFilePath(arena, o_basename);
        var zig_cache_tmp_dir = try comp.local_cache_directory.handle.makeOpenPath("tmp", .{});
        defer zig_cache_tmp_dir.close();

        const out_dep_path: ?[]const u8 = if (comp.disable_c_depfile or !ext.clangSupportsDepFile())
            null
        else
            try std.fmt.allocPrint(arena, "{s}.d", .{out_obj_path});
        try comp.addCCArgs(arena, &argv, ext, out_dep_path);
        try argv.appendSlice(c_object.src.extra_flags);
        try argv.appendSlice(c_object.src.cache_exempt_flags);

        try argv.ensureUnusedCapacity(5);
        switch (comp.clang_preprocessor_mode) {
            .no => argv.appendSliceAssumeCapacity(&[_][]const u8{ "-c", "-o", out_obj_path }),
            .yes => argv.appendSliceAssumeCapacity(&[_][]const u8{ "-E", "-o", out_obj_path }),
            .stdout => argv.appendAssumeCapacity("-E"),
        }
        if (comp.clang_passthrough_mode) {
            if (comp.emit_asm != null) {
                argv.appendAssumeCapacity("-S");
            } else if (comp.emit_llvm_ir != null) {
                argv.appendSliceAssumeCapacity(&[_][]const u8{ "-emit-llvm", "-S" });
            } else if (comp.emit_llvm_bc != null) {
                argv.appendAssumeCapacity("-emit-llvm");
            }
        }

        if (comp.verbose_cc) {
            dump_argv(argv.items);
        }

        if (std.process.can_spawn) {
            var child = std.ChildProcess.init(argv.items, arena);
            if (comp.clang_passthrough_mode) {
                child.stdin_behavior = .Inherit;
                child.stdout_behavior = .Inherit;
                child.stderr_behavior = .Inherit;

                const term = child.spawnAndWait() catch |err| {
                    return comp.failCObj(c_object, "unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) });
                };
                switch (term) {
                    .Exited => |code| {
                        if (code != 0) {
                            std.process.exit(code);
                        }
                        if (comp.clang_preprocessor_mode == .stdout)
                            std.process.exit(0);
                    },
                    else => std.process.abort(),
                }
            } else {
                child.stdin_behavior = .Ignore;
                child.stdout_behavior = .Ignore;
                child.stderr_behavior = .Pipe;

                try child.spawn();

                const stderr_reader = child.stderr.?.reader();

                const stderr = try stderr_reader.readAllAlloc(arena, 10 * 1024 * 1024);

                const term = child.wait() catch |err| {
                    return comp.failCObj(c_object, "unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) });
                };

                switch (term) {
                    .Exited => |code| {
                        if (code != 0) {
                            // TODO parse clang stderr and turn it into an error message
                            // and then call failCObjWithOwnedErrorMsg
                            log.err("clang failed with stderr: {s}", .{stderr});
                            return comp.failCObj(c_object, "clang exited with code {d}", .{code});
                        }
                    },
                    else => {
                        log.err("clang terminated with stderr: {s}", .{stderr});
                        return comp.failCObj(c_object, "clang terminated unexpectedly", .{});
                    },
                }
            }
        } else {
            const exit_code = try clangMain(arena, argv.items);
            if (exit_code != 0) {
                if (comp.clang_passthrough_mode) {
                    std.process.exit(exit_code);
                } else {
                    return comp.failCObj(c_object, "clang exited with code {d}", .{exit_code});
                }
            }
            if (comp.clang_passthrough_mode and
                comp.clang_preprocessor_mode == .stdout)
            {
                std.process.exit(0);
            }
        }

        if (out_dep_path) |dep_file_path| {
            const dep_basename = std.fs.path.basename(dep_file_path);
            // Add the files depended on to the cache system.
            try man.addDepFilePost(zig_cache_tmp_dir, dep_basename);
            if (comp.whole_cache_manifest) |whole_cache_manifest| {
                comp.whole_cache_manifest_mutex.lock();
                defer comp.whole_cache_manifest_mutex.unlock();
                try whole_cache_manifest.addDepFilePost(zig_cache_tmp_dir, dep_basename);
            }
            // Just to save disk space, we delete the file because it is never needed again.
            zig_cache_tmp_dir.deleteFile(dep_basename) catch |err| {
                log.warn("failed to delete '{s}': {s}", .{ dep_file_path, @errorName(err) });
            };
        }

        // We don't actually care whether it's a cache hit or miss; we just need the digest and the lock.
        if (comp.disable_c_depfile) _ = try man.hit();

        // Rename into place.
        const digest = man.final();
        const o_sub_path = try std.fs.path.join(arena, &[_][]const u8{ "o", &digest });
        var o_dir = try comp.local_cache_directory.handle.makeOpenPath(o_sub_path, .{});
        defer o_dir.close();
        const tmp_basename = std.fs.path.basename(out_obj_path);
        try std.fs.rename(zig_cache_tmp_dir, tmp_basename, o_dir, o_basename);
        break :blk digest;
    };

    if (man.have_exclusive_lock) {
        // Write the updated manifest. This is a no-op if the manifest is not dirty. Note that it is
        // possible we had a hit and the manifest is dirty, for example if the file mtime changed but
        // the contents were the same, we hit the cache but the manifest is dirty and we need to update
        // it to prevent doing a full file content comparison the next time around.
        man.writeManifest() catch |err| {
            log.warn("failed to write cache manifest when compiling '{s}': {s}", .{ c_object.src.src_path, @errorName(err) });
        };
    }

    const o_basename = try std.fmt.allocPrint(arena, "{s}{s}", .{ o_basename_noext, o_ext });

    c_object.status = .{
        .success = .{
            .object_path = try comp.local_cache_directory.join(comp.gpa, &[_][]const u8{
                "o", &digest, o_basename,
            }),
            .lock = man.toOwnedLock(),
        },
    };
}

pub fn tmpFilePath(comp: *Compilation, ally: Allocator, suffix: []const u8) error{OutOfMemory}![]const u8 {
    const s = std.fs.path.sep_str;
    const rand_int = std.crypto.random.int(u64);
    if (comp.local_cache_directory.path) |p| {
        return std.fmt.allocPrint(ally, "{s}" ++ s ++ "tmp" ++ s ++ "{x}-{s}", .{ p, rand_int, suffix });
    } else {
        return std.fmt.allocPrint(ally, "tmp" ++ s ++ "{x}-{s}", .{ rand_int, suffix });
    }
}

pub fn addTranslateCCArgs(
    comp: *Compilation,
    arena: Allocator,
    argv: *std.ArrayList([]const u8),
    ext: FileExt,
    out_dep_path: ?[]const u8,
) !void {
    try argv.appendSlice(&[_][]const u8{ "-x", "c" });
    try comp.addCCArgs(arena, argv, ext, out_dep_path);
    // This gives us access to preprocessing entities, presumably at the cost of performance.
    try argv.appendSlice(&[_][]const u8{ "-Xclang", "-detailed-preprocessing-record" });
}

/// Add common C compiler args between translate-c and C object compilation.
pub fn addCCArgs(
    comp: *const Compilation,
    arena: Allocator,
    argv: *std.ArrayList([]const u8),
    ext: FileExt,
    out_dep_path: ?[]const u8,
) !void {
    const target = comp.getTarget();

    if (ext == .cpp) {
        try argv.append("-nostdinc++");
    }

    // We don't ever put `-fcolor-diagnostics` or `-fno-color-diagnostics` because in passthrough mode
    // we want Clang to infer it, and in normal mode we always want it off, which will be true since
    // clang will detect stderr as a pipe rather than a terminal.
    if (!comp.clang_passthrough_mode) {
        // Make stderr more easily parseable.
        try argv.append("-fno-caret-diagnostics");
    }

    if (comp.bin_file.options.function_sections) {
        try argv.append("-ffunction-sections");
    }

    if (comp.bin_file.options.no_builtin) {
        try argv.append("-fno-builtin");
    }

    if (comp.bin_file.options.link_libcpp) {
        const libcxx_include_path = try std.fs.path.join(arena, &[_][]const u8{
            comp.zig_lib_directory.path.?, "libcxx", "include",
        });
        const libcxxabi_include_path = try std.fs.path.join(arena, &[_][]const u8{
            comp.zig_lib_directory.path.?, "libcxxabi", "include",
        });

        try argv.append("-isystem");
        try argv.append(libcxx_include_path);

        try argv.append("-isystem");
        try argv.append(libcxxabi_include_path);

        if (target.abi.isMusl()) {
            try argv.append("-D_LIBCPP_HAS_MUSL_LIBC");
        }
        try argv.append("-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS");
        try argv.append("-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS");
        try argv.append("-D_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS");

        if (comp.bin_file.options.single_threaded) {
            try argv.append("-D_LIBCPP_HAS_NO_THREADS");
        }

        try argv.append(try std.fmt.allocPrint(arena, "-D_LIBCPP_ABI_VERSION={d}", .{
            @enumToInt(comp.libcxx_abi_version),
        }));
        try argv.append(try std.fmt.allocPrint(arena, "-D_LIBCPP_ABI_NAMESPACE=__{d}", .{
            @enumToInt(comp.libcxx_abi_version),
        }));
    }

    if (comp.bin_file.options.link_libunwind) {
        const libunwind_include_path = try std.fs.path.join(arena, &[_][]const u8{
            comp.zig_lib_directory.path.?, "libunwind", "include",
        });

        try argv.append("-isystem");
        try argv.append(libunwind_include_path);
    }

    if (comp.bin_file.options.link_libc and target.isGnuLibC()) {
        const target_version = target.os.version_range.linux.glibc;
        const glibc_minor_define = try std.fmt.allocPrint(arena, "-D__GLIBC_MINOR__={d}", .{
            target_version.minor,
        });
        try argv.append(glibc_minor_define);
    }

    const llvm_triple = try @import("codegen/llvm.zig").targetTriple(arena, target);
    try argv.appendSlice(&[_][]const u8{ "-target", llvm_triple });

    switch (ext) {
        .c, .cpp, .m, .mm, .h, .cu => {
            try argv.appendSlice(&[_][]const u8{
                "-nostdinc",
                "-fno-spell-checking",
            });
            if (comp.bin_file.options.lto) {
                try argv.append("-flto");
            }

            if (ext == .mm) {
                try argv.append("-ObjC++");
            }

            // According to Rich Felker libc headers are supposed to go before C language headers.
            // However as noted by @dimenus, appending libc headers before c_headers breaks intrinsics
            // and other compiler specific items.
            const c_headers_dir = try std.fs.path.join(arena, &[_][]const u8{ comp.zig_lib_directory.path.?, "include" });
            try argv.append("-isystem");
            try argv.append(c_headers_dir);

            for (comp.libc_include_dir_list) |include_dir| {
                try argv.append("-isystem");
                try argv.append(include_dir);
            }

            if (target.cpu.model.llvm_name) |llvm_name| {
                try argv.appendSlice(&[_][]const u8{
                    "-Xclang", "-target-cpu", "-Xclang", llvm_name,
                });
            }

            // It would be really nice if there was a more compact way to communicate this info to Clang.
            const all_features_list = target.cpu.arch.allFeaturesList();
            try argv.ensureUnusedCapacity(all_features_list.len * 4);
            for (all_features_list, 0..) |feature, index_usize| {
                const index = @intCast(std.Target.Cpu.Feature.Set.Index, index_usize);
                const is_enabled = target.cpu.features.isEnabled(index);

                if (feature.llvm_name) |llvm_name| {
                    argv.appendSliceAssumeCapacity(&[_][]const u8{ "-Xclang", "-target-feature", "-Xclang" });
                    const plus_or_minus = "-+"[@boolToInt(is_enabled)];
                    const arg = try std.fmt.allocPrint(arena, "{c}{s}", .{ plus_or_minus, llvm_name });
                    argv.appendAssumeCapacity(arg);
                }
            }
            const mcmodel = comp.bin_file.options.machine_code_model;
            if (mcmodel != .default) {
                try argv.append(try std.fmt.allocPrint(arena, "-mcmodel={s}", .{@tagName(mcmodel)}));
            }

            switch (target.os.tag) {
                .windows => {
                    // windows.h has files such as pshpack1.h which do #pragma packing,
                    // triggering a clang warning. So for this target, we disable this warning.
                    if (target.abi.isGnu()) {
                        try argv.append("-Wno-pragma-pack");
                    }
                },
                .macos => {
                    try argv.ensureUnusedCapacity(2);
                    // Pass the proper -m<os>-version-min argument for darwin.
                    const ver = target.os.version_range.semver.min;
                    argv.appendAssumeCapacity(try std.fmt.allocPrint(arena, "-mmacos-version-min={d}.{d}.{d}", .{
                        ver.major, ver.minor, ver.patch,
                    }));
                    // This avoids a warning that sometimes occurs when
                    // providing both a -target argument that contains a
                    // version as well as the -mmacosx-version-min argument.
                    // Zig provides the correct value in both places, so it
                    // doesn't matter which one gets overridden.
                    argv.appendAssumeCapacity("-Wno-overriding-t-option");
                },
                .ios, .tvos, .watchos => switch (target.cpu.arch) {
                    // Pass the proper -m<os>-version-min argument for darwin.
                    .x86, .x86_64 => {
                        const ver = target.os.version_range.semver.min;
                        try argv.append(try std.fmt.allocPrint(
                            arena,
                            "-m{s}-simulator-version-min={d}.{d}.{d}",
                            .{ @tagName(target.os.tag), ver.major, ver.minor, ver.patch },
                        ));
                    },
                    else => {
                        const ver = target.os.version_range.semver.min;
                        try argv.append(try std.fmt.allocPrint(arena, "-m{s}-version-min={d}.{d}.{d}", .{
                            @tagName(target.os.tag), ver.major, ver.minor, ver.patch,
                        }));
                    },
                },
                else => {},
            }

            if (target.cpu.arch.isThumb()) {
                try argv.append("-mthumb");
            }

            if (comp.sanitize_c and !comp.bin_file.options.tsan) {
                try argv.append("-fsanitize=undefined");
                try argv.append("-fsanitize-trap=undefined");
            } else if (comp.sanitize_c and comp.bin_file.options.tsan) {
                try argv.append("-fsanitize=undefined,thread");
                try argv.append("-fsanitize-trap=undefined");
            } else if (!comp.sanitize_c and comp.bin_file.options.tsan) {
                try argv.append("-fsanitize=thread");
            }

            if (comp.bin_file.options.red_zone) {
                try argv.append("-mred-zone");
            } else if (target_util.hasRedZone(target)) {
                try argv.append("-mno-red-zone");
            }

            if (comp.bin_file.options.omit_frame_pointer) {
                try argv.append("-fomit-frame-pointer");
            } else {
                try argv.append("-fno-omit-frame-pointer");
            }

            const ssp_buf_size = comp.bin_file.options.stack_protector;
            if (ssp_buf_size != 0) {
                try argv.appendSlice(&[_][]const u8{
                    "-fstack-protector-strong",
                    "--param",
                    try std.fmt.allocPrint(arena, "ssp-buffer-size={d}", .{ssp_buf_size}),
                });
            } else {
                try argv.append("-fno-stack-protector");
            }

            switch (comp.bin_file.options.optimize_mode) {
                .Debug => {
                    // windows c runtime requires -D_DEBUG if using debug libraries
                    try argv.append("-D_DEBUG");
                    // Clang has -Og for compatibility with GCC, but currently it is just equivalent
                    // to -O1. Besides potentially impairing debugging, -O1/-Og significantly
                    // increases compile times.
                    try argv.append("-O0");
                },
                .ReleaseSafe => {
                    // See the comment in the BuildModeFastRelease case for why we pass -O2 rather
                    // than -O3 here.
                    try argv.append("-O2");
                    try argv.append("-D_FORTIFY_SOURCE=2");
                },
                .ReleaseFast => {
                    try argv.append("-DNDEBUG");
                    // Here we pass -O2 rather than -O3 because, although we do the equivalent of
                    // -O3 in Zig code, the justification for the difference here is that Zig
                    // has better detection and prevention of undefined behavior, so -O3 is safer for
                    // Zig code than it is for C code. Also, C programmers are used to their code
                    // running in -O2 and thus the -O3 path has been tested less.
                    try argv.append("-O2");
                },
                .ReleaseSmall => {
                    try argv.append("-DNDEBUG");
                    try argv.append("-Os");
                },
            }

            if (target_util.supports_fpic(target) and comp.bin_file.options.pic) {
                try argv.append("-fPIC");
            }

            if (comp.unwind_tables) {
                try argv.append("-funwind-tables");
            } else {
                try argv.append("-fno-unwind-tables");
            }
        },
        .shared_library, .ll, .bc, .unknown, .static_library, .object, .def, .zig => {},
        .assembly, .assembly_with_cpp => {
            // The Clang assembler does not accept the list of CPU features like the
            // compiler frontend does. Therefore we must hard-code the -m flags for
            // all CPU features here.
            switch (target.cpu.arch) {
                .riscv32, .riscv64 => {
                    const RvArchFeat = struct { char: u8, feat: std.Target.riscv.Feature };
                    const letters = [_]RvArchFeat{
                        .{ .char = 'm', .feat = .m },
                        .{ .char = 'a', .feat = .a },
                        .{ .char = 'f', .feat = .f },
                        .{ .char = 'd', .feat = .d },
                        .{ .char = 'c', .feat = .c },
                    };
                    const prefix: []const u8 = if (target.cpu.arch == .riscv64) "rv64" else "rv32";
                    const prefix_len = 4;
                    assert(prefix.len == prefix_len);
                    var march_buf: [prefix_len + letters.len + 1]u8 = undefined;
                    var march_index: usize = prefix_len;
                    mem.copy(u8, &march_buf, prefix);

                    if (std.Target.riscv.featureSetHas(target.cpu.features, .e)) {
                        march_buf[march_index] = 'e';
                    } else {
                        march_buf[march_index] = 'i';
                    }
                    march_index += 1;

                    for (letters) |letter| {
                        if (std.Target.riscv.featureSetHas(target.cpu.features, letter.feat)) {
                            march_buf[march_index] = letter.char;
                            march_index += 1;
                        }
                    }

                    const march_arg = try std.fmt.allocPrint(arena, "-march={s}", .{
                        march_buf[0..march_index],
                    });
                    try argv.append(march_arg);

                    if (std.Target.riscv.featureSetHas(target.cpu.features, .relax)) {
                        try argv.append("-mrelax");
                    } else {
                        try argv.append("-mno-relax");
                    }
                    if (std.Target.riscv.featureSetHas(target.cpu.features, .save_restore)) {
                        try argv.append("-msave-restore");
                    } else {
                        try argv.append("-mno-save-restore");
                    }
                },
                else => {
                    // TODO
                },
            }
            if (target_util.clangAssemblerSupportsMcpuArg(target)) {
                if (target.cpu.model.llvm_name) |llvm_name| {
                    try argv.append(try std.fmt.allocPrint(arena, "-mcpu={s}", .{llvm_name}));
                }
            }
        },
    }

    if (!comp.bin_file.options.strip) {
        switch (target.ofmt) {
            .coff => try argv.append("-gcodeview"),
            .elf, .macho => try argv.append("-gdwarf-4"),
            else => try argv.append("-g"),
        }
    }

    if (target_util.llvmMachineAbi(target)) |mabi| {
        try argv.append(try std.fmt.allocPrint(arena, "-mabi={s}", .{mabi}));
    }

    if (out_dep_path) |p| {
        try argv.appendSlice(&[_][]const u8{ "-MD", "-MV", "-MF", p });
    }

    // We never want clang to invoke the system assembler for anything. So we would want
    // this option always enabled. However, it only matters for some targets. To avoid
    // "unused parameter" warnings, and to keep CLI spam to a minimum, we only put this
    // flag on the command line if it is necessary.
    if (target_util.clangMightShellOutForAssembly(target)) {
        try argv.append("-integrated-as");
    }

    if (target.os.tag == .freestanding) {
        try argv.append("-ffreestanding");
    }

    try argv.appendSlice(comp.clang_argv);
}

fn failCObj(comp: *Compilation, c_object: *CObject, comptime format: []const u8, args: anytype) SemaError {
    @setCold(true);
    const err_msg = blk: {
        const msg = try std.fmt.allocPrint(comp.gpa, format, args);
        errdefer comp.gpa.free(msg);
        const err_msg = try comp.gpa.create(CObject.ErrorMsg);
        errdefer comp.gpa.destroy(err_msg);
        err_msg.* = .{
            .msg = msg,
            .line = 0,
            .column = 0,
        };
        break :blk err_msg;
    };
    return comp.failCObjWithOwnedErrorMsg(c_object, err_msg);
}

fn failCObjWithOwnedErrorMsg(
    comp: *Compilation,
    c_object: *CObject,
    err_msg: *CObject.ErrorMsg,
) SemaError {
    @setCold(true);
    {
        comp.mutex.lock();
        defer comp.mutex.unlock();
        {
            errdefer err_msg.destroy(comp.gpa);
            try comp.failed_c_objects.ensureUnusedCapacity(comp.gpa, 1);
        }
        comp.failed_c_objects.putAssumeCapacityNoClobber(c_object, err_msg);
    }
    c_object.status = .failure;
    return error.AnalysisFail;
}

pub const FileExt = enum {
    c,
    cpp,
    cu,
    h,
    m,
    mm,
    ll,
    bc,
    assembly,
    assembly_with_cpp,
    shared_library,
    object,
    static_library,
    zig,
    def,
    unknown,

    pub fn clangSupportsDepFile(ext: FileExt) bool {
        return switch (ext) {
            .c, .cpp, .h, .m, .mm, .cu => true,

            .ll,
            .bc,
            .assembly,
            .assembly_with_cpp,
            .shared_library,
            .object,
            .static_library,
            .zig,
            .def,
            .unknown,
            => false,
        };
    }
};

pub fn hasObjectExt(filename: []const u8) bool {
    return mem.endsWith(u8, filename, ".o") or mem.endsWith(u8, filename, ".obj");
}

pub fn hasStaticLibraryExt(filename: []const u8) bool {
    return mem.endsWith(u8, filename, ".a") or mem.endsWith(u8, filename, ".lib");
}

pub fn hasCExt(filename: []const u8) bool {
    return mem.endsWith(u8, filename, ".c");
}

pub fn hasCppExt(filename: []const u8) bool {
    return mem.endsWith(u8, filename, ".C") or
        mem.endsWith(u8, filename, ".cc") or
        mem.endsWith(u8, filename, ".cpp") or
        mem.endsWith(u8, filename, ".cxx") or
        mem.endsWith(u8, filename, ".stub");
}

pub fn hasObjCExt(filename: []const u8) bool {
    return mem.endsWith(u8, filename, ".m");
}

pub fn hasObjCppExt(filename: []const u8) bool {
    return mem.endsWith(u8, filename, ".mm");
}

pub fn hasSharedLibraryExt(filename: []const u8) bool {
    if (mem.endsWith(u8, filename, ".so") or
        mem.endsWith(u8, filename, ".dll") or
        mem.endsWith(u8, filename, ".dylib") or
        mem.endsWith(u8, filename, ".tbd"))
    {
        return true;
    }
    // Look for .so.X, .so.X.Y, .so.X.Y.Z
    var it = mem.split(u8, filename, ".");
    _ = it.first();
    var so_txt = it.next() orelse return false;
    while (!mem.eql(u8, so_txt, "so")) {
        so_txt = it.next() orelse return false;
    }
    const n1 = it.next() orelse return false;
    const n2 = it.next();
    const n3 = it.next();

    _ = std.fmt.parseInt(u32, n1, 10) catch return false;
    if (n2) |x| _ = std.fmt.parseInt(u32, x, 10) catch return false;
    if (n3) |x| _ = std.fmt.parseInt(u32, x, 10) catch return false;
    if (it.next() != null) return false;

    return true;
}

pub fn classifyFileExt(filename: []const u8) FileExt {
    if (hasCExt(filename)) {
        return .c;
    } else if (hasCppExt(filename)) {
        return .cpp;
    } else if (hasObjCExt(filename)) {
        return .m;
    } else if (hasObjCppExt(filename)) {
        return .mm;
    } else if (mem.endsWith(u8, filename, ".ll")) {
        return .ll;
    } else if (mem.endsWith(u8, filename, ".bc")) {
        return .bc;
    } else if (mem.endsWith(u8, filename, ".s")) {
        return .assembly;
    } else if (mem.endsWith(u8, filename, ".S")) {
        return .assembly_with_cpp;
    } else if (mem.endsWith(u8, filename, ".h")) {
        return .h;
    } else if (mem.endsWith(u8, filename, ".zig")) {
        return .zig;
    } else if (hasSharedLibraryExt(filename)) {
        return .shared_library;
    } else if (hasStaticLibraryExt(filename)) {
        return .static_library;
    } else if (hasObjectExt(filename)) {
        return .object;
    } else if (mem.endsWith(u8, filename, ".cu")) {
        return .cu;
    } else if (mem.endsWith(u8, filename, ".def")) {
        return .def;
    } else {
        return .unknown;
    }
}

test "classifyFileExt" {
    try std.testing.expectEqual(FileExt.cpp, classifyFileExt("foo.cc"));
    try std.testing.expectEqual(FileExt.m, classifyFileExt("foo.m"));
    try std.testing.expectEqual(FileExt.mm, classifyFileExt("foo.mm"));
    try std.testing.expectEqual(FileExt.unknown, classifyFileExt("foo.nim"));
    try std.testing.expectEqual(FileExt.shared_library, classifyFileExt("foo.so"));
    try std.testing.expectEqual(FileExt.shared_library, classifyFileExt("foo.so.1"));
    try std.testing.expectEqual(FileExt.shared_library, classifyFileExt("foo.so.1.2"));
    try std.testing.expectEqual(FileExt.shared_library, classifyFileExt("foo.so.1.2.3"));
    try std.testing.expectEqual(FileExt.unknown, classifyFileExt("foo.so.1.2.3~"));
    try std.testing.expectEqual(FileExt.zig, classifyFileExt("foo.zig"));
}

const LibCDirs = struct {
    libc_include_dir_list: []const []const u8,
    libc_installation: ?*const LibCInstallation,
};

fn getZigShippedLibCIncludeDirsDarwin(arena: Allocator, zig_lib_dir: []const u8, target: Target) !LibCDirs {
    const arch_name = @tagName(target.cpu.arch);
    const os_name = try std.fmt.allocPrint(arena, "{s}.{d}", .{
        @tagName(target.os.tag),
        target.os.version_range.semver.min.major,
    });
    const s = std.fs.path.sep_str;
    const list = try arena.alloc([]const u8, 3);

    list[0] = try std.fmt.allocPrint(
        arena,
        "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-{s}-none",
        .{ zig_lib_dir, arch_name, os_name },
    );
    list[1] = try std.fmt.allocPrint(
        arena,
        "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "any-{s}-any",
        .{ zig_lib_dir, os_name },
    );
    list[2] = try std.fmt.allocPrint(
        arena,
        "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "any-macos-any",
        .{zig_lib_dir},
    );

    return LibCDirs{
        .libc_include_dir_list = list,
        .libc_installation = null,
    };
}

fn detectLibCIncludeDirs(
    arena: Allocator,
    zig_lib_dir: []const u8,
    target: Target,
    is_native_abi: bool,
    link_libc: bool,
    libc_installation: ?*const LibCInstallation,
    has_macos_sdk: bool,
) !LibCDirs {
    if (!link_libc) {
        return LibCDirs{
            .libc_include_dir_list = &[0][]u8{},
            .libc_installation = null,
        };
    }

    if (libc_installation) |lci| {
        return detectLibCFromLibCInstallation(arena, target, lci);
    }

    // If linking system libraries and targeting the native abi, default to
    // using the system libc installation.
    if (is_native_abi and !target.isMinGW()) {
        if (target.isDarwin()) {
            return if (has_macos_sdk)
                // For Darwin/macOS, we are all set with getDarwinSDK found earlier.
                LibCDirs{
                    .libc_include_dir_list = &[0][]u8{},
                    .libc_installation = null,
                }
            else
                getZigShippedLibCIncludeDirsDarwin(arena, zig_lib_dir, target);
        }
        const libc = try arena.create(LibCInstallation);
        libc.* = LibCInstallation.findNative(.{ .allocator = arena }) catch |err| switch (err) {
            error.CCompilerExitCode,
            error.CCompilerCrashed,
            error.CCompilerCannotFindHeaders,
            error.UnableToSpawnCCompiler,
            => |e| {
                // We tried to integrate with the native system C compiler,
                // however, it is not installed. So we must rely on our bundled
                // libc files.
                if (target_util.canBuildLibC(target)) {
                    return detectLibCFromBuilding(arena, zig_lib_dir, target, has_macos_sdk);
                }
                return e;
            },
            else => |e| return e,
        };
        return detectLibCFromLibCInstallation(arena, target, libc);
    }

    // If not linking system libraries, build and provide our own libc by
    // default if possible.
    if (target_util.canBuildLibC(target)) {
        return detectLibCFromBuilding(arena, zig_lib_dir, target, has_macos_sdk);
    }

    // If zig can't build the libc for the target and we are targeting the
    // native abi, fall back to using the system libc installation.
    // On windows, instead of the native (mingw) abi, we want to check
    // for the MSVC abi as a fallback.
    const use_system_abi = if (builtin.target.os.tag == .windows)
        target.abi == .msvc
    else
        is_native_abi;

    if (use_system_abi) {
        const libc = try arena.create(LibCInstallation);
        libc.* = try LibCInstallation.findNative(.{ .allocator = arena, .verbose = true });
        return detectLibCFromLibCInstallation(arena, target, libc);
    }

    return LibCDirs{
        .libc_include_dir_list = &[0][]u8{},
        .libc_installation = null,
    };
}

fn detectLibCFromLibCInstallation(arena: Allocator, target: Target, lci: *const LibCInstallation) !LibCDirs {
    var list = try std.ArrayList([]const u8).initCapacity(arena, 5);

    list.appendAssumeCapacity(lci.include_dir.?);

    const is_redundant = mem.eql(u8, lci.sys_include_dir.?, lci.include_dir.?);
    if (!is_redundant) list.appendAssumeCapacity(lci.sys_include_dir.?);

    if (target.os.tag == .windows) {
        if (std.fs.path.dirname(lci.include_dir.?)) |include_dir_parent| {
            const um_dir = try std.fs.path.join(arena, &[_][]const u8{ include_dir_parent, "um" });
            list.appendAssumeCapacity(um_dir);

            const shared_dir = try std.fs.path.join(arena, &[_][]const u8{ include_dir_parent, "shared" });
            list.appendAssumeCapacity(shared_dir);
        }
    }
    if (target.os.tag == .haiku) {
        const include_dir_path = lci.include_dir orelse return error.LibCInstallationNotAvailable;
        const os_dir = try std.fs.path.join(arena, &[_][]const u8{ include_dir_path, "os" });
        list.appendAssumeCapacity(os_dir);
        // Errors.h
        const os_support_dir = try std.fs.path.join(arena, &[_][]const u8{ include_dir_path, "os/support" });
        list.appendAssumeCapacity(os_support_dir);

        const config_dir = try std.fs.path.join(arena, &[_][]const u8{ include_dir_path, "config" });
        list.appendAssumeCapacity(config_dir);
    }

    return LibCDirs{
        .libc_include_dir_list = list.items,
        .libc_installation = lci,
    };
}

fn detectLibCFromBuilding(
    arena: Allocator,
    zig_lib_dir: []const u8,
    target: std.Target,
    has_macos_sdk: bool,
) !LibCDirs {
    switch (target.os.tag) {
        .macos => return if (has_macos_sdk)
            // For Darwin/macOS, we are all set with getDarwinSDK found earlier.
            LibCDirs{
                .libc_include_dir_list = &[0][]u8{},
                .libc_installation = null,
            }
        else
            getZigShippedLibCIncludeDirsDarwin(arena, zig_lib_dir, target),
        else => {
            const generic_name = target_util.libCGenericName(target);
            // Some architectures are handled by the same set of headers.
            const arch_name = if (target.abi.isMusl())
                musl.archName(target.cpu.arch)
            else if (target.cpu.arch.isThumb())
                // ARM headers are valid for Thumb too.
                switch (target.cpu.arch) {
                    .thumb => "arm",
                    .thumbeb => "armeb",
                    else => unreachable,
                }
            else
                @tagName(target.cpu.arch);
            const os_name = @tagName(target.os.tag);
            // Musl's headers are ABI-agnostic and so they all have the "musl" ABI name.
            const abi_name = if (target.abi.isMusl()) "musl" else @tagName(target.abi);
            const s = std.fs.path.sep_str;
            const arch_include_dir = try std.fmt.allocPrint(
                arena,
                "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-{s}-{s}",
                .{ zig_lib_dir, arch_name, os_name, abi_name },
            );
            const generic_include_dir = try std.fmt.allocPrint(
                arena,
                "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "generic-{s}",
                .{ zig_lib_dir, generic_name },
            );
            const generic_arch_name = target_util.osArchName(target);
            const arch_os_include_dir = try std.fmt.allocPrint(
                arena,
                "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "{s}-{s}-any",
                .{ zig_lib_dir, generic_arch_name, os_name },
            );
            const generic_os_include_dir = try std.fmt.allocPrint(
                arena,
                "{s}" ++ s ++ "libc" ++ s ++ "include" ++ s ++ "any-{s}-any",
                .{ zig_lib_dir, os_name },
            );

            const list = try arena.alloc([]const u8, 4);
            list[0] = arch_include_dir;
            list[1] = generic_include_dir;
            list[2] = arch_os_include_dir;
            list[3] = generic_os_include_dir;

            return LibCDirs{
                .libc_include_dir_list = list,
                .libc_installation = null,
            };
        },
    }
}

pub fn get_libc_crt_file(comp: *Compilation, arena: Allocator, basename: []const u8) ![]const u8 {
    if (comp.wantBuildGLibCFromSource() or
        comp.wantBuildMuslFromSource() or
        comp.wantBuildMinGWFromSource() or
        comp.wantBuildWasiLibcFromSource())
    {
        return comp.crt_files.get(basename).?.full_object_path;
    }
    const lci = comp.bin_file.options.libc_installation orelse return error.LibCInstallationNotAvailable;
    const crt_dir_path = lci.crt_dir orelse return error.LibCInstallationMissingCRTDir;
    const full_path = try std.fs.path.join(arena, &[_][]const u8{ crt_dir_path, basename });
    return full_path;
}

fn wantBuildLibCFromSource(comp: Compilation) bool {
    const is_exe_or_dyn_lib = switch (comp.bin_file.options.output_mode) {
        .Obj => false,
        .Lib => comp.bin_file.options.link_mode == .Dynamic,
        .Exe => true,
    };
    return comp.bin_file.options.link_libc and is_exe_or_dyn_lib and
        comp.bin_file.options.libc_installation == null and
        comp.bin_file.options.target.ofmt != .c;
}

fn wantBuildGLibCFromSource(comp: Compilation) bool {
    return comp.wantBuildLibCFromSource() and comp.getTarget().isGnuLibC();
}

fn wantBuildMuslFromSource(comp: Compilation) bool {
    return comp.wantBuildLibCFromSource() and comp.getTarget().isMusl() and
        !comp.getTarget().isWasm();
}

fn wantBuildWasiLibcFromSource(comp: Compilation) bool {
    return comp.wantBuildLibCFromSource() and comp.getTarget().isWasm() and
        comp.getTarget().os.tag == .wasi;
}

fn wantBuildMinGWFromSource(comp: Compilation) bool {
    return comp.wantBuildLibCFromSource() and comp.getTarget().isMinGW();
}

fn wantBuildLibUnwindFromSource(comp: *Compilation) bool {
    const is_exe_or_dyn_lib = switch (comp.bin_file.options.output_mode) {
        .Obj => false,
        .Lib => comp.bin_file.options.link_mode == .Dynamic,
        .Exe => true,
    };
    return is_exe_or_dyn_lib and comp.bin_file.options.link_libunwind and
        comp.bin_file.options.target.ofmt != .c;
}

fn setAllocFailure(comp: *Compilation) void {
    log.debug("memory allocation failure", .{});
    comp.alloc_failure_occurred = true;
}

/// Assumes that Compilation mutex is locked.
/// See also `lockAndSetMiscFailure`.
pub fn setMiscFailure(
    comp: *Compilation,
    tag: MiscTask,
    comptime format: []const u8,
    args: anytype,
) void {
    comp.misc_failures.ensureUnusedCapacity(comp.gpa, 1) catch return comp.setAllocFailure();
    const msg = std.fmt.allocPrint(comp.gpa, format, args) catch return comp.setAllocFailure();
    const gop = comp.misc_failures.getOrPutAssumeCapacity(tag);
    if (gop.found_existing) {
        gop.value_ptr.deinit(comp.gpa);
    }
    gop.value_ptr.* = .{ .msg = msg };
}

/// See also `setMiscFailure`.
pub fn lockAndSetMiscFailure(
    comp: *Compilation,
    tag: MiscTask,
    comptime format: []const u8,
    args: anytype,
) void {
    comp.mutex.lock();
    defer comp.mutex.unlock();

    return setMiscFailure(comp, tag, format, args);
}

fn parseLldStderr(comp: *Compilation, comptime prefix: []const u8, stderr: []const u8) Allocator.Error!void {
    var context_lines = std.ArrayList([]const u8).init(comp.gpa);
    defer context_lines.deinit();

    var current_err: ?*LldError = null;
    var lines = mem.split(u8, stderr, std.cstr.line_sep);
    while (lines.next()) |line| {
        if (mem.startsWith(u8, line, prefix ++ ":")) {
            if (current_err) |err| {
                err.context_lines = try context_lines.toOwnedSlice();
            }

            var split = std.mem.split(u8, line, "error: ");
            _ = split.first();

            const duped_msg = try std.fmt.allocPrint(comp.gpa, "{s}: {s}", .{ prefix, split.rest() });
            errdefer comp.gpa.free(duped_msg);

            current_err = try comp.lld_errors.addOne(comp.gpa);
            current_err.?.* = .{ .msg = duped_msg };
        } else if (current_err != null) {
            const context_prefix = ">>> ";
            var trimmed = mem.trimRight(u8, line, &std.ascii.whitespace);
            if (mem.startsWith(u8, trimmed, context_prefix)) {
                trimmed = trimmed[context_prefix.len..];
            }

            if (trimmed.len > 0) {
                const duped_line = try comp.gpa.dupe(u8, trimmed);
                try context_lines.append(duped_line);
            }
        }
    }

    if (current_err) |err| {
        err.context_lines = try context_lines.toOwnedSlice();
    }
}

pub fn lockAndParseLldStderr(comp: *Compilation, comptime prefix: []const u8, stderr: []const u8) void {
    comp.mutex.lock();
    defer comp.mutex.unlock();

    comp.parseLldStderr(prefix, stderr) catch comp.setAllocFailure();
}

pub fn dump_argv(argv: []const []const u8) void {
    for (argv[0 .. argv.len - 1]) |arg| {
        std.debug.print("{s} ", .{arg});
    }
    std.debug.print("{s}\n", .{argv[argv.len - 1]});
}

pub fn getZigBackend(comp: Compilation) std.builtin.CompilerBackend {
    if (build_options.have_llvm and comp.bin_file.options.use_llvm) return .stage2_llvm;
    const target = comp.bin_file.options.target;
    if (target.ofmt == .c) return .stage2_c;
    return switch (target.cpu.arch) {
        .wasm32, .wasm64 => std.builtin.CompilerBackend.stage2_wasm,
        .arm, .armeb, .thumb, .thumbeb => .stage2_arm,
        .x86_64 => .stage2_x86_64,
        .x86 => .stage2_x86,
        .aarch64, .aarch64_be, .aarch64_32 => .stage2_aarch64,
        .riscv64 => .stage2_riscv64,
        .sparc64 => .stage2_sparc64,
        else => .other,
    };
}

pub fn generateBuiltinZigSource(comp: *Compilation, allocator: Allocator) Allocator.Error![:0]u8 {
    const tracy_trace = trace(@src());
    defer tracy_trace.end();

    var buffer = std.ArrayList(u8).init(allocator);
    defer buffer.deinit();

    const target = comp.getTarget();
    const generic_arch_name = target.cpu.arch.genericName();
    const zig_backend = comp.getZigBackend();

    @setEvalBranchQuota(4000);
    try buffer.writer().print(
        \\const std = @import("std");
        \\/// Zig version. When writing code that supports multiple versions of Zig, prefer
        \\/// feature detection (i.e. with `@hasDecl` or `@hasField`) over version checks.
        \\pub const zig_version = std.SemanticVersion.parse("{s}") catch unreachable;
        \\pub const zig_backend = std.builtin.CompilerBackend.{};
        \\
        \\pub const output_mode = std.builtin.OutputMode.{};
        \\pub const link_mode = std.builtin.LinkMode.{};
        \\pub const is_test = {};
        \\pub const single_threaded = {};
        \\pub const abi = std.Target.Abi.{};
        \\pub const cpu: std.Target.Cpu = .{{
        \\    .arch = .{},
        \\    .model = &std.Target.{}.cpu.{},
        \\    .features = std.Target.{}.featureSet(&[_]std.Target.{}.Feature{{
        \\
    , .{
        build_options.version,
        std.zig.fmtId(@tagName(zig_backend)),
        std.zig.fmtId(@tagName(comp.bin_file.options.output_mode)),
        std.zig.fmtId(@tagName(comp.bin_file.options.link_mode)),
        comp.bin_file.options.is_test,
        comp.bin_file.options.single_threaded,
        std.zig.fmtId(@tagName(target.abi)),
        std.zig.fmtId(@tagName(target.cpu.arch)),
        std.zig.fmtId(generic_arch_name),
        std.zig.fmtId(target.cpu.model.name),
        std.zig.fmtId(generic_arch_name),
        std.zig.fmtId(generic_arch_name),
    });

    for (target.cpu.arch.allFeaturesList(), 0..) |feature, index_usize| {
        const index = @intCast(std.Target.Cpu.Feature.Set.Index, index_usize);
        const is_enabled = target.cpu.features.isEnabled(index);
        if (is_enabled) {
            try buffer.writer().print("        .{},\n", .{std.zig.fmtId(feature.name)});
        }
    }

    try buffer.writer().print(
        \\    }}),
        \\}};
        \\pub const os = std.Target.Os{{
        \\    .tag = .{},
        \\    .version_range = .{{
    ,
        .{std.zig.fmtId(@tagName(target.os.tag))},
    );

    switch (target.os.getVersionRange()) {
        .none => try buffer.appendSlice(" .none = {} },\n"),
        .semver => |semver| try buffer.writer().print(
            \\ .semver = .{{
            \\        .min = .{{
            \\            .major = {},
            \\            .minor = {},
            \\            .patch = {},
            \\        }},
            \\        .max = .{{
            \\            .major = {},
            \\            .minor = {},
            \\            .patch = {},
            \\        }},
            \\    }}}},
            \\
        , .{
            semver.min.major,
            semver.min.minor,
            semver.min.patch,

            semver.max.major,
            semver.max.minor,
            semver.max.patch,
        }),
        .linux => |linux| try buffer.writer().print(
            \\ .linux = .{{
            \\        .range = .{{
            \\            .min = .{{
            \\                .major = {},
            \\                .minor = {},
            \\                .patch = {},
            \\            }},
            \\            .max = .{{
            \\                .major = {},
            \\                .minor = {},
            \\                .patch = {},
            \\            }},
            \\        }},
            \\        .glibc = .{{
            \\            .major = {},
            \\            .minor = {},
            \\            .patch = {},
            \\        }},
            \\    }}}},
            \\
        , .{
            linux.range.min.major,
            linux.range.min.minor,
            linux.range.min.patch,

            linux.range.max.major,
            linux.range.max.minor,
            linux.range.max.patch,

            linux.glibc.major,
            linux.glibc.minor,
            linux.glibc.patch,
        }),
        .windows => |windows| try buffer.writer().print(
            \\ .windows = .{{
            \\        .min = {s},
            \\        .max = {s},
            \\    }}}},
            \\
        ,
            .{ windows.min, windows.max },
        ),
    }
    try buffer.appendSlice("};\n");

    // This is so that compiler_rt and libc.zig libraries know whether they
    // will eventually be linked with libc. They make different decisions
    // about what to export depending on whether another libc will be linked
    // in. For example, compiler_rt will not export the __chkstk symbol if it
    // knows libc will provide it, and likewise c.zig will not export memcpy.
    const link_libc = comp.bin_file.options.link_libc or
        (comp.bin_file.options.skip_linker_dependencies and comp.bin_file.options.parent_compilation_link_libc);

    try buffer.writer().print(
        \\pub const target = std.Target{{
        \\    .cpu = cpu,
        \\    .os = os,
        \\    .abi = abi,
        \\    .ofmt = object_format,
        \\}};
        \\pub const object_format = std.Target.ObjectFormat.{};
        \\pub const mode = std.builtin.Mode.{};
        \\pub const link_libc = {};
        \\pub const link_libcpp = {};
        \\pub const have_error_return_tracing = {};
        \\pub const valgrind_support = {};
        \\pub const sanitize_thread = {};
        \\pub const position_independent_code = {};
        \\pub const position_independent_executable = {};
        \\pub const strip_debug_info = {};
        \\pub const code_model = std.builtin.CodeModel.{};
        \\
    , .{
        std.zig.fmtId(@tagName(target.ofmt)),
        std.zig.fmtId(@tagName(comp.bin_file.options.optimize_mode)),
        link_libc,
        comp.bin_file.options.link_libcpp,
        comp.bin_file.options.error_return_tracing,
        comp.bin_file.options.valgrind,
        comp.bin_file.options.tsan,
        comp.bin_file.options.pic,
        comp.bin_file.options.pie,
        comp.bin_file.options.strip,
        std.zig.fmtId(@tagName(comp.bin_file.options.machine_code_model)),
    });

    if (target.os.tag == .wasi) {
        const wasi_exec_model_fmt = std.zig.fmtId(@tagName(comp.bin_file.options.wasi_exec_model));
        try buffer.writer().print(
            \\pub const wasi_exec_model = std.builtin.WasiExecModel.{};
            \\
        , .{wasi_exec_model_fmt});
    }

    if (comp.bin_file.options.is_test) {
        try buffer.appendSlice(
            \\pub var test_functions: []std.builtin.TestFn = undefined; // overwritten later
            \\
        );
        if (comp.test_evented_io) {
            try buffer.appendSlice(
                \\pub const test_io_mode = .evented;
                \\
            );
        } else {
            try buffer.appendSlice(
                \\pub const test_io_mode = .blocking;
                \\
            );
        }
    }

    return buffer.toOwnedSliceSentinel(0);
}

pub fn updateSubCompilation(sub_compilation: *Compilation) !void {
    try sub_compilation.update();

    // Look for compilation errors in this sub_compilation
    // TODO instead of logging these errors, handle them in the callsites
    // of updateSubCompilation and attach them as sub-errors, properly
    // surfacing the errors. You can see an example of this already
    // done inside buildOutputFromZig.
    var errors = try sub_compilation.getAllErrorsAlloc();
    defer errors.deinit(sub_compilation.gpa);

    if (errors.list.len != 0) {
        for (errors.list) |full_err_msg| {
            switch (full_err_msg) {
                .src => |src| {
                    log.err("{s}:{d}:{d}: {s}", .{
                        src.src_path,
                        src.line + 1,
                        src.column + 1,
                        src.msg,
                    });
                },
                .plain => |plain| {
                    log.err("{s}", .{plain.msg});
                },
            }
        }
        return error.BuildingLibCObjectFailed;
    }
}

fn buildOutputFromZig(
    comp: *Compilation,
    src_basename: []const u8,
    output_mode: std.builtin.OutputMode,
    out: *?CRTFile,
    misc_task_tag: MiscTask,
) !void {
    const tracy_trace = trace(@src());
    defer tracy_trace.end();

    std.debug.assert(output_mode != .Exe);

    var main_pkg: Package = .{
        .root_src_directory = comp.zig_lib_directory,
        .root_src_path = src_basename,
    };
    defer main_pkg.deinitTable(comp.gpa);
    const root_name = src_basename[0 .. src_basename.len - std.fs.path.extension(src_basename).len];
    const target = comp.getTarget();
    const bin_basename = try std.zig.binNameAlloc(comp.gpa, .{
        .root_name = root_name,
        .target = target,
        .output_mode = output_mode,
    });
    defer comp.gpa.free(bin_basename);

    const emit_bin = Compilation.EmitLoc{
        .directory = null, // Put it in the cache directory.
        .basename = bin_basename,
    };
    const sub_compilation = try Compilation.create(comp.gpa, .{
        .global_cache_directory = comp.global_cache_directory,
        .local_cache_directory = comp.global_cache_directory,
        .zig_lib_directory = comp.zig_lib_directory,
        .cache_mode = .whole,
        .target = target,
        .root_name = root_name,
        .main_pkg = &main_pkg,
        .output_mode = output_mode,
        .thread_pool = comp.thread_pool,
        .libc_installation = comp.bin_file.options.libc_installation,
        .emit_bin = emit_bin,
        .optimize_mode = comp.compilerRtOptMode(),
        .link_mode = .Static,
        .function_sections = true,
        .no_builtin = true,
        .want_sanitize_c = false,
        .want_stack_check = false,
        .want_stack_protector = 0,
        .want_red_zone = comp.bin_file.options.red_zone,
        .omit_frame_pointer = comp.bin_file.options.omit_frame_pointer,
        .want_valgrind = false,
        .want_tsan = false,
        .want_pic = comp.bin_file.options.pic,
        .want_pie = comp.bin_file.options.pie,
        .emit_h = null,
        .strip = comp.compilerRtStrip(),
        .is_native_os = comp.bin_file.options.is_native_os,
        .is_native_abi = comp.bin_file.options.is_native_abi,
        .self_exe_path = comp.self_exe_path,
        .verbose_cc = comp.verbose_cc,
        .verbose_link = comp.bin_file.options.verbose_link,
        .verbose_air = comp.verbose_air,
        .verbose_llvm_ir = comp.verbose_llvm_ir,
        .verbose_cimport = comp.verbose_cimport,
        .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
        .clang_passthrough_mode = comp.clang_passthrough_mode,
        .skip_linker_dependencies = true,
        .parent_compilation_link_libc = comp.bin_file.options.link_libc,
    });
    defer sub_compilation.destroy();

    try sub_compilation.update();
    // Look for compilation errors in this sub_compilation.
    var keep_errors = false;
    var errors = try sub_compilation.getAllErrorsAlloc();
    defer if (!keep_errors) errors.deinit(sub_compilation.gpa);

    if (errors.list.len != 0) {
        try comp.misc_failures.ensureUnusedCapacity(comp.gpa, 1);
        comp.misc_failures.putAssumeCapacityNoClobber(misc_task_tag, .{
            .msg = try std.fmt.allocPrint(comp.gpa, "sub-compilation of {s} failed", .{
                @tagName(misc_task_tag),
            }),
            .children = errors,
        });
        keep_errors = true;
        return error.SubCompilationFailed;
    }

    assert(out.* == null);
    out.* = Compilation.CRTFile{
        .full_object_path = try sub_compilation.bin_file.options.emit.?.directory.join(comp.gpa, &[_][]const u8{
            sub_compilation.bin_file.options.emit.?.sub_path,
        }),
        .lock = sub_compilation.bin_file.toOwnedLock(),
    };
}

pub fn build_crt_file(
    comp: *Compilation,
    root_name: []const u8,
    output_mode: std.builtin.OutputMode,
    c_source_files: []const Compilation.CSourceFile,
) !void {
    const tracy_trace = trace(@src());
    defer tracy_trace.end();

    const target = comp.getTarget();
    const basename = try std.zig.binNameAlloc(comp.gpa, .{
        .root_name = root_name,
        .target = target,
        .output_mode = output_mode,
    });
    errdefer comp.gpa.free(basename);

    const sub_compilation = try Compilation.create(comp.gpa, .{
        .local_cache_directory = comp.global_cache_directory,
        .global_cache_directory = comp.global_cache_directory,
        .zig_lib_directory = comp.zig_lib_directory,
        .cache_mode = .whole,
        .target = target,
        .root_name = root_name,
        .main_pkg = null,
        .output_mode = output_mode,
        .thread_pool = comp.thread_pool,
        .libc_installation = comp.bin_file.options.libc_installation,
        .emit_bin = .{
            .directory = null, // Put it in the cache directory.
            .basename = basename,
        },
        .optimize_mode = comp.compilerRtOptMode(),
        .want_sanitize_c = false,
        .want_stack_check = false,
        .want_stack_protector = 0,
        .want_red_zone = comp.bin_file.options.red_zone,
        .omit_frame_pointer = comp.bin_file.options.omit_frame_pointer,
        .want_valgrind = false,
        .want_tsan = false,
        .want_pic = comp.bin_file.options.pic,
        .want_pie = comp.bin_file.options.pie,
        .want_lto = switch (output_mode) {
            .Lib => comp.bin_file.options.lto,
            .Obj, .Exe => false,
        },
        .emit_h = null,
        .strip = comp.compilerRtStrip(),
        .is_native_os = comp.bin_file.options.is_native_os,
        .is_native_abi = comp.bin_file.options.is_native_abi,
        .self_exe_path = comp.self_exe_path,
        .c_source_files = c_source_files,
        .verbose_cc = comp.verbose_cc,
        .verbose_link = comp.bin_file.options.verbose_link,
        .verbose_air = comp.verbose_air,
        .verbose_llvm_ir = comp.verbose_llvm_ir,
        .verbose_cimport = comp.verbose_cimport,
        .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
        .clang_passthrough_mode = comp.clang_passthrough_mode,
        .skip_linker_dependencies = true,
        .parent_compilation_link_libc = comp.bin_file.options.link_libc,
    });
    defer sub_compilation.destroy();

    try sub_compilation.updateSubCompilation();

    try comp.crt_files.ensureUnusedCapacity(comp.gpa, 1);

    comp.crt_files.putAssumeCapacityNoClobber(basename, .{
        .full_object_path = try sub_compilation.bin_file.options.emit.?.directory.join(comp.gpa, &[_][]const u8{
            sub_compilation.bin_file.options.emit.?.sub_path,
        }),
        .lock = sub_compilation.bin_file.toOwnedLock(),
    });
}

pub fn addLinkLib(comp: *Compilation, lib_name: []const u8) !void {
    // Avoid deadlocking on building import libs such as kernel32.lib
    // This can happen when the user uses `build-exe foo.obj -lkernel32` and
    // then when we create a sub-Compilation for zig libc, it also tries to
    // build kernel32.lib.
    if (comp.bin_file.options.skip_linker_dependencies) return;

    // This happens when an `extern "foo"` function is referenced.
    // If we haven't seen this library yet and we're targeting Windows, we need
    // to queue up a work item to produce the DLL import library for this.
    const gop = try comp.bin_file.options.system_libs.getOrPut(comp.gpa, lib_name);
    if (!gop.found_existing and comp.getTarget().os.tag == .windows) {
        try comp.work_queue.writeItem(.{
            .windows_import_lib = comp.bin_file.options.system_libs.count() - 1,
        });
    }
}

/// This decides the optimization mode for all zig-provided libraries, including
/// compiler-rt, libcxx, libc, libunwind, etc.
pub fn compilerRtOptMode(comp: Compilation) std.builtin.Mode {
    if (comp.debug_compiler_runtime_libs) {
        return comp.bin_file.options.optimize_mode;
    }
    switch (comp.bin_file.options.optimize_mode) {
        .Debug, .ReleaseSafe => return target_util.defaultCompilerRtOptimizeMode(comp.getTarget()),
        .ReleaseFast => return .ReleaseFast,
        .ReleaseSmall => return .ReleaseSmall,
    }
}

/// This decides whether to strip debug info for all zig-provided libraries, including
/// compiler-rt, libcxx, libc, libunwind, etc.
pub fn compilerRtStrip(comp: Compilation) bool {
    if (comp.debug_compiler_runtime_libs) {
        return comp.bin_file.options.strip;
    } else {
        return true;
    }
}