cinrs-core 0.2.0

The C front end behind the cinrs crate: lexer, preprocessor, parser, semantic analysis, code generation
Documentation
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
//! Declarations: objects, `typedef`s, functions and the `extern` block.

use std::collections::{HashMap, HashSet};

use crate::ast;
use crate::capture::SourceRange;
use crate::ir::{
    self, ConstValue, Expr, ExprKind, FuncId, Function, ObjectId, Place, PlaceKind, Signature,
    StaticVar, Stmt, Storage, Ty, TypedefItem,
};
use crate::target::Arch;

use super::types::Completeness;
use super::{ConvContext, Entry, FuncScope, NestFrame, SavedFunc, Sema, TypedefEntry};

/// What a declaration's `_Thread_local` specifier came to.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ThreadLocal {
    /// There was none.
    No,
    /// The object is thread-local, and the declaration is well formed.
    Yes,
    /// The declaration was reported; nothing more should be made of it.
    Rejected,
}

/// What the alignment specifiers of one declarator ask of the object.
///
/// See [`Sema::align_request`], which builds it, and
/// [`Sema::apply_object_alignment`], which decides what the object does with
/// it.
#[derive(Clone, Copy, Debug)]
struct AlignRequest {
    /// The strictest alignment asked for, in bytes; already checked to be a
    /// power of two.
    want: u64,
    /// Where the specifier that asked for it was written.
    range: SourceRange,
    /// Whether an `_Alignas` specifier is among the requests, rather than only
    /// GCC's `aligned` attribute.
    standard: bool,
}

impl Sema<'_> {
    // -- static assertions --------------------------------------------------

    /// Checks a `_Static_assert` declaration, which generates nothing at all.
    ///
    /// It is the same check wherever the declaration was written — at file
    /// scope, inside a block or among a record's members — because a constant
    /// expression means the same thing in all three.
    pub(super) fn static_assert(&mut self, assert: &ast::StaticAssert) {
        let Some(value) = self.expr(&assert.cond) else {
            return;
        };
        if !value.ty.is_integer() {
            self.error(
                assert.cond.range,
                format!(
                    "the controlling expression of a static assertion must have an integer \
                     type, not '{}'",
                    self.tyname(value.ty)
                ),
            );
            return;
        }
        let what = "the controlling expression of a static assertion";
        let Some(constant) = self.const_eval_at(&value, what) else {
            return;
        };
        if super::is_true(constant) {
            return;
        }
        let message = match &assert.message {
            Some(text) => format!("static assertion failed: {text}"),
            None => "static assertion failed".to_owned(),
        };
        self.error(assert.range, message);
    }

    // -- top level ----------------------------------------------------------

    pub(super) fn file_scope_decl(&mut self, decl: &ast::Decl) {
        if decl.declarators.is_empty() {
            // `struct S { … };` and friends: a tag definition with nothing
            // declared. Resolving the specifier is what defines the tag.
            self.declare_sole_tag(decl);
            self.standalone_declaration(decl, |sema| {
                let _ = sema.ty_of(&decl.specifiers.base);
            });
            return;
        }
        for declarator in &decl.declarators {
            self.declarator(decl, declarator, true);
        }
    }

    /// C11 6.7.2.3p7: `struct S;` **on its own** declares the tag in the scope
    /// it is written in, and therefore a *new* type, even where an enclosing
    /// scope has a `struct S` of its own.
    ///
    /// Only the sole declaration does that. `struct S *p;` is 6.7.2.3p8 —
    /// "and no other declaration of the identifier as a tag is visible" — and
    /// names the visible tag. WG14 DR088 is the difference: a `struct S;`
    /// written inside a block makes the file scope's `struct S *` and this
    /// block's two incompatible pointer types, and `drs/dr0xx.c` checks both
    /// halves of it.
    ///
    /// The tag goes in before the specifier is resolved, which is what makes
    /// [`Sema::record_ty`] find it in *this* scope and stop looking outward.
    /// A definition (`struct S { … };`) already declares a new type and needs
    /// nothing here, and neither does `enum`, which has no such form —
    /// footnote 130's "a similar construction with `enum` does not exist".
    /// Marks a declaration that declares nothing but its specifier, which is
    /// the one place C23 lets a non-defining `enum E : T` stand.
    ///
    /// See [`Sema::standalone_enum`].
    pub(super) fn standalone_declaration(&mut self, decl: &ast::Decl, f: impl FnOnce(&mut Self)) {
        let outer = match &decl.specifiers.base.kind {
            ast::TypeKind::Enum(id) => self.standalone_enum.replace(*id),
            _ => self.standalone_enum.take(),
        };
        f(self);
        self.standalone_enum = outer;
    }

    pub(super) fn declare_sole_tag(&mut self, decl: &ast::Decl) {
        let ast::TypeKind::Record(spec_id) = &decl.specifiers.base.kind else {
            return;
        };
        if self.record_by_spec[spec_id.index()].is_some() {
            return;
        }
        let spec = self.record_spec(*spec_id);
        if spec.fields.is_some() {
            return;
        }
        let Some(name) = spec.name.as_ref().map(|n| n.name.clone()) else {
            return;
        };
        // A tag this scope already has — as a record or as an enumeration — is
        // this declaration's subject, or its diagnostic; either way there is
        // nothing new to declare.
        if self.tag_here(&name).is_some() {
            return;
        }
        let kind = match spec.kind {
            ast::RecordKind::Struct => crate::ir::RecordKind::Struct,
            ast::RecordKind::Union => crate::ir::RecordKind::Union,
        };
        let range = spec.range;
        let id = self.declare_record(kind, Some(name.clone()), range);
        self.insert_tag(&name, super::TagEntry::Record(id));
        self.record_by_spec[spec_id.index()] = Some(id);
    }

    /// Handles one declarator of a declaration, at file or block scope.
    ///
    /// Returns the statements the declarator contributes to the enclosing
    /// block (empty at file scope, for `typedef`s and for `static` locals).
    ///
    /// The declarators of `decl` are handed in one at a time, in order. When
    /// its specifiers name a `typedef`, the first one pins what that name
    /// denotes *before* anything is declared, and the last one lets go: the
    /// specifiers are the same for every declarator, even after one of them
    /// has hidden the name (C11 6.2.1p7). See [`Sema::pinned_typedefs`].
    pub(super) fn declarator(
        &mut self,
        decl: &ast::Decl,
        declarator: &ast::InitDeclarator,
        file_scope: bool,
    ) -> Vec<Stmt> {
        let pinned = match &decl.specifiers.base.kind {
            ast::TypeKind::Typedef(name) if decl.declarators.len() > 1 => Some(name),
            _ => None,
        };
        let first = decl
            .declarators
            .first()
            .is_some_and(|d| std::ptr::eq(d, declarator));
        let last = decl
            .declarators
            .last()
            .is_some_and(|d| std::ptr::eq(d, declarator));
        if let Some(name) = pinned
            && first
        {
            let entry = self.lookup_typedef(name).cloned();
            if let Some(entry) = entry {
                self.pinned_typedefs
                    .push((name.range, name.name.clone(), entry));
            }
        }
        let out = self.declare_one(decl, declarator, file_scope);
        if let Some(name) = pinned
            && last
            && self
                .pinned_typedefs
                .last()
                .is_some_and(|(range, _, _)| *range == name.range)
        {
            self.pinned_typedefs.pop();
        }
        out
    }

    /// [`Sema::declarator`], once the specifiers' `typedef` is pinned.
    fn declare_one(
        &mut self,
        decl: &ast::Decl,
        declarator: &ast::InitDeclarator,
        file_scope: bool,
    ) -> Vec<Stmt> {
        let Some(name) = &declarator.name else {
            // Nothing is declared, but the specifier may still define a tag.
            let _ = self.ty_of(&decl.specifiers.base);
            return Vec::new();
        };
        // Whether it is a `long double`, which the resolved type no longer
        // says; see `sema::long_double`.
        self.note_long_double(name.range, &declarator.ty);

        if decl.specifiers.is_typedef() {
            let mut attrs = declarator.attrs.clone();
            attrs.merge(decl.specifiers.attrs.clone());
            self.reject_cleanup(&attrs, "a 'typedef'");
            self.reject_safe(&attrs, "a 'typedef'");
            self.reject_weak(&attrs, "a 'typedef'");
            self.reject_alignas(&decl.specifiers, "a 'typedef'");
            // `typedef __attribute__((aligned(1))) uint64_t T;` puts the
            // attribute among the specifiers, which is where xxHash writes it.
            if attrs.aligned.is_none() {
                attrs.aligned = decl
                    .specifiers
                    .alignas
                    .iter()
                    .find(|s| s.from_attribute)
                    .cloned();
            }
            return self.declare_typedef(name, &declarator.ty, declarator.init.as_ref(), &attrs);
        }

        let storage = decl.specifiers.storage.as_ref().map(|s| s.node);
        if let ast::TypeKind::Function(func) = &declarator.ty.kind {
            // C11 6.7.1p4: `_Thread_local` applies to an object, and a
            // function is not one.
            if let Some(range) = decl.specifiers.thread_local {
                self.error(range, "'_Thread_local' is not allowed on a function");
            }
            self.reject_alignas(&decl.specifiers, "a function");
            let mut attrs = declarator.attrs.clone();
            attrs.merge(decl.specifiers.attrs.clone());
            // GNU spells the forward declaration of a nested function
            // `auto int g(int);`, which is the one way to write two nested
            // functions that call each other. At file scope the storage class
            // means nothing a function can have.
            let scope = match storage {
                Some(ast::StorageClass::Auto) if !file_scope => FuncScope::Nested,
                Some(ast::StorageClass::Auto) => {
                    let at = decl
                        .specifiers
                        .storage
                        .as_ref()
                        .map_or(name.range, |s| s.range);
                    self.error(
                        at,
                        "'auto' is not allowed on a file-scope function; it declares a nested \
                         function, which only a block may hold",
                    );
                    FuncScope::File
                }
                _ => FuncScope::File,
            };
            if let Some(id) = self.declare_function(
                decl,
                name,
                func,
                &attrs,
                declarator.asm_label.as_ref(),
                None,
                scope,
            ) {
                self.note_long_double_function(id, func);
            }
            return Vec::new();
        }

        // Everything below declares an *object*, which none of the function
        // specifiers apply to.
        if let Some(range) = decl.specifiers.noreturn {
            self.error(range, "'_Noreturn' is only allowed on a function");
        }
        let mut attrs = declarator.attrs.clone();
        attrs.merge(decl.specifiers.attrs.clone());
        if let Some(range) = attrs.packed {
            self.error(range, "'packed' is only meaningful on a record or a member");
        }
        self.reject_safe(&attrs, "an object");
        // `_Alignas(N)`, `_Alignas(T)` and `__attribute__((aligned(N)))` on the
        // object itself; see [`Sema::align_request`]. The operand is checked
        // here, where it is written; whether the object can carry the answer
        // depends on its type, and is [`Sema::apply_object_alignment`]'s
        // question.
        let mut requested = self.align_request(&decl.specifiers, &attrs);
        if let Some(request) = &requested
            && let Some(what) = match storage {
                // C11 6.7.5p2: the address of a `register` object cannot be
                // taken, so there is nothing an alignment could describe.
                Some(ast::StorageClass::Register) => Some("an object declared 'register'"),
                Some(ast::StorageClass::Constexpr) => {
                    Some("a 'constexpr' object, which becomes a constant rather than storage")
                }
                // The object is defined in another translation unit and this
                // declaration reserves no storage, so there is nothing here to
                // align; GCC's own attribute is equally inert on one.
                Some(ast::StorageClass::Extern) => None,
                _ => None,
            }
        {
            self.error(
                request.range,
                format!("an alignment specifier is not allowed on {what}"),
            );
            requested = None;
        }
        // An object declared with an over-aligned `typedef` (`typedef double
        // __attribute__((aligned(16))) d16; d16 x;`) is that aligned. One
        // declared with an under-aligned `typedef` keeps its type's own
        // alignment, which is stricter and so still correct: a weaker request
        // from an attribute is not applied (see `apply_object_alignment`).
        if let Some(n) = self.typedef_align(&declarator.ty)
            && !matches!(
                storage,
                Some(
                    ast::StorageClass::Register
                        | ast::StorageClass::Constexpr
                        | ast::StorageClass::Extern
                )
            )
        {
            match &mut requested {
                Some(request) => request.want = request.want.max(n),
                None => {
                    requested = Some(AlignRequest {
                        want: n,
                        range: declarator.ty.range,
                        standard: false,
                    });
                }
            }
        }
        // GCC drops `cleanup` on anything but an automatic object, with
        // "'cleanup' attribute ignored"; dropping it silently would change
        // what the program does, so it is refused with the reason.
        if let Some(what) = match storage {
            _ if decl.specifiers.thread_local.is_some() => Some("a thread-local object"),
            Some(ast::StorageClass::Static) => Some("an object with static storage duration"),
            Some(ast::StorageClass::Extern) => Some("an 'extern' declaration"),
            Some(ast::StorageClass::Constexpr) => Some("a 'constexpr' object"),
            _ if file_scope => Some("an object at file scope"),
            _ => None,
        } {
            self.reject_cleanup(&attrs, what);
        }
        // An `extern` declaration reserves no storage, so there is no
        // definition for the linker to make weak; anything else here does.
        if storage != Some(ast::StorageClass::Extern) {
            self.reject_weak(&attrs, "an object this unit defines");
        }

        let thread_local = self.check_thread_local(decl, storage, file_scope);
        if thread_local == ThreadLocal::Rejected {
            // The name is still declared, as something already reported, so
            // that every use of it adds nothing to the diagnostics.
            self.check_redefinition(name);
            let id = self.new_object(&name.name, Ty::Error, Storage::Automatic, false, name.range);
            self.insert(&name.name, Entry::Object(id));
            return Vec::new();
        }
        if storage == Some(ast::StorageClass::Extern) {
            self.declare_extern_object(name, declarator);
            if let Some(Entry::Object(id)) = self.lookup(&name.name).cloned() {
                self.apply_object_attributes(id, &attrs, declarator);
            }
            return Vec::new();
        }

        // C99 6.2.1p7: "the scope of an identifier … begins just after the
        // completion of its declarator", which puts the object in scope for
        // its *own* initialiser. `struct list head = { &head, &head }` is the
        // circular-list idiom, `T *p = malloc(sizeof *p)` is the allocation
        // one, and `struct E e[2] = { { 0, &e[1] }, … }` is a torture case.
        // So the type is resolved and the object declared *before* the
        // initialiser is checked.
        //
        // The two forms whose type the initialiser decides — C23's `auto x =
        // e` and `T x[] = { … }` — cannot do that, because there is no type to
        // declare the object with yet. Neither of them can name itself either
        // (an incomplete array has no `sizeof`), so nothing is lost.
        //
        // Every bound that is not a constant expression gets a hidden object
        // of its own during the resolution below, and the statements that bind
        // them are this declaration's to take.
        self.vm_bounds.clear();
        let mut inferred = type_from_initializer(declarator);
        let (mut ty, mut init) = if inferred {
            self.typed_initializer(declarator, &name.name)
                .unwrap_or((Ty::Error, None))
        } else {
            // A file-scope declaration with no initialiser is a tentative
            // definition, and one of the two places an incomplete array type
            // may be the type of an object (6.9.2p3); `extern` is the other,
            // and went through `declare_extern_object` above.
            let completeness = if file_scope {
                Completeness::TentativeArray
            } else {
                Completeness::Required
            };
            let ty = self
                .declared_object_ty_of(&declarator.ty, &name.name, completeness)
                .unwrap_or(Ty::Error);
            // A tentative definition of an enumeration that has no list yet:
            // the tag may still be completed later in the unit, so the answer
            // waits for `Sema::check_tentative_enums`.
            if file_scope && let Some(tag) = self.incomplete_enum(&declarator.ty).map(str::to_owned)
            {
                self.incomplete_enum_objects
                    .push((name.name.clone(), tag, declarator.range));
            }
            (self.apply_mode(ty, &attrs), None)
        };
        // `typedef int A[]; A a = { 1, 2 };` — an incomplete array type reached
        // through a `typedef` takes its length from the initialiser too
        // (6.7.9p22), exactly as the `int a[] = { … }` spelling does. It is the
        // only shape of that rule the declarator itself does not show.
        if !inferred
            && let Some(list) = &declarator.init
            && let Ty::Array(id) = ty
            && self.types().array_type(id).incomplete
        {
            let array = self.types().array_type(id);
            if let Some((completed, value)) =
                self.init_array_inferred(list, array.elem, array.elem_const, &name.name)
            {
                ty = completed;
                init = Some(value);
                inferred = true;
            }
        }
        let bounds = self.take_vm_bounds();

        if storage == Some(ast::StorageClass::Constexpr) {
            // A `constexpr` object is a *constant* rather than storage, so
            // there is no address for its own initialiser to take and nothing
            // to declare before checking one.
            if !inferred {
                init = self.late_initializer(declarator, ty, &name.name);
            }
            self.declare_constexpr(name, ty, init, declarator);
            return Vec::new();
        }
        let is_const = declarator.ty.qualifiers.is_const;
        let is_static = storage == Some(ast::StorageClass::Static);

        // A variably modified type is the one type whose object cannot be a
        // plain `let`, and the one C hedges around with rules about where it
        // may be declared at all. It may not have an initialiser at all.
        if self.types().is_vm(ty) {
            // The object is a pointer into a heap allocation, whose alignment
            // is the element type's; a stricter one asked for — spectral-norm
            // writes `double v[n] __attribute__((aligned(32)))` and reads it
            // with `_mm256_load_pd` — is had by over-allocating and starting
            // the array at the first multiple of it. See [`ir::VlaDef::align`].
            let mut align = None;
            if let Some(request) = &requested {
                let elem = self.types().vm_step_ty(ty);
                let natural = self.natural_align(elem).unwrap_or(1);
                if request.want < natural && request.standard {
                    self.error(
                        request.range,
                        format!(
                            "the requested alignment {} is weaker than the alignment {natural} \
                             that '{}' already has",
                            request.want,
                            self.tyname(elem)
                        ),
                    );
                } else if request.want > natural {
                    align = Some(request.want);
                }
            }
            let mut out = self.declare_vla(name, decl, declarator, ty, bounds, file_scope);
            if let Some(Stmt::Vla(def)) = out.last_mut() {
                def.align = align;
            }
            if let Some(Stmt::Vla(def)) = out.last() {
                let object = def.object;
                out.extend(self.declare_cleanup(object, attrs.cleanup.as_ref()));
            }
            return out;
        }

        if file_scope || is_static {
            // C99 6.7.5.2p2: an object with static storage duration may not
            // have a variably modified type — `static int (*p)[n];` has no
            // moment at which its bound could be evaluated. Having evaluated
            // one is exactly what says the type is.
            if !bounds.is_empty() {
                self.error(
                    declarator.range,
                    "a variably modified type cannot have static storage duration",
                );
            }
            // An object with static storage duration outlives every argument
            // list there could be, and Rust's `VaList` says so with a lifetime
            // no item could name.
            let ty = if self.reject_va_list(ty, declarator.range) {
                Ty::Error
            } else {
                ty
            };
            let object = self.declare_static_object(
                name,
                ty,
                is_const,
                is_static,
                file_scope,
                thread_local == ThreadLocal::Yes,
                declarator,
            );
            if !inferred {
                // An object with static storage duration is the only one GNU C
                // lets initialise a flexible array member: its storage is the
                // compiler's to make as large as the initialiser asks. See
                // `Sema::flexible_member_init`.
                self.flexible_init = super::init::FlexibleInit::Allowed;
                init = self.late_initializer(declarator, ty, &name.name);
                self.flexible_init = super::init::FlexibleInit::Automatic;
            }
            if let (Some(id), Some(init)) = (object, init) {
                self.initialize_static_object(id, declarator, init);
            }
            if let Some(Entry::Object(id)) = self.lookup(&name.name).cloned() {
                self.apply_object_attributes(id, &attrs, declarator);
                self.apply_object_alignment(id, ty, requested);
            }
            return Vec::new();
        }

        if let Some(label) = &declarator.asm_label {
            self.error(
                label.range,
                "an 'asm' label on a local variable is not supported: GCC's register variable \
                 has no counterpart in Rust's 'asm!'. Write the register as a constraint of the \
                 'asm' statement instead, such as \"a\"(x) for eax",
            );
        }
        if let Some(section) = &attrs.section {
            self.error(
                section.range,
                "'section' is only meaningful on a function or an object with static \
                 storage duration",
            );
        }
        self.check_redefinition(name);
        self.refuse_float128_object(&name.name, ty, name.range);
        let id = self.new_object(&name.name, ty, Storage::Automatic, is_const, name.range);
        // C11 6.7.1p6: the address of a `register` object cannot be computed,
        // explicitly or by an array decaying to a pointer. See
        // [`ir::Object::is_register`].
        self.program.objects[id.0 as usize].is_register =
            storage == Some(ast::StorageClass::Register);
        self.insert(&name.name, Entry::Object(id));
        if ty.is_error() {
            return Vec::new();
        }
        self.apply_object_alignment(id, ty, requested);
        if !inferred {
            init = self.late_initializer(declarator, ty, &name.name);
        }
        // A `va_list` has no zero value: it starts out as a copy of the list
        // the function was called with, which is also what `va_start` puts
        // back into it. (A `va_list *` local has one — a null pointer.)
        if ty.is_va_list() && init.is_none() {
            let Some(init) = self.va_list_init(declarator.range) else {
                // The name stays declared, but as something already reported,
                // so that using it adds nothing.
                self.program.objects[id.0 as usize].ty = Ty::Error;
                return Vec::new();
            };
            return vec![Stmt::Let {
                object: id,
                init,
                explicit: true,
            }];
        }
        let explicit = init.is_some();
        let init = match init {
            Some(init) => init,
            None => self.zero(ty, declarator.range),
        };
        // Rust cannot name a binding in its own initialiser, so an automatic
        // object whose initialiser names *itself* is defined with the zero
        // C would have left there and assigned afterwards. The assignment
        // stands where the declaration was written, which is where C evaluates
        // the initialiser; a hoisted definition keeps the zero, which is what
        // `explicit: false` asks for.
        // A bound written in the declarator — `int (*p)[n]` — is evaluated
        // where the declaration stands, into the hidden object the type points
        // at, and that has to happen before anything can use the type.
        let mut out = bounds;
        if explicit && ir::mentions_object(&init, id) {
            let zero = self.zero(ty, declarator.range);
            let place = super::place_of(PlaceKind::Object(id), ty, false, name.range);
            let assign = Expr::new(
                ExprKind::Assign {
                    place,
                    value: Box::new(init),
                },
                ty,
                declarator.range,
            );
            out.push(Stmt::Let {
                object: id,
                init: zero,
                explicit: false,
            });
            out.push(Stmt::Expr(assign));
        } else {
            out.push(Stmt::Let {
                object: id,
                init,
                explicit,
            });
        }
        out.extend(self.declare_cleanup(id, attrs.cleanup.as_ref()));
        out
    }

    /// Registers `T x __attribute__((cleanup(f)));` on an object that has just
    /// been declared (GCC's extension).
    ///
    /// The registration is a statement rather than a property of the object
    /// because *where* it stands is what it means: the guard the structured
    /// lowering binds goes right after the object's own binding, so that
    /// Rust's drop order is C's reverse declaration order, and the
    /// [CFG](crate::cfg) lowering reads the same statement as "from here to
    /// the end of the block, this call is owed on every way out".
    pub(super) fn declare_cleanup(
        &mut self,
        object: ObjectId,
        cleanup: Option<&ast::Cleanup>,
    ) -> Option<Stmt> {
        let cleanup = cleanup?;
        // GCC's own two words for the argument it cannot use.
        let Some(name) = &cleanup.func else {
            self.error(cleanup.range, "cleanup argument not an identifier");
            return None;
        };
        let Some(Entry::Function(func)) = self.lookup(&name.name).cloned() else {
            self.error(name.range, "cleanup argument not a function");
            return None;
        };
        // The structured lowering holds the cleanup function in a drop guard,
        // which is its *address*; a lifted nested function that uses the
        // enclosing frame has none to give.
        if self.program.function(func).is_nested() {
            self.nested_addresses.push((func, name.range));
        }
        let entry = self.program.function(func);
        let (sig, declared, fname) = (entry.sig.clone(), entry.range, entry.name.clone());
        if sig.params.len() != 1 || sig.variadic {
            let expected = if sig.variadic {
                format!("at least {}", sig.params.len())
            } else {
                sig.params.len().to_string()
            };
            let word = if sig.params.len() > 1 { "few" } else { "many" };
            self.error_note(
                cleanup.range,
                format!(
                    "the cleanup function is called with one argument, the object's address: \
                     too {word} arguments to function call, expected {expected}, have 1"
                ),
                declared,
                format!("'{fname}' is declared"),
            );
            return None;
        }
        let param = sig.params[0];
        let info = self.program.object(object);
        let (ty, is_const, range) = (info.ty, info.is_const, info.range);
        if ty.is_error() {
            return None;
        }
        let address = Expr::new(
            ExprKind::AddrOf(super::place_of(
                PlaceKind::Object(object),
                ty,
                is_const,
                range,
            )),
            self.ptr_to(ty, is_const),
            range,
        );
        let arg = self.convert_for(
            address,
            param,
            super::ConvContext::Argument {
                index: 1,
                func: fname,
            },
        );
        let call = Expr::new(
            ExprKind::Call {
                callee: ir::Callee::Direct(func),
                args: vec![arg],
            },
            sig.ret,
            range,
        );
        self.cleanup_depth += 1;
        // The guard holds the function as an `extern "C" fn` pointer.
        self.program.functions[func.0 as usize].address_taken = true;
        Some(Stmt::Cleanup(Box::new(ir::CleanupDef {
            object,
            func,
            param,
            call,
            range: cleanup.range,
        })))
    }

    /// Refuses `[[cinrs::safe]]` where there is no function *definition* for it
    /// to apply to.
    ///
    /// Safety is a property of a body: the attribute makes the generated item
    /// an ordinary `extern "C" fn` whose statements `rustc` checks. A
    /// `typedef`, an object of function pointer type and any other declaration
    /// has no body to check, and a call *through* such a type is unsafe in Rust
    /// whatever the attribute says — so writing it there would promise
    /// something that is not delivered.
    pub(super) fn reject_safe(&mut self, attrs: &ast::Attributes, what: &str) {
        if let Some(range) = attrs.safe {
            self.error(
                range,
                format!(
                    "'safe' is not allowed on {what}: it applies to a function definition, \
                     whose body is what is checked"
                ),
            );
        }
    }

    /// Reports a `cleanup` attribute somewhere it cannot mean anything.
    ///
    /// GCC drops it with "'cleanup' attribute ignored"; ignoring it here would
    /// change what the program does, so it is refused with the reason instead.
    pub(super) fn reject_cleanup(&mut self, attrs: &ast::Attributes, what: &str) {
        if let Some(cleanup) = &attrs.cleanup {
            self.error(
                cleanup.range,
                format!(
                    "'cleanup' attribute ignored on {what}: it calls the function when the \
                     object goes out of scope, and only an object with automatic storage \
                     duration ever does"
                ),
            );
        }
    }

    /// Refuses `__attribute__((weak))` where it would mean something.
    ///
    /// Weak linkage is two things at once: a *definition* the linker may
    /// replace with a strong one, and a *reference* that may go unresolved and
    /// whose address is then null. Neither is expressible in stable Rust —
    /// `#[linkage]` is unstable — so the definition is refused with the reason.
    ///
    /// A plain declaration is another matter: the only thing lost is the null
    /// address, the call itself is exactly the call a strong declaration makes,
    /// and refusing it would make glibc's `<pthread.h>` unreadable over one
    /// internal function nobody calls. So it is accepted, and
    /// `__has_attribute(weak)` still answers *no*, which is what keeps a
    /// program that guards on the answer from taking the branch that tests the
    /// address; see [`crate::gnu::has_attribute`].
    pub(super) fn reject_weak(&mut self, attrs: &ast::Attributes, what: &str) {
        if let Some(range) = attrs.weak {
            self.error(
                range,
                format!(
                    "'weak' is not supported on {what}: Rust's `#[linkage]` is unstable, so weak \
                     linkage cannot be asked for. Only a declaration of something defined \
                     elsewhere may carry it, where it is accepted and ignored — the symbol then \
                     having to be there at link time"
                ),
            );
        }
    }

    /// Checks a `_Thread_local` object declaration (C11 6.7.1).
    ///
    /// The three spellings — `_Thread_local`, C23's `thread_local` and GNU's
    /// `__thread` — mean the same thing, and the parser has already gated the
    /// two that a revision introduced. What is left is where the specifier may
    /// appear and what this crate can generate for it:
    ///
    /// * at block scope it needs `static` or `extern` (6.7.1p3), because an
    ///   object with automatic storage duration is per *call*, not per thread;
    /// * `extern` is refused: naming a TLS symbol another object file defines
    ///   needs Rust's `#[thread_local]` on an `extern` item, which is unstable;
    /// * a function is not an object (6.7.1p4);
    /// * and the object's initialiser must be a constant expression, which the
    ///   static-initialiser path enforces on its own.
    ///
    /// [`ThreadLocal::Rejected`] means the declaration was reported and the
    /// caller should register the name as an error and stop.
    fn check_thread_local(
        &mut self,
        decl: &ast::Decl,
        storage: Option<ast::StorageClass>,
        file_scope: bool,
    ) -> ThreadLocal {
        let Some(range) = decl.specifiers.thread_local else {
            return ThreadLocal::No;
        };
        if storage == Some(ast::StorageClass::Extern) {
            self.error(
                range,
                "an 'extern' thread-local object is not supported: reaching a TLS symbol \
                 defined elsewhere needs Rust's `#[thread_local]`, which is unstable. \
                 Define the object in this unit instead",
            );
            return ThreadLocal::Rejected;
        }
        if matches!(
            storage,
            Some(ast::StorageClass::Auto | ast::StorageClass::Register)
        ) {
            self.error(
                range,
                "'_Thread_local' cannot be combined with 'auto' or 'register'; it goes with \
                 'static' or 'extern', or on its own at file scope",
            );
            return ThreadLocal::Rejected;
        }
        if storage == Some(ast::StorageClass::Constexpr) {
            self.error(
                range,
                "'_Thread_local' cannot be combined with 'constexpr'; a constant has no \
                 storage to give a thread a copy of",
            );
            return ThreadLocal::Rejected;
        }
        if !file_scope && storage != Some(ast::StorageClass::Static) {
            // C11 6.7.1p3. GCC says the same thing in the same place.
            self.error(
                range,
                "'_Thread_local' on a block-scope object needs 'static' or 'extern': the \
                 object has static storage duration, one copy per thread",
            );
            return ThreadLocal::Rejected;
        }
        // A variably modified type needs nothing here: the object has static
        // storage duration either way, and the variable-length-array path
        // already says so in more useful words.
        ThreadLocal::Yes
    }

    /// Declares an object of variably modified type: `T a[n];`, `T a[n][m];`
    /// (C99 6.7.5.2).
    ///
    /// The elements are one allocation off the function's bump arena —
    /// however many dimensions there are — and the object itself is a pointer
    /// to it; see [`ir::VlaDef`].
    /// `bounds` are the statements that bind the hidden length objects the
    /// type carries, which have to run before the allocation does. Everything
    /// C forbids about such a declaration is reported here, because a
    /// block-scope object with automatic storage duration is the only place a
    /// variably modified *object* is allowed to reach at all.
    fn declare_vla(
        &mut self,
        name: &ast::Ident,
        decl: &ast::Decl,
        declarator: &ast::InitDeclarator,
        ty: Ty,
        bounds: Vec<Stmt>,
        file_scope: bool,
    ) -> Vec<Stmt> {
        // C99 6.7.5.2 introduced them (N683), so a `c89!` block is told to
        // write a different macro rather than being told the bound is not a
        // constant expression.
        self.require_standard(
            crate::Standard::C99,
            "a variable length array",
            declarator.range,
        );
        let storage = decl.specifiers.storage.as_ref().map(|s| s.node);
        let unknown = self.types().vm_dims(ty).contains(&ir::VmDim::Unknown);
        let problem = if file_scope || storage == Some(ast::StorageClass::Static) {
            // An object with static storage duration is an item whose size the
            // linker has to know, and there is no moment at which the bound
            // could be evaluated.
            Some("a variable length array cannot have static storage duration".to_owned())
        } else if declarator.init.is_some() {
            // C99 6.7.8p3: there would be nothing to check the number of
            // initialisers against.
            Some("a variable length array cannot have an initializer".to_owned())
        } else if unknown {
            // The type arrived from somewhere that carries no bound with it:
            // `int a[*]`, or `typeof` of a parameter declared in a prototype.
            Some(
                "the length of this variably modified type is not available here: \
                 its bound was never evaluated"
                    .to_owned(),
            )
        } else {
            None
        };
        if let Some(message) = problem {
            self.error(declarator.range, message);
            // The name is still declared, as something already reported, so
            // that using it adds nothing to the diagnostics.
            self.check_redefinition(name);
            let id = self.new_object(&name.name, Ty::Error, Storage::Automatic, false, name.range);
            self.insert(&name.name, Entry::Object(id));
            return Vec::new();
        }

        let is_const = declarator.ty.qualifiers.is_const;
        self.check_redefinition(name);
        self.refuse_float128_object(&name.name, ty, name.range);
        let object = self.new_object(&name.name, ty, Storage::Automatic, is_const, name.range);
        self.insert(&name.name, Entry::Object(object));
        // The frame is not an object of the C program; its type is what is
        // left under the variable dimensions — the type the arena hands out —
        // and code generation knows to spell the binding as the arena's frame.
        let elem = self.types().vm_step_ty(ty);
        self.func_uses_arena = true;
        let storage = self.new_object(
            &format!("__cinrs_vla_frame_{}", name.name),
            elem,
            Storage::Automatic,
            false,
            name.range,
        );
        self.program.objects[storage.0 as usize].vla_storage = true;
        let count = self
            .vm_count(ty, Vec::new(), declarator.range, declarator.range)
            .expect("every dimension has a length object");
        let mut out = bounds;
        out.push(Stmt::Vla(Box::new(ir::VlaDef {
            object,
            storage,
            count,
            align: None,
            range: declarator.range,
        })));
        out
    }

    /// Puts what `__asm__("symbol")` and `__attribute__((section("…")))`
    /// asked for onto an object with static storage duration.
    fn apply_object_attributes(
        &mut self,
        id: ObjectId,
        attrs: &ast::Attributes,
        declarator: &ast::InitDeclarator,
    ) {
        // A thread-local object is a `thread_local!` item rather than a
        // `static`, and neither of these has anywhere to go on one: a
        // `link_section` and a symbol name both describe a linker symbol that
        // a `thread_local!` does not have.
        if self.program.object(id).storage.is_thread_local() {
            for range in [
                declarator.asm_label.as_ref().map(|label| label.range),
                attrs.section.as_ref().map(|section| section.range),
            ]
            .into_iter()
            .flatten()
            {
                self.error(
                    range,
                    "a '_Thread_local' object has no linker symbol to name or to place in a \
                     section: it becomes a `thread_local!` item",
                );
            }
            return;
        }
        if let Some(label) = &declarator.asm_label {
            self.program.objects[id.0 as usize].asm_label = Some(label.node.clone());
        }
        if let Some(section) = &attrs.section {
            self.program.objects[id.0 as usize].section = Some(section.node.clone());
        }
    }

    /// Reports an `_Alignas` on one of the declarations C11 6.7.5p2 forbids it
    /// in: "a typedef, or a bit-field, or a function, or a parameter, or an
    /// object declared with the `register` storage-class specifier".
    ///
    /// Only the `_Alignas` spelling: GCC's `aligned` attribute is *allowed* on
    /// a `typedef` and on a function, and each of those has an answer of its
    /// own — [`Sema::align_typedef_record`](super::Sema::align_typedef_record)
    /// for the one shape a `typedef` can carry, and a diagnostic of its own
    /// for a function, Rust having no way to align code.
    fn reject_alignas(&mut self, specifiers: &ast::DeclSpecifiers, what: &str) {
        let Some(spec) = specifiers.alignas.iter().find(|s| !s.from_attribute) else {
            return;
        };
        self.error(
            spec.range,
            format!("an alignment specifier is not allowed on {what}"),
        );
    }

    /// What the alignment specifiers of one declarator ask for, together.
    ///
    /// The strictest of them wins (C11 6.7.5p6), whether they were spelled
    /// `_Alignas` or `aligned` and whether they stood among the declaration
    /// specifiers or on the declarator; see
    /// [`Sema::strictest_alignment`](super::Sema::strictest_alignment), which
    /// is the same fold a record's member goes through.
    ///
    /// [`AlignRequest::standard`] records whether an `_Alignas` is among them,
    /// because the two spellings differ on one point and only one: an
    /// `_Alignas` weaker than the type's own alignment is a constraint
    /// violation (6.7.5p4), while GCC's `aligned` "can only increase
    /// alignment" and a weaker one is simply not applied.
    fn align_request(
        &mut self,
        specifiers: &ast::DeclSpecifiers,
        attrs: &ast::Attributes,
    ) -> Option<AlignRequest> {
        let standard = specifiers.alignas.iter().any(|spec| !spec.from_attribute);
        let (want, spec) = self.strictest_alignment(&specifiers.alignas, attrs.aligned.as_ref())?;
        Some(AlignRequest {
            want,
            range: spec.range,
            standard,
        })
    }

    /// Gives an object the alignment its declaration asked for.
    ///
    /// Nothing is recorded when the request is no stricter than the alignment
    /// the type already has: there would be nothing for the generated wrapper
    /// to say, and `_Alignof` answers the same either way. A *weaker* one is
    /// C11 6.7.5p4's constraint violation when it was spelled `_Alignas`, and
    /// GCC's silent no-op when it was spelled `aligned`; see
    /// [`Sema::align_request`].
    fn apply_object_alignment(&mut self, id: ObjectId, ty: Ty, requested: Option<AlignRequest>) {
        let Some(request) = requested else { return };
        if ty.is_error() {
            return;
        }
        let natural = self.natural_align(ty).unwrap_or(1);
        if request.want < natural {
            if request.standard {
                self.error(
                    request.range,
                    format!(
                        "the requested alignment {} is weaker than the alignment {natural} \
                         that '{}' already has",
                        request.want,
                        self.tyname(ty)
                    ),
                );
            }
            return;
        }
        if request.want == natural {
            return;
        }
        // Several declarations of one file-scope object each get a say, and
        // the strictest of them wins, exactly as several specifiers on one
        // declaration do.
        let slot = &mut self.program.objects[id.0 as usize].align;
        *slot = Some(slot.unwrap_or(0).max(request.want));
    }

    /// The alignment a type has of its own.
    ///
    /// An array's is its element's, which is also the answer for the one array
    /// whose length is not known yet — a tentative definition's `int a[];`.
    fn natural_align(&self, ty: Ty) -> Option<u64> {
        if let Ty::Array(id) = ty {
            let elem = self.types().array_type(id).elem;
            return self.natural_align(elem);
        }
        self.types()
            .size_align(ty, &self.target)
            .map(|layout| layout.align)
    }

    /// Declares a C23 `constexpr` object.
    ///
    /// The object becomes a *constant* rather than storage: every use of the
    /// name is folded to its value, which is what makes it usable as an array
    /// bound or a `case` label. The cost — and the reason only arithmetic
    /// objects are accepted — is that there is nothing to take the address of.
    fn declare_constexpr(
        &mut self,
        name: &ast::Ident,
        ty: Ty,
        init: Option<Expr>,
        declarator: &ast::InitDeclarator,
    ) {
        if ty.is_error() {
            return;
        }
        let Some(init) = init else {
            self.error(
                declarator.range,
                format!(
                    "'{}' is declared 'constexpr' and needs an initializer",
                    name.name
                ),
            );
            return;
        };
        if !ty.is_arithmetic() {
            self.error(
                declarator.range,
                format!(
                    "a 'constexpr' object of type '{}' is not supported yet; only the \
                     arithmetic types are",
                    self.tyname(ty)
                ),
            );
            return;
        }
        let Some(value) = self.const_eval_at(&init, "the initializer of a 'constexpr' object")
        else {
            return;
        };
        self.check_redefinition(name);
        self.insert(
            &name.name,
            Entry::Constant {
                value,
                ty,
                range: name.range,
            },
        );
    }

    /// Checks the initialiser of a declarator whose type came from the
    /// declarator alone, after the object has been declared.
    ///
    /// See [`Sema::declarator`] for why the two are in that order. The
    /// [`type_from_initializer`] forms have already had theirs checked by
    /// [`Sema::typed_initializer`] and never reach here.
    fn late_initializer(
        &mut self,
        declarator: &ast::InitDeclarator,
        ty: Ty,
        name: &str,
    ) -> Option<Expr> {
        let init = declarator.init.as_ref()?;
        // A variable length array may not have one at all (C99 6.7.8p3);
        // `Sema::declare_vla` says so, and checking a list against a length
        // nobody knows would only add noise on top. A type that did not check
        // out has already been reported.
        if ty.is_error() || self.types().is_vm(ty) {
            return None;
        }
        self.initializer(init, ty, name)
    }

    /// Resolves a declarator's type and its initialiser together.
    ///
    /// They cannot be separated: `char s[] = "hi"` takes the array's length
    /// from the initialiser, and the initialiser needs the element type. Only
    /// the [`type_from_initializer`] forms come here; everything else resolves
    /// its type first, so that the object is in scope for its own initialiser.
    /// `auto *ptr = &a;` — Clang's extension, where the deduction happens
    /// through a run of pointer derivations.
    ///
    /// The type the declarator asks for is `T` under `depth` pointers, so the
    /// object's type is simply the initialiser's *own* type as long as it has
    /// that many levels to peel; what is deduced is what is left under them.
    /// See [`auto_pointer_depth`].
    fn auto_through_pointers(
        &mut self,
        declarator: &ast::InitDeclarator,
        name: &str,
        depth: usize,
    ) -> Option<(Ty, Option<Expr>)> {
        let init = declarator.init.as_ref()?;
        let ast::InitializerKind::Expr(expr) = &init.kind else {
            self.error(
                init.range,
                format!("the type of '{name}' cannot be inferred from a braced initializer"),
            );
            return None;
        };
        let stars = "*".repeat(depth);
        let value = self.underspecified(name, |sema| sema.expr(expr))?;
        let mut peeled = value.ty;
        for _ in 0..depth {
            match self.pointee(peeled) {
                Some(inner) => peeled = inner,
                None => {
                    self.error(
                        expr.range,
                        format!(
                            "'{name}', of type 'auto {stars}', has an incompatible initializer \
                             of type '{}'",
                            self.tyname(value.ty)
                        ),
                    );
                    return None;
                }
            }
        }
        if peeled.is_error() {
            return None;
        }
        Some((value.ty, Some(value)))
    }

    /// Checks something with the name of an **underspecified** declaration —
    /// C23's `auto x = e;` — recorded, so that naming it inside its own
    /// initialiser is refused rather than resolving to whatever an enclosing
    /// scope had.
    ///
    /// The identifier is in scope for its own initialiser (6.2.1p7), and for
    /// an inferred type there is nothing for it to name: `double b = 9; {
    /// auto b = b * b; }` is a constraint violation and not a use of the outer
    /// `b`, which is what `C23/n3007.c` checks and what GCC calls
    /// "underspecified 'b' referenced in its initializer".
    fn underspecified<T>(&mut self, name: &str, f: impl FnOnce(&mut Self) -> T) -> T {
        let outer = self.underspecified.replace(name.to_owned());
        let out = f(self);
        self.underspecified = outer;
        out
    }

    fn typed_initializer(
        &mut self,
        declarator: &ast::InitDeclarator,
        name: &str,
    ) -> Option<(Ty, Option<Expr>)> {
        if let Some(depth) = auto_pointer_depth(&declarator.ty) {
            return self.auto_through_pointers(declarator, name, depth);
        }
        // C23's `auto x = e;`: the type is whatever the initialiser has after
        // the lvalue conversion, which is exactly what checking it gives.
        if matches!(declarator.ty.kind, ast::TypeKind::Auto) {
            let Some(init) = &declarator.init else {
                self.error(
                    declarator.range,
                    format!("'{name}' is declared 'auto' and needs an initializer"),
                );
                return None;
            };
            let ast::InitializerKind::Expr(expr) = &init.kind else {
                self.error(
                    init.range,
                    format!("the type of '{name}' cannot be inferred from a braced initializer"),
                );
                return None;
            };
            let value = self.underspecified(name, |sema| sema.expr(expr))?;
            if value.ty.is_void() || value.ty.is_error() {
                self.error(
                    expr.range,
                    format!(
                        "the type of '{name}' cannot be inferred from an expression of type \
                         '{}'",
                        self.tyname(value.ty)
                    ),
                );
                return None;
            }
            // `_Atomic auto x = 12;` is `_Atomic int`: N3007 keeps `_Atomic`
            // out of the "no other type specifier beside `auto`" rule
            // precisely because in this spelling it is a *qualifier*, and it
            // is the one qualifier an inferred type has to carry itself —
            // `const` and `volatile` live on the object. `_Atomic(auto)`, the
            // specifier spelling, is a different thing and is refused where
            // every other use of `auto` in a type name is.
            if declarator.ty.qualifiers.is_atomic {
                return match self.make_atomic(value.ty, declarator.ty.range) {
                    Ok(ty) => {
                        let value = self.convert_for(value, ty, ConvContext::Init(name.to_owned()));
                        Some((ty, Some(value)))
                    }
                    Err(err) => {
                        self.report_type_error(err);
                        None
                    }
                };
            }
            return Some((value.ty, Some(value)));
        }

        if let ast::TypeKind::Array {
            elem,
            size: ast::ArraySize::Unspecified,
            ..
        } = &declarator.ty.kind
        {
            let element = self.ty_of(elem)?;
            if self.types().is_vm(element) {
                // `int x[][n] = { … }`: the number of elements would have to
                // come from the initialiser, and a variably modified object
                // may not have one at all (C99 6.7.8p3).
                self.error(
                    declarator.ty.range,
                    "a variable length array cannot have an initializer",
                );
                return None;
            }
            let elem_const = elem.qualifiers.is_const;
            // Without one the type is an *incomplete* array type, which is a
            // type rather than a mistake; `Sema::declarator` never sends such
            // a declarator here.
            let init = declarator
                .init
                .as_ref()
                .expect("`type_from_initializer` requires one");
            let (ty, expr) = self.init_array_inferred(init, element, elem_const, name)?;
            return Some((ty, Some(expr)));
        }

        unreachable!("only the `type_from_initializer` forms reach here")
    }

    /// Declares a file-scope object or a function-local `static`, *without*
    /// its initialiser.
    ///
    /// The object exists before the initialiser is checked, because C99
    /// 6.2.1p7 puts its name in scope from the end of its declarator and a
    /// static initialiser is where that matters most: `struct list head = {
    /// &head, &head }` is an address constant naming the object it
    /// initialises. It starts out with the zero C gives static storage, and
    /// [`Sema::initialize_static_object`] replaces that with the value the
    /// declaration wrote. `None` means there is nothing to give a value to —
    /// no initialiser, or a declaration that did not check out.
    #[allow(clippy::too_many_arguments)]
    fn declare_static_object(
        &mut self,
        name: &ast::Ident,
        ty: Ty,
        is_const: bool,
        is_static: bool,
        file_scope: bool,
        thread_local: bool,
        declarator: &ast::InitDeclarator,
    ) -> Option<ObjectId> {
        // C99 6.9.2: a file-scope declaration without an initialiser is a
        // *tentative* definition, and repeating one — or completing it with an
        // initialiser later — is perfectly ordinary C.
        // The composite type is what a second declaration leaves behind
        // (6.2.7p4), which is how `int j[]; int j[3];` ends up with a size.
        let composite = match self.declared_here(&name.name).cloned() {
            Some(Entry::Object(existing)) if file_scope => {
                let declared = self.visible_object_ty(existing);
                self.composite_object_ty(declared, ty)
            }
            _ => None,
        };
        if file_scope
            && let Some(composite) = composite
            && let Some(Entry::Object(existing)) = self.declared_here(&name.name).cloned()
        {
            self.retype_object(existing, composite, declarator);
            self.note_object_ty(existing, composite);
            // C11 6.7.1p3: if `_Thread_local` appears in any declaration of an
            // object it has to appear in every one. Letting the two disagree
            // would silently give the object whichever storage the *first*
            // declaration asked for.
            if thread_local != self.program.object(existing).storage.is_thread_local() {
                let previous = self.program.object(existing).range;
                self.error_note(
                    name.range,
                    format!(
                        "'{}' is declared '_Thread_local' here but not there; the specifier \
                         has to be on every declaration of an object",
                        name.name
                    ),
                    previous,
                    format!("previous declaration of '{}' is", name.name),
                );
                return None;
            }
            return self.complete_tentative_definition(name, existing, declarator, !is_static);
        }

        self.check_redefinition(name);
        if ty.is_error() {
            // The declaration was already reported; the name is registered so
            // that using it does not produce a second diagnostic, but there is
            // nothing to generate an item from.
            let id = self.new_object(&name.name, ty, Storage::Automatic, is_const, name.range);
            self.insert(&name.name, Entry::Object(id));
            return None;
        }
        let base = if file_scope {
            name.name.clone()
        } else {
            // Two functions may each have a `static` under the same name, and
            // so may two `c99!` blocks in one Rust module.
            format!(
                "__cinrs_static_{:08x}_{}_{}",
                self.program.unit_id as u32, self.func_name, name.name
            )
        };
        let item_name = self.reserve_item_name(&base);
        let exported = file_scope && !is_static;
        let storage = if thread_local {
            Storage::ThreadLocal {
                item_name,
                exported,
            }
        } else {
            Storage::Static {
                item_name,
                exported,
            }
        };
        self.refuse_float128_object(&name.name, ty, name.range);
        let id = self.new_object(&name.name, ty, storage, is_const, name.range);
        self.insert(&name.name, Entry::Object(id));
        if file_scope {
            // An identifier with linkage carries the type of the declaration
            // it was named through rather than the object's; see
            // [`Scope::composites`].
            self.note_object_ty(id, ty);
        }

        // C zero-initialises static storage; an initialiser, if written, must
        // be a constant expression, and replaces the zero once it has been
        // checked.
        let init = self.zero(ty, declarator.range);
        if declarator.init.is_some() {
            self.initialized.insert(id);
        }
        self.program.statics.push(StaticVar { object: id, init });
        declarator.init.is_some().then_some(id)
    }

    /// The composite of two declarations of one object (C99 6.2.7p4), or
    /// `None` when the two types are not compatible at all.
    ///
    /// The one case where the composite is neither of the two spellings is an
    /// array: the composite of a completed array type and an incomplete one is
    /// the *completed* one, which is what makes `extern int j[]; int j[3];`
    /// declare one object whose size this unit knows.
    fn composite_object_ty(&mut self, declared: Ty, again: Ty) -> Option<Ty> {
        if declared == again {
            return Some(declared);
        }
        if !self.compatible(declared, again) {
            return None;
        }
        if self.types().is_incomplete_array(declared) {
            return Some(again);
        }
        Some(declared)
    }

    /// Gives an already-declared object the composite type a redeclaration
    /// left it with, and the zero of that type if it is waiting for one.
    fn retype_object(&mut self, id: ObjectId, ty: Ty, declarator: &ast::InitDeclarator) {
        if self.program.object(id).ty == ty {
            return;
        }
        self.program.objects[id.0 as usize].ty = ty;
        let zero = self.zero(ty, declarator.range);
        if !self.initialized.contains(&id)
            && let Some(entry) = self.program.statics.iter_mut().find(|s| s.object == id)
        {
            entry.init = zero;
        }
    }

    /// Gives an object with static storage duration the value its initialiser
    /// says, which C99 6.7.8p4 requires to be a constant expression.
    fn initialize_static_object(
        &mut self,
        id: ObjectId,
        declarator: &ast::InitDeclarator,
        init: Expr,
    ) {
        let ty = self.program.object(id).ty;
        let value = self
            .static_init(init, "initializer")
            .unwrap_or_else(|| self.zero(ty, declarator.range));
        // An initialised flexible array member makes the *object* larger than
        // its type; the item is generated with a companion type whose tail is
        // that long. See [`ir::Object::flexible_len`].
        if let Some(len) = self.flexible_tail_of(&value) {
            self.program.objects[id.0 as usize].flexible_len = Some(len);
        }
        if let Some(entry) = self.program.statics.iter_mut().find(|s| s.object == id) {
            entry.init = value;
        }
    }

    /// How many elements an initialiser gave a record's flexible array member,
    /// when it gave it any.
    fn flexible_tail_of(&self, value: &Expr) -> Option<u64> {
        let ExprKind::RecordLit { record, fields } = &value.kind else {
            return None;
        };
        let def = self.types().record(*record);
        if !def.flexible {
            return None;
        }
        let tail = fields.last()?;
        let Ty::Array(id) = tail.ty else {
            return None;
        };
        let len = self.types().array_type(id).len;
        (len > 0).then_some(len)
    }

    /// Handles a repeated file-scope declaration of the same object.
    ///
    /// `int n; int n = 1;` declares one object twice and initialises it once,
    /// which C allows; a second initialiser does not. The object to give the
    /// initialiser to comes back, or `None` when this declaration wrote none
    /// or is the second one that did.
    fn complete_tentative_definition(
        &mut self,
        name: &ast::Ident,
        id: ObjectId,
        declarator: &ast::InitDeclarator,
        defines: bool,
    ) -> Option<ObjectId> {
        // C99 6.9.2p2: a file-scope declaration with no storage-class
        // specifier is a definition of the object — a *tentative* one when it
        // has no initialiser, which the end of the translation unit turns into
        // a definition with a zero initialiser. An earlier `extern` only said
        // that the name has external linkage; it does not stop this unit
        // defining it, so `extern int x; int x;` defines `x` here and the
        // declaration has to stop being an external one. `static` is the
        // storage class that does *not* define anything on its own, and it is
        // the only one that reaches here.
        if defines {
            self.define_here(id, declarator);
        }
        declarator.init.as_ref()?;
        if !self.initialized.insert(id) {
            let previous = self.program.object(id).range;
            self.error_note(
                name.range,
                format!("redefinition of '{}'", name.name),
                previous,
                format!("previous definition of '{}' is", name.name),
            );
            return None;
        }
        Some(id)
    }

    /// Turns an object this unit only *declared* into one it defines.
    ///
    /// `extern int x;` puts `x` in the generated `extern` block, where the
    /// linker is expected to find it elsewhere. A later declaration of the
    /// same name without a storage class is a definition (C99 6.9.2p2), so the
    /// object moves out of the `extern` block and becomes a `static mut` item
    /// with the zero C gives an object with static storage duration; an
    /// initialiser, if the declaration wrote one, replaces that zero
    /// afterwards. Doing nothing at all is what left `extern int x; int x;`
    /// with an undefined symbol at link time.
    fn define_here(&mut self, id: ObjectId, declarator: &ast::InitDeclarator) {
        if !matches!(self.program.object(id).storage, Storage::Extern { .. }) {
            return;
        }
        let ty = self.program.object(id).ty;
        let name = self.program.object(id).name.clone();
        let item_name = self.reserve_item_name(&name);
        self.program.objects[id.0 as usize].storage = Storage::Static {
            item_name,
            exported: true,
        };
        self.program.externs.retain(|e| *e != id);
        let init = self.zero(ty, declarator.range);
        self.program.statics.push(StaticVar { object: id, init });
    }

    /// Declares an object defined outside the translation unit.
    fn declare_extern_object(&mut self, name: &ast::Ident, declarator: &ast::InitDeclarator) {
        // `extern int j[];` is the canonical incomplete array type, and
        // `extern struct incomplete es;` (WG14 DR047) is the same rule for a
        // tag: the object is defined in another unit, so neither its size nor
        // the completeness of its type is any of this one's business
        // (6.2.5p22), and only its address is ever taken here.
        let Some(ty) = self.declared_object_ty_of(&declarator.ty, &name.name, Completeness::Any)
        else {
            return;
        };
        if self.types().is_vm(ty) {
            self.error(
                declarator.range,
                "a variable length array cannot have static storage duration",
            );
            return;
        }
        if let Some(init) = &declarator.init {
            self.error(
                init.range,
                format!(
                    "'{}' is declared 'extern' and cannot have an initializer here",
                    name.name
                ),
            );
        }
        // The declaration a redeclaration has to agree with is the one with
        // *linkage*, which lives at file scope: `int v = 4; { extern int v; }`
        // names the file-scope `v` and not the local one (C99 6.2.2p4), since
        // a block-scope object declared without `extern` has no linkage at
        // all.
        if let Some(Entry::Object(existing)) = self.lookup_linked(&name.name).cloned() {
            // The type to compose with is the one *visible here* rather than
            // the object's, which may already carry a composite an inner block
            // elsewhere gave it and which C would not have shown this
            // declaration (6.2.7p4).
            let declared = self.visible_object_ty(existing);
            if let Some(composite) = self.composite_object_ty(declared, ty) {
                self.retype_object(existing, composite, declarator);
                // The composite lasts to the end of *this* scope only, so a
                // `sizeof` after the block sees the outer declaration's type
                // again — WG14 DR011.
                self.note_object_ty(existing, composite);
                self.insert(&name.name, Entry::Object(existing));
                return;
            }
            let previous = self.program.object(existing).range;
            self.error_note(
                name.range,
                format!("redeclaration of '{}' with a different type", name.name),
                previous,
                format!("previous declaration of '{}' is", name.name),
            );
            return;
        }
        let id = self.new_object(
            &name.name,
            ty,
            Storage::Extern {
                item_name: name.name.clone(),
            },
            declarator.ty.qualifiers.is_const,
            name.range,
        );
        self.program.externs.push(id);
        // An `extern` declaration names an object with external linkage
        // wherever it is written, so the name belongs in the file scope.
        self.insert_at_file_scope(&name.name, Entry::Object(id));
        self.insert(&name.name, Entry::Object(id));
        self.note_object_ty(id, ty);
    }

    // -- typedef ------------------------------------------------------------

    fn declare_typedef(
        &mut self,
        name: &ast::Ident,
        ty: &ast::Type,
        init: Option<&ast::Initializer>,
        attrs: &ast::Attributes,
    ) -> Vec<Stmt> {
        if let Some(init) = init {
            self.error(init.range, "a 'typedef' cannot have an initializer");
        }
        // A `typedef` *stores* the reason its type would not resolve and
        // reports it where the name is used, which is right for a type that is
        // merely unavailable here. `auto` in a parameter is a mistake in the
        // declaration itself and has no use to wait for, so it is reported
        // where it stands — `C23/n3007.c`'s `typedef void (*fp)(auto);`.
        if let Some(range) = auto_in_prototype(ty) {
            self.error(range, "'auto' is not allowed in a function prototype");
        }
        let file_scope = self.at_file_scope();
        // `typedef int A[n];` is a variably modified type, and C99 6.7.7p4
        // says the bound is evaluated *here*, once, however many objects `A`
        // later declares. That needs an object to keep the length in, which is
        // what `BoundMode::Object` asks for; at file scope there is no moment
        // at which the bound could be evaluated at all.
        let resolved = match self.resolve_declared_ty(ty, &name.name) {
            Ok(ty) => Ok(self.apply_mode(ty, attrs)),
            Err(err) if err.message.is_empty() => return Vec::new(),
            Err(err) => Err(err.message),
        };
        let mut out = self.take_vm_bounds();
        if let Ok(resolved) = resolved
            && self.types().is_vm(resolved)
            && file_scope
        {
            self.error(
                ty.range,
                format!("variably modified '{}' at file scope", name.name),
            );
            out.clear();
        }
        // `typedef struct { … } T __attribute__((aligned(N)));` asks for a
        // stricter alignment than the members give; see
        // `Sema::align_typedef_record`.
        //
        // On a `typedef` of a scalar or a pointer, GCC makes a new variant of
        // the type whose alignment is N — weaker than its own included, which
        // is the one attribute that *lowers* an alignment: xxHash's
        // `typedef __attribute__((aligned(1))) xxh_u64 xxh_unalign64;` is a
        // `uint64_t` that may be at any address, and reads through a
        // `xxh_unalign64 *` are unaligned loads. A `typedef` of another
        // `typedef` that has one keeps it unless it says otherwise.
        let mut align = self.typedef_align(ty);
        if let Ok(resolved) = &resolved
            && let Some(aligned) = attrs.aligned.clone()
            && let Some(want) = self.alignment_of(Some(&aligned))
        {
            let resolved = *resolved;
            let natural = self
                .types()
                .size_align(resolved, &self.target)
                .map(|layout| layout.align);
            let scalar = resolved.is_arithmetic()
                || resolved.is_pointer()
                || matches!(resolved, Ty::Enum(_));
            if matches!(resolved, Ty::Atomic(_)) && natural.is_some_and(|n| want < n) {
                self.error(
                    aligned.range,
                    "an '_Atomic' type cannot be given a weaker alignment: there is no \
                     unaligned atomic access",
                );
            } else if scalar {
                align = (natural != Some(want)).then_some(want);
            } else if natural.is_some_and(|n| want < n) {
                self.error(
                    aligned.range,
                    format!(
                        "'aligned({want})' on a 'typedef' of '{}' would make it less aligned \
                         than its type, which is supported for a scalar or a pointer 'typedef' \
                         only",
                        self.types().name(resolved)
                    ),
                );
            } else {
                self.align_typedef_record(resolved, want, aligned.range);
            }
        }
        let already = self.declared_here(&name.name).is_some();
        if already {
            // Repeating a `typedef` is a C11 relaxation that GCC accepts in
            // C99 mode too, so only a change of meaning is worth reporting.
            let same = matches!(
                self.declared_here(&name.name),
                Some(Entry::Typedef(entry)) if entry.resolved == resolved && entry.align == align
            );
            if !same {
                self.check_redefinition(name);
            }
        }
        self.insert(
            &name.name,
            Entry::Typedef(TypedefEntry {
                resolved: resolved.clone(),
                range: name.range,
                align,
            }),
        );

        // Only a file-scope `typedef` becomes an item Rust code can use; one
        // inside a block is resolved and forgotten, exactly as C does.
        if !file_scope || already {
            return out;
        }
        let Ok(resolved) = resolved else { return out };
        if self.claim_anonymous_tag(resolved, &name.name) {
            return out;
        }
        // `typedef struct Point { … } Point;` is the commonest idiom in C, and
        // the tag already generated a Rust type of exactly that name; an alias
        // would only be a second name for it.
        let same_name = match resolved {
            Ty::Record(id) => self.types().record(id).rust_name == name.name,
            Ty::Enum(id) => self.types().enum_def(id).rust_name == name.name,
            _ => false,
        };
        if same_name {
            return out;
        }
        let rust_name = self.reserve_item_name(&name.name);
        self.program.typedefs.push(TypedefItem {
            rust_name,
            ty: resolved,
            range: name.range,
        });
        out
    }

    /// Gives an anonymous `struct { … }` or `enum { … }` the name of the
    /// `typedef` that introduces it, the way C programmers intend it to be
    /// read.
    ///
    /// Returns whether the tag took the name, in which case no alias item is
    /// needed.
    fn claim_anonymous_tag(&mut self, ty: Ty, name: &str) -> bool {
        let anonymous = match ty {
            Ty::Record(id) => self.types().record(id).anonymous,
            Ty::Enum(id) => self.types().enum_def(id).anonymous,
            _ => false,
        };
        if !anonymous || !self.try_reserve_item_name(name) {
            return false;
        }
        match ty {
            Ty::Record(id) => {
                let record = self.program.types.record_mut(id);
                record.rust_name = name.to_owned();
                record.anonymous = false;
            }
            Ty::Enum(id) => {
                let def = self.program.types.enum_mut(id);
                def.rust_name = name.to_owned();
                def.anonymous = false;
            }
            _ => unreachable!("only tags can be anonymous"),
        }
        true
    }

    // -- functions ----------------------------------------------------------

    /// Evaluates the bounds of the array parameters of a definition, on entry
    /// and in declaration order (C99 6.9.1p10).
    ///
    /// Two things happen here. The *inner* dimensions of a variably modified
    /// parameter — the `m` of `void f(int n, int m, double a[n][m])` — are
    /// part of its adjusted type, `double (*)[m]`, and get a hidden object
    /// apiece, bound here, which is what makes `a[i][j]`, `sizeof a[0]` and
    /// `a + 1` mean anything in the body. The *outermost* one is not part of
    /// the type at all — the parameter is a pointer — so its value is thrown
    /// away and only its side effects are kept; a bound that plainly cannot do
    /// anything is left out, so that the overwhelmingly common
    /// `void f(int n, int a[n])` still generates nothing at all.
    fn parameter_size_effects(&mut self, func: &ast::FunctionType) -> Vec<Stmt> {
        // A compound literal written in a bound — `int g(char *p[f((int[27]){0})])`,
        // which is WG14 N2819's example — is an object of the function body's
        // outermost block, so its definition goes in front of everything, the
        // way `Sema::block_items` puts a block's own literals at its head.
        let enclosing = std::mem::take(&mut self.compound_literals);
        let mut out = Vec::new();
        for (index, param) in func.params.iter().enumerate() {
            // The bounds inside the declarator come first, innermost first,
            // which is the order GCC evaluates them in.
            if let Some(name) = &param.name {
                out.extend(self.variably_modified_param(param, index, &name.name));
            }
            let ast::TypeKind::Array {
                size: ast::ArraySize::Expr(size),
                ..
            } = &param.ty.kind
            else {
                continue;
            };
            let Some(value) = self.expr(size) else {
                continue;
            };
            let harmless = match &value.kind {
                ExprKind::Int(_) | ExprKind::Float(_) => true,
                ExprKind::Load(place) => matches!(place.kind, PlaceKind::Object(_)),
                _ => false,
            };
            if !harmless {
                out.push(Stmt::Expr(value));
            }
        }
        let literals = std::mem::replace(&mut self.compound_literals, enclosing);
        let mut prologue = Vec::with_capacity(literals.len() + out.len());
        for object in literals {
            let info = self.program.object(object);
            let (ty, range) = (info.ty, info.range);
            let init = self.zero(ty, range);
            prologue.push(Stmt::Let {
                object,
                init,
                explicit: false,
            });
        }
        prologue.append(&mut out);
        prologue
    }

    /// Re-resolves a definition's parameter type inside the *body's* scope,
    /// where its bounds can be evaluated and kept.
    ///
    /// The signature keeps the type the prototype gave it — a parameter's
    /// bound is not part of its type (C99 6.7.5.3p7), and any two variably
    /// modified types are compatible whatever their bounds — while the
    /// *object* the body sees is retyped with the lengths bound here. That is
    /// the whole of `void f(int n, int m, double a[n][m])`: `a` is a
    /// `double (*)[m]` whose `m` was read on entry and cannot change
    /// afterwards, however the body assigns to the parameter `m`.
    fn variably_modified_param(
        &mut self,
        param: &ast::ParamDecl,
        index: usize,
        name: &str,
    ) -> Vec<Stmt> {
        // Only an array or a pointer declarator can carry an inner bound, and
        // resolving anything else again would define a tag twice.
        if !matches!(
            param.ty.kind,
            ast::TypeKind::Array { .. } | ast::TypeKind::Pointer(_)
        ) {
            return Vec::new();
        }
        let Ok(ty) = self.resolve_param_ty_declared(&param.ty, name) else {
            // Whatever is wrong with it was reported when the signature was
            // built; this pass says nothing new.
            self.vm_bounds.clear();
            return Vec::new();
        };
        let bounds = self.take_vm_bounds();
        if bounds.is_empty() {
            return Vec::new();
        }
        // The parameter object was created from the signature's type; it is
        // the same type but for the bounds, which is exactly what has to
        // change.
        if let Some(object) = self.func_params.get(index).copied() {
            self.program.objects[object.0 as usize].ty = ty;
        }
        bounds
    }

    /// Resolves a parameter list, inside the prototype scope its names live
    /// in; `None` means the list was reported and there is no signature.
    fn declare_params(
        &mut self,
        func: &ast::FunctionType,
        definition: Option<&ast::FunctionDef>,
        param_tys: &mut Vec<Ty>,
        param_names: &mut Vec<Option<String>>,
    ) -> Option<()> {
        for param in &func.params {
            // A parameter is an object of automatic storage duration; neither
            // of these can apply to one.
            if let Some(storage) = &param.specifiers.storage
                && storage.node == ast::StorageClass::Constexpr
            {
                self.error(
                    storage.range,
                    format!("'{}' is not allowed on a parameter", storage.node.as_str()),
                );
            }
            if let Some(range) = param.specifiers.thread_local {
                self.error(range, "'_Thread_local' is not allowed on a parameter");
            }
            // C11 6.7.5p2 names the parameter as one of the five declarations
            // an alignment specifier may not appear in: the argument is placed
            // by the calling convention, which nothing here can change.
            if let Some(range) = param.specifiers.alignas.first().map(|spec| spec.range) {
                self.error(
                    range,
                    "an alignment specifier is not allowed on a parameter; the argument is \
                     placed by the calling convention",
                );
            }
            let ty = match self.resolve_param_ty(&param.ty) {
                Ok(ty) => ty,
                Err(err) => {
                    self.report_type_error(err);
                    return None;
                }
            };
            if ty.is_void() {
                // C99 6.7.5.3p10: a parameter list of one unnamed parameter of
                // type `void` is a prototype with *no* parameters. The parser
                // recognises the keyword spelling on its own; reaching `void`
                // through a `typedef` is DR157 part 1, and only sema can see
                // it — `typedef void V; int f(V);` is `int f(void)`.
                if func.params.len() == 1 && !func.variadic && param.name.is_none() {
                    param_tys.clear();
                    param_names.clear();
                    break;
                }
                self.error(param.range, "parameter has incomplete type 'void'");
                return None;
            }
            // C99 6.9.1p7: it is a *definition* whose parameters must have a
            // complete type. A declaration that is not one may mention a tag
            // this unit has not defined — `void f(struct S s);` before
            // `struct S` — because nothing here has to know its size; `drs`
            // DR103 is exactly that question, and GCC and Clang both accept
            // it with only a warning about the tag's scope.
            if definition.is_some() && !self.types().is_complete(ty) {
                self.error(
                    param.range,
                    format!("parameter has incomplete type '{}'", self.tyname(ty)),
                );
                return None;
            }
            // C23 N2480 lets a parameter of a *definition* go unnamed, exactly
            // as C++ always has; GCC and Clang accepted it before that and
            // warn about it only under `-pedantic`
            // ("ISO C does not support omitting parameter names in function
            // definitions before C23"). There is nothing to bind — the body
            // cannot name the parameter — but the generated item still needs
            // one in that position; see `Sema::function_def`.
            if definition.is_some() && param.name.is_none() {
                self.require_standard(
                    crate::Standard::C23,
                    "omitting a parameter name in a function definition",
                    param.range,
                );
            }
            // The name is visible to the declarators that follow it, and to
            // nothing else; the object exists only so that a bound written
            // there resolves to something.
            if let Some(name) = &param.name {
                let object = self.new_object(&name.name, ty, Storage::Automatic, false, name.range);
                self.insert(&name.name, Entry::Object(object));
            }
            param_tys.push(ty);
            param_names.push(param.name.as_ref().map(|n| n.name.clone()));
        }
        Some(())
    }

    /// Declares (but does not define) a function.
    ///
    /// `definition` carries the parameter declarations of a *definition*, which
    /// is what turns the check into "this is the definition". `scope` says
    /// whether the name belongs to the file scope, where C gives every
    /// function its linkage, or to the block it was written in, which is where
    /// GNU puts a [nested one](Sema::nested_function_def).
    #[allow(clippy::too_many_arguments)]
    pub(super) fn declare_function(
        &mut self,
        decl: &ast::Decl,
        name: &ast::Ident,
        func: &ast::FunctionType,
        attrs: &ast::Attributes,
        asm_label: Option<&ast::Spanned<String>>,
        definition: Option<&ast::FunctionDef>,
        scope: FuncScope,
    ) -> Option<FuncId> {
        let specifiers = &decl.specifiers;
        // A nested function is an item of this unit and never a symbol of its
        // own, whatever the unit's `#pragma cinrs export` says.
        let is_static = scope == FuncScope::Nested
            || specifiers.storage.as_ref().map(|s| s.node) == Some(ast::StorageClass::Static);
        let is_inline = specifiers.inline;
        let is_noreturn = specifiers.noreturn.is_some() || attrs.noreturn.is_some();
        let inline_hint = match (attrs.always_inline.is_some(), attrs.noinline.is_some()) {
            (true, false) => Some(ir::InlineHint::Always),
            (false, true) => Some(ir::InlineHint::Never),
            _ => None,
        };
        let init_kind = match (attrs.constructor.is_some(), attrs.destructor.is_some()) {
            (true, _) => Some(ir::InitKind::Constructor),
            (false, true) => Some(ir::InitKind::Destructor),
            _ => None,
        };
        if let Some(alignment) = &attrs.aligned {
            self.error(
                alignment.range,
                "'aligned' is not supported on a function; Rust has no way to say it",
            );
        }
        if let Some(packed) = attrs.packed {
            self.error(
                packed,
                "'packed' is only meaningful on a record or a member",
            );
        }
        self.reject_cleanup(attrs, "a function");
        if definition.is_some() {
            self.reject_weak(attrs, "a function definition");
        }
        // C23 has no `constexpr` functions, and neither has this: a constant
        // here is a value, folded wherever its name is used.
        if let Some(storage) = &specifiers.storage
            && storage.node == ast::StorageClass::Constexpr
        {
            let at = storage.range;
            self.error(at, "'constexpr' is not supported on a function");
        }

        // A definition's identifier list has already become a parameter list
        // (see `Sema::old_style_params`), so one that is still here belongs to
        // a declaration — where C99 6.7.5.3p3 says it must be empty.
        if let Some(first) = func.kr_names.first() {
            self.error(
                first.range,
                "an identifier list is only allowed in a function definition; \
                 a declaration needs the parameter types",
            );
            return None;
        }
        let ret = self.ty_of(&func.ret)?;
        if self.reject_va_list(ret, func.ret.range) {
            return None;
        }
        // Only a *definition* needs the return type complete (C11 6.9.1p3);
        // a declaration may name a tag nobody ever completes — Kissat's
        // `kimits.h` declares `changes kissat_changes (struct kissat *);` with
        // `struct changes` defined nowhere, and glibc's headers do the same.
        // A call needs it too (6.5.2.2p1), which `Sema::call` checks.
        if definition.is_some() && !ret.is_void() && !self.types().is_complete(ret) {
            self.error(
                func.ret.range,
                format!(
                    "function cannot return an incomplete type '{}'",
                    self.tyname(ret)
                ),
            );
            return None;
        }

        let mut param_tys = Vec::with_capacity(func.params.len());
        let mut param_names = Vec::with_capacity(func.params.len());
        // C99 6.2.1p4's *function prototype scope*: a parameter's name is
        // visible to the declarators that follow it, which is what makes the
        // bound of `void f(int n, double a[3][n])` resolve to the parameter
        // rather than to nothing. The names are gone again at the closing
        // parenthesis, and the bounds themselves are never evaluated here —
        // see [`BoundMode::Unevaluated`].
        self.push_prototype_scope();
        let result = self.declare_params(func, definition, &mut param_tys, &mut param_names);
        // A tag the list declared belongs to the prototype scope and is gone
        // with it — unless this list is a *definition*'s, where 6.2.1p4 gives
        // it the body's block scope instead; see [`Sema::param_tags`].
        self.pop_prototype_scope(definition.is_some());
        result?;

        if func.old_style {
            // C99 6.9.1p7: the definition's type has no prototype, so every
            // caller applies the default argument promotions — and the
            // generated item has to take what a caller really passes. The
            // declared types come back on entry; see `Sema::function_def`.
            for ty in &mut param_tys {
                *ty = ty.promote_argument(&self.target);
            }
        }
        let sig = Signature {
            ret,
            params: param_tys,
            variadic: func.variadic,
            prototyped: self.is_prototyped(func),
        };

        // Is this one of the [x86 intrinsics](crate::x86)? The bundled
        // `<immintrin.h>` declares eight hundred of them, and a call to one is
        // generated as `::core::arch::x86_64::<name>` rather than as a call to
        // a symbol, because there is no symbol.
        //
        // The test is deliberately conservative — the same name, a prototype,
        // not variadic, and no definition in this unit — so a program that has
        // a `_mm_add_ps` of its own gets its own function. The header is what
        // puts the real declarations in scope; nothing here reads it.
        let intrinsic = (definition.is_none()
            && matches!(self.target.arch, Arch::X86 | Arch::X86_64)
            && sig.prototyped
            && !sig.variadic)
            .then(|| crate::x86::lookup(&name.name))
            .flatten();
        // A declaration of one of those names that does *not* match is refused
        // rather than left to be a symbol: there is no `_mm_add_ps` to link
        // against, so a call to it would be an unresolved reference nobody can
        // read. The way to get the real one is to include the header.
        let intrinsic = match intrinsic {
            Some(intr) if intr.x86_64_only && self.target.arch != Arch::X86_64 => {
                self.error(
                    name.range,
                    format!(
                        "'{}' is an x86 intrinsic that Rust's core::arch has only on x86-64, and \
                         this unit is being translated for x86",
                        intr.name
                    ),
                );
                None
            }
            Some(intr) if usize::from(intr.arity) != sig.params.len() => {
                self.error(
                    name.range,
                    format!(
                        "'{}' is an x86 intrinsic and takes {} argument{}, not {}: this \
                         declaration does not match the one <immintrin.h> gives it, and there is \
                         no symbol of that name to link against. Include the header instead of \
                         declaring it",
                        intr.name,
                        intr.arity,
                        if intr.arity == 1 { "" } else { "s" },
                        sig.params.len(),
                    ),
                );
                None
            }
            other => other,
        };
        let target_features = self.target_features(attrs);

        // A nested function has no linkage: its name lives in the block it was
        // written in, where it shadows whatever a file-scope declaration of the
        // same name means, and the only declaration it can be a redeclaration
        // of is one written in the same block — GNU's `auto int g(int);`
        // forward declaration.
        let visible = match scope {
            FuncScope::File => self.lookup(&name.name),
            FuncScope::Nested => self.declared_here(&name.name),
        };
        let existing = match visible {
            Some(Entry::Function(id)) => Some(*id),
            Some(other) => {
                let what = other.describe();
                let previous = match other {
                    Entry::Object(id) => self.program.object(*id).range,
                    Entry::Typedef(entry) => entry.range,
                    Entry::Constant { range, .. } => *range,
                    Entry::Function(_) => unreachable!("matched above"),
                };
                self.error_note(
                    name.range,
                    format!("redefinition of '{}', which is already {what}", name.name),
                    previous,
                    format!("previous declaration of '{}' is", name.name),
                );
                return None;
            }
            None => None,
        };

        // `char *strcpy();` — a declaration of a C library function with no
        // prototype — declares GCC's built-in, whose prototype is the
        // composite of the two; see [`Sema::implicit_library_signature`].
        // Only when nothing the program wrote has declared the name yet: an
        // earlier prototype of its own is what the declaration refers to. A
        // return type that disagrees with the library's (`char *malloc();`)
        // keeps the declaration as written.
        let mut sig = sig;
        let mut from_library = false;
        if definition.is_none()
            && !sig.prototyped
            && !is_static
            && scope == FuncScope::File
            && existing.is_none_or(|id| self.library_prototyped.contains(&id))
            && let Some(library) = self.implicit_library_signature(&name.name)
            && let Some(composite) = self.composite_signature(&sig, &library)
        {
            param_names = vec![None; composite.params.len()];
            sig = composite;
            from_library = true;
        }

        let id = match existing {
            Some(id) => {
                let previous = self.program.function(id).clone();
                // A library function that was declared with the library's
                // prototype on the program's behalf and is now declared by the
                // program with other parameters is the program's own function,
                // which GCC accepts with "conflicting types for built-in
                // function". Earlier calls converted their arguments for the
                // library's parameters, and a call whose arguments disagree
                // with the final signature is reinterpreted where it is
                // generated — so only the return type has to agree.
                let library_owned = self.library_prototyped.contains(&id);
                let lenient = library_owned && self.compatible(previous.sig.ret, sig.ret);
                let composite = self
                    .composite_signature(&previous.sig, &sig)
                    .or_else(|| lenient.then(|| sig.clone()));
                let Some(composite) = composite else {
                    let note = if library_owned {
                        format!(
                            "'{}' was declared here without a prototype of the program's own, \
                             which gave it the C library's, as GCC does for a built-in function",
                            name.name
                        )
                    } else {
                        format!("previous declaration of '{}' is", name.name)
                    };
                    self.error_note(
                        name.range,
                        format!("conflicting types for '{}'", name.name),
                        previous.range,
                        note,
                    );
                    return None;
                };
                // Anything the program writes with a prototype of its own, and
                // any definition, makes the declaration the program's.
                if !from_library && (sig.prototyped || definition.is_some()) {
                    self.library_prototyped.remove(&id);
                }
                // The composite type is what later calls are checked against;
                // a *definition* keeps its own signature instead, because that
                // is what the generated Rust item really takes. The two differ
                // only for `int f(int); int f() { … }`, which C allows and
                // which defines a function that ignores its argument.
                let merged = if definition.is_some() {
                    sig.clone()
                } else if previous.body.is_some() {
                    previous.sig.clone()
                } else {
                    composite
                };
                // The parameter names the `extern` block declares come from
                // whichever declaration supplied the signature.
                let names_from_here = definition.is_some() || merged == sig;
                if definition.is_some() && previous.body.is_some() {
                    self.error_note(
                        name.range,
                        format!("redefinition of '{}'", name.name),
                        previous.range,
                        format!("previous definition of '{}' is", name.name),
                    );
                    return None;
                }
                let entry = &mut self.program.functions[id.0 as usize];
                entry.sig = merged;
                entry.is_static |= is_static;
                entry.is_inline |= is_inline;
                entry.noreturn |= is_noreturn;
                entry.cold |= attrs.cold.is_some();
                // Attributes accumulate over the declarations of one function,
                // so a `safe` written on any of them makes it safe — and the
                // range kept is the first one, which is where the diagnostics
                // about it point.
                entry.safe = entry.safe.or(attrs.safe);
                entry.inline_hint = entry.inline_hint.or(inline_hint);
                entry.init_kind = entry.init_kind.or(init_kind);
                entry.deprecated = entry
                    .deprecated
                    .take()
                    .or_else(|| attrs.deprecated.as_ref().map(|d| d.node.clone()));
                entry.section = entry
                    .section
                    .take()
                    .or_else(|| attrs.section.as_ref().map(|s| s.node.clone()));
                entry.asm_label = entry
                    .asm_label
                    .take()
                    .or_else(|| asm_label.map(|label| label.node.clone()));
                // GCC takes the union of the `target` attributes written on
                // the declarations of one function, as it does for every other
                // attribute; the definition's are simply added to whatever a
                // prototype above it asked for.
                for feature in target_features {
                    if !entry.target_features.contains(&feature) {
                        entry.target_features.push(feature);
                    }
                }
                // A unit that *defines* `_mm_add_ps` means its own function,
                // whatever the name says, so the mapping is taken back.
                if definition.is_some() {
                    entry.intrinsic = None;
                }
                if definition.is_some() {
                    entry.range = name.range;
                }
                if names_from_here {
                    entry.param_names = param_names;
                }
                id
            }
            None => {
                let id = FuncId(self.program.functions.len() as u32);
                // A lifted nested function becomes a file-scope Rust item, so
                // it needs a name of its own: `__cinrs_<enclosing>_<name>`,
                // which reads as what it is and is made unique against
                // everything else the unit generates.
                let item_name = match scope {
                    FuncScope::File => None,
                    FuncScope::Nested => {
                        let base = format!("__cinrs_{}_{}", self.func_name, name.name);
                        Some(self.reserve_item_name(&base))
                    }
                };
                self.program.functions.push(Function {
                    name: name.name.clone(),
                    sig,
                    params: Vec::new(),
                    param_names,
                    is_static,
                    is_inline,
                    noreturn: is_noreturn,
                    inline_hint,
                    cold: attrs.cold.is_some(),
                    deprecated: attrs.deprecated.as_ref().map(|d| d.node.clone()),
                    section: attrs.section.as_ref().map(|s| s.node.clone()),
                    asm_label: asm_label.map(|label| label.node.clone()),
                    init_kind,
                    target_features,
                    address_taken: false,
                    intrinsic,
                    safe: attrs.safe,
                    locals: Vec::new(),
                    uses_arena: false,
                    body: None,
                    item_name,
                    env: Vec::new(),
                    range: name.range,
                });
                match scope {
                    FuncScope::File => {
                        self.item_names.insert(name.name.clone());
                        self.insert_at_file_scope(&name.name, Entry::Function(id));
                    }
                    FuncScope::Nested => self.insert(&name.name, Entry::Function(id)),
                }
                if from_library {
                    self.library_prototyped.insert(id);
                }
                id
            }
        };
        Some(id)
    }

    /// What `__attribute__((target("…")))` asks for, in Rust's spelling.
    ///
    /// GCC's attribute takes the same names its `-m` switches do and cinrs
    /// turns each one into a `#[target_feature(enable = "…")]` on the
    /// generated item, which is the same promise: the function may use that
    /// instruction set, and it is the program's business to have checked that
    /// the processor running it has one. [`crate::x86::TARGET_FEATURES`] is
    /// the mapping, and everything it does not carry is a diagnostic rather
    /// than a silent omission — an ignored `target` would be a function
    /// compiled for the baseline and a program that crashes on the first AVX
    /// instruction it does not have.
    fn target_features(&mut self, attrs: &ast::Attributes) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        for asked in &attrs.target {
            let name = asked.node.as_str();
            if !matches!(self.target.arch, Arch::X86 | Arch::X86_64) {
                self.error(
                    asked.range,
                    format!(
                        "'target' is only mapped on x86 targets, and this unit is being \
                         translated for {}",
                        self.target.arch.as_str()
                    ),
                );
                continue;
            }
            // `target("arch=haswell")` names a processor, and `target("no-sse")`
            // takes an instruction set away; Rust's attribute can do neither.
            if let Some((key, _)) = name.split_once('=') {
                self.error(
                    asked.range,
                    format!(
                        "'target(\"{name}\")' selects a processor: Rust's #[target_feature] only \
                         enables an instruction set, so '{key}=' has no equivalent. Name the \
                         instruction sets the function needs instead, as in target(\"avx2,fma\")"
                    ),
                );
                continue;
            }
            if let Some(rest) = name.strip_prefix("no-").or_else(|| name.strip_prefix('-')) {
                self.error(
                    asked.range,
                    format!(
                        "'target(\"{name}\")' turns an instruction set off, which Rust's \
                         #[target_feature] cannot do: it only enables. Leave '{rest}' out of the \
                         list instead"
                    ),
                );
                continue;
            }
            if let Some(why) = crate::x86::unsupported_feature(name) {
                self.error(asked.range, format!("'target(\"{name}\")': {why}"));
                continue;
            }
            let Some(features) = crate::x86::target_features(name) else {
                self.error(
                    asked.range,
                    format!(
                        "unknown instruction set '{name}' in a 'target' attribute; the ones cinrs \
                         maps onto Rust's #[target_feature] are {}",
                        super::list_of_names(&crate::x86::feature_names())
                    ),
                );
                continue;
            };
            for feature in features {
                if !out.iter().any(|have| have == feature) {
                    out.push((*feature).to_owned());
                }
            }
        }
        out
    }

    /// The parameter list an old-style (K&R) definition really declares.
    ///
    /// `int f(a, b) int a; char *b; { … }` writes an *identifier list* and then
    /// a declaration list saying what each name is; C99 6.9.1p6 makes the two
    /// into the parameter list every other pass here expects, so sema builds
    /// it once, up front, and works on that.
    ///
    /// Two things survive the translation. The type still has **no prototype**
    /// (6.9.1p7): a call to it applies the default argument promotions and is
    /// only compatible with a prototype whose parameters are already their own
    /// promoted forms — which is why [`ast::FunctionType::old_style`] is set
    /// and why [`Sema::declare_function`] builds the signature out of the
    /// promoted types. And a name the declaration list leaves out is an `int`,
    /// which is implicit `int` and therefore C89's alone (a constraint
    /// violation from C99 on, and an error in GCC 14).
    fn old_style_params(
        &mut self,
        def: &ast::FunctionDef,
        func: &ast::FunctionType,
    ) -> ast::FunctionType {
        let mut out = func.clone();
        out.kr_names = Vec::new();
        out.old_style = true;
        out.has_prototype = false;

        if !self.gating.old_style_definitions() {
            self.error(
                def.ty.range,
                "old-style function definitions were removed in C23",
            );
        }
        if func.has_prototype {
            // `int f(int a) int a; { … }` — the declaration list has nothing
            // left to declare.
            if let Some(first) = def.kr_decls.first() {
                self.error(
                    first.range,
                    "a declaration list is not allowed after a parameter type list",
                );
            }
            out.old_style = false;
            out.has_prototype = true;
            return out;
        }

        // What the declaration list says, by name.
        let mut declared: Vec<(String, ast::ParamDecl)> = Vec::new();
        for decl in &def.kr_decls {
            if decl.declarators.is_empty() {
                self.error(decl.range, "this declaration declares no parameter");
                continue;
            }
            if let Some(storage) = &decl.specifiers.storage
                && storage.node != ast::StorageClass::Register
            {
                // `register` is the one C allows on a parameter, and the only
                // one a K&R declaration list is ever written with.
                self.error(
                    storage.range,
                    format!("'{}' is not allowed on a parameter", storage.node.as_str()),
                );
            }
            for declarator in &decl.declarators {
                let Some(name) = &declarator.name else {
                    self.error(declarator.range, "this declaration declares no parameter");
                    continue;
                };
                if declarator.init.is_some() {
                    self.error(
                        declarator.range,
                        format!("parameter '{}' cannot have an initializer", name.name),
                    );
                }
                if !func.kr_names.iter().any(|n| n.name == name.name) {
                    self.error(
                        name.range,
                        format!(
                            "declaration for parameter '{}', which is not in the \
                             identifier list",
                            name.name
                        ),
                    );
                    continue;
                }
                if declared.iter().any(|(other, _)| *other == name.name) {
                    self.error(
                        name.range,
                        format!("redefinition of parameter '{}'", name.name),
                    );
                    continue;
                }
                declared.push((
                    name.name.clone(),
                    ast::ParamDecl {
                        specifiers: decl.specifiers.clone(),
                        name: Some(name.clone()),
                        ty: declarator.ty.clone(),
                        range: declarator.range,
                    },
                ));
            }
        }

        let mut seen: Vec<&str> = Vec::new();
        for ident in &func.kr_names {
            if seen.contains(&ident.name.as_str()) {
                self.error(
                    ident.range,
                    format!("redefinition of parameter '{}'", ident.name),
                );
                continue;
            }
            seen.push(&ident.name);
            match declared.iter().find(|(name, _)| *name == ident.name) {
                Some((_, param)) => out.params.push(param.clone()),
                None => {
                    if !self.gating.implicit_int() {
                        self.error(
                            ident.range,
                            format!(
                                "type specifier missing for parameter '{}'; C99 does \
                                 not support implicit 'int'",
                                ident.name
                            ),
                        );
                    }
                    out.params.push(ast::ParamDecl {
                        specifiers: ast::DeclSpecifiers {
                            storage: None,
                            thread_local: None,
                            inline: false,
                            noreturn: None,
                            alignas: Vec::new(),
                            attrs: ast::Attributes::default(),
                            base: implicit_int_type(ident.range),
                            range: ident.range,
                        },
                        name: Some(ident.clone()),
                        ty: implicit_int_type(ident.range),
                        range: ident.range,
                    });
                }
            }
        }
        out
    }

    pub(super) fn function_def(&mut self, def: &ast::FunctionDef) {
        self.check_function_def(def, FuncScope::File);
    }

    /// Checks GNU's nested function definition and lifts it out.
    ///
    /// The body is checked where it stands, so it sees the enclosing
    /// function's parameters and locals exactly as far as C's scoping makes
    /// them visible; every one of those it uses becomes a hidden pointer
    /// parameter (see [`ir::EnvParam`]), and the definition becomes a
    /// file-scope item that nothing else in the unit can name. What is left in
    /// the enclosing function is nothing at all: the name is in scope for the
    /// rest of its block, and a call to it passes the addresses of the objects
    /// it uses.
    pub(super) fn nested_function_def(&mut self, def: &ast::FunctionDef) {
        if self.nest.is_empty() {
            // A statement expression written in a file-scope initialiser is
            // the one block that is inside no function at all, and there is
            // nothing for a nested definition there to be nested in.
            self.error(
                def.name.range,
                format!(
                    "'{}' is defined inside a statement expression at file scope, which is \
                     inside no function; a nested function definition needs an enclosing one",
                    def.name.name
                ),
            );
            return;
        }
        if let Some(storage) = &def.specifiers.storage
            && storage.node != ast::StorageClass::Auto
        {
            self.error(
                storage.range,
                format!(
                    "'{}' is not allowed on a nested function definition: a nested function \
                     has no linkage, and 'auto' is the only storage class GNU C accepts on \
                     one",
                    storage.node.as_str()
                ),
            );
        }
        self.check_function_def(def, FuncScope::Nested);
    }

    fn check_function_def(&mut self, def: &ast::FunctionDef, scope: FuncScope) {
        let ast::TypeKind::Function(func) = &def.ty.kind else {
            return;
        };
        // An old-style definition is turned into an ordinary parameter list
        // here, once, so that nothing downstream has to know about identifier
        // lists; see [`Sema::old_style_params`].
        let synthesized;
        let func = if func.kr_names.is_empty() && def.kr_decls.is_empty() {
            func
        } else {
            synthesized = self.old_style_params(def, func);
            &synthesized
        };
        let decl = ast::Decl {
            specifiers: def.specifiers.clone(),
            declarators: Vec::new(),
            range: def.range,
        };
        let mut attrs = def.attrs.clone();
        attrs.merge(def.specifiers.attrs.clone());
        let Some(id) = self.declare_function(
            &decl,
            &def.name,
            func,
            &attrs,
            def.asm_label.as_ref(),
            Some(def),
            scope,
        ) else {
            return;
        };
        self.note_long_double_function(id, func);
        // The enclosing function's state goes aside for the length of a nested
        // definition, and the nesting gains a level.
        let saved = (scope == FuncScope::Nested).then(|| self.save_function_state());
        self.nest.push(NestFrame {
            func: id,
            labels: HashSet::new(),
        });
        self.nest_chains
            .insert(id, self.nest.iter().map(|frame| frame.func).collect());
        let level = (self.nest.len() - 1) as u32;

        // Parameters live in the same scope as the body's outermost block, so
        // that `int f(int x) { int x; }` is the redefinition C says it is.
        self.push_scope();
        // And so do the tags the parameter list declared: a `struct T` written
        // in a *definition*'s list has block scope terminating with the body
        // (6.2.1p4), which is what makes `f(struct T { int a; } t)` able to
        // reach `t.a`.
        self.take_param_tags();
        self.ret_ty = self.program.function(id).sig.ret;
        self.func_name = def.name.name.clone();
        self.func_variadic = func.variadic;
        self.va_param = None;
        self.breakables.clear();
        self.switch_stack.clear();
        self.vla_scopes.clear();
        self.switch_vla_depths.clear();
        self.goto_scopes.clear();
        self.label_vla_scopes.clear();
        self.func_uses_arena = false;
        self.next_loop = 0;
        self.next_switch = 0;
        // `next_label` is *not* reset: a label's identity is unique across the
        // unit, so that a `&&label` in a block-scope `static`'s initialiser —
        // which becomes an item at module level — can be resolved without
        // knowing whose function it came from.
        //
        // Whether the body can keep Rust's own control flow is decided before
        // it is checked, because it changes how `switch` is lowered and which
        // labels the statements keep.
        let lowering = Self::lowering(def);
        self.cfg_mode = lowering.is_none();
        self.region_labels = lowering.unwrap_or_default();
        self.collect_labels(&def.body);
        // A `goto` in a function nested inside this one that names one of
        // these labels is GNU's nonlocal goto, which is refused by name rather
        // than as "no such label".
        if let Some(frame) = self.nest.last_mut() {
            frame.labels = self.labels.keys().cloned().collect();
        }

        // A definition returning a type that holds no value here; see
        // `sema::float128`.
        let ret = self.program.function(id).sig.ret;
        let fname = self.program.function(id).name.clone();
        self.refuse_float128_object(&fname, ret, func.ret.range);
        let mut params = Vec::with_capacity(func.params.len());
        // The old-style parameters whose declared type is not what the ABI
        // hands over: the item takes the promoted one under a hidden name, and
        // the prologue below binds the C name to the declared type.
        let mut converted: Vec<(ast::Ident, Ty, Ty, ObjectId, bool)> = Vec::new();
        for (index, (param, ty)) in func
            .params
            .iter()
            .zip(self.program.function(id).sig.params.clone())
            .enumerate()
        {
            let Some(name) = &param.name else {
                // C23's unnamed parameter (N2480). Nothing in the body can
                // reach it, but the generated item still takes an argument in
                // that position, so it gets a name of its own — the parameter
                // list has to keep the shape the signature has.
                let object = self.new_object(
                    &format!("__cinrs_unnamed_param{index}"),
                    ty,
                    Storage::Automatic,
                    param.ty.qualifiers.is_const,
                    param.range,
                );
                params.push(object);
                continue;
            };
            self.note_long_double(name.range, &param.ty);
            // A parameter of a *definition* is an object; one of a prototype
            // is not, and is fine.
            self.refuse_float128_object(&name.name, ty, name.range);
            if func.old_style {
                // `resolve_param_ty` already succeeded for this parameter in
                // `declare_function`, or there would be no `id` to be here
                // with; it neither reports nor changes anything.
                let declared = self.resolve_param_ty(&param.ty).unwrap_or(ty);
                if declared != ty {
                    let object = self.new_object(
                        &format!("__cinrs_kr_{}", name.name),
                        ty,
                        Storage::Automatic,
                        false,
                        name.range,
                    );
                    converted.push((
                        name.clone(),
                        declared,
                        ty,
                        object,
                        param.ty.qualifiers.is_const,
                    ));
                    params.push(object);
                    continue;
                }
            }
            if self.check_redefinition(name) {
                // Two parameters under one name; leaving the second out keeps
                // the generated signature from being invalid Rust on top of
                // being invalid C.
                continue;
            }
            let object = self.new_object(
                &name.name,
                ty,
                Storage::Automatic,
                param.ty.qualifiers.is_const,
                name.range,
            );
            self.insert(&name.name, Entry::Object(object));
            // Either spelling is a list this function may copy: a `va_list`
            // parameter holds the caller's list, and a `va_list *` points at
            // it, so `va_list x;` inside has something to start from.
            if (ty.is_va_list() || self.points_to_va_list(ty)) && self.va_param.is_none() {
                self.va_param = Some(object);
            }
            params.push(object);
        }
        self.func_params = params.clone();

        // Every automatic object the body declares — including the ones
        // buried in a statement expression, which no walk over the statements
        // would find — is the function's, so the range of ids the body used is
        // what code generation names its locals from.
        let first_object = self.program.objects.len() as u32;
        // A function the body defines — a nested one — could name a table of
        // label addresses this function's own body does not show.
        let first_function = self.program.functions.len();
        // `let a: c_char = __cinrs_kr_a as c_char;` — C99 6.9.1p10 gives an
        // old-style parameter the type its own declaration gave it, while the
        // caller passed the promoted one, which is what the item takes.
        let mut body = Vec::new();
        for (name, declared, promoted, object, is_const) in converted {
            let load = Expr::new(
                ExprKind::Load(super::place_of(
                    PlaceKind::Object(object),
                    promoted,
                    false,
                    name.range,
                )),
                promoted,
                name.range,
            );
            let init = self.convert(load, declared);
            let local = self.new_object(
                &name.name,
                declared,
                Storage::Automatic,
                is_const,
                name.range,
            );
            self.insert(&name.name, Entry::Object(local));
            body.push(Stmt::Let {
                object: local,
                init,
                explicit: true,
            });
        }
        // C99 6.9.1p10 again: the size expressions of a variably modified
        // parameter are evaluated on entry. The bound is not part of the
        // adjusted type — the parameter is a pointer — but `void f(int n, int
        // a[n++])` still increments `n`, and a definition is the one place
        // where that is observable.
        body.extend(self.parameter_size_effects(func));
        body.extend(self.block_items(&def.body.items));
        // A forward `goto` names a label the walk above had not reached yet, so
        // the jumps are checked now that every label's scope is known.
        self.check_goto_vla_scopes();
        // Outside CFG mode every `goto` left in the body is an outward jump,
        // which becomes a `break` or a `continue` of the labelled region built
        // here; see [`crate::regions`].
        if !self.region_labels.is_empty() {
            let names: HashMap<ir::LabelId, String> = self
                .labels
                .iter()
                .map(|(name, label)| (label.id, name.clone()))
                .collect();
            let planned = crate::regions::restructure(&mut body, &names, &self.program.functions);
            // The walk that chose this lowering and the walk that built it
            // agree by construction. They can only disagree about a `goto`
            // sema left out because it named a label that is not there, which
            // has been reported already — and if they ever disagree otherwise,
            // saying so is better than generating a jump that does nothing.
            if !planned && !self.diags.has_errors() {
                self.error(
                    def.body.range,
                    "internal error in cinrs: this function's jumps were taken for ones Rust \
                     can express and then could not be. Please report it",
                );
            }
        }
        let ret = self.ret_ty;
        // A C function may fall off its end; the value is then whatever the ABI
        // left behind. Returning a zero is the honest, safe translation —
        // `unreachable_unchecked` would turn a legal (if useless) C program
        // into undefined behaviour. In CFG mode the `return` is unconditional:
        // every block needs a terminator, and an unreachable one is dropped.
        // A call to a `_Noreturn` function ends the statement it is in, which
        // is why the function table is needed here.
        let terminates = ir::always_terminates(&body, &self.program.functions);
        if self.cfg_mode || (!ret.is_void() && !terminates) {
            let value = (!ret.is_void()).then(|| self.zero(ret, def.body.range));
            body.push(Stmt::Return {
                value,
                range: def.body.range,
            });
        }
        self.pop_scope();

        let body = if self.cfg_mode {
            // The labels of *this* function whose address a `&&label` took.
            // `Sema::label_addrs` is unit-wide, so it is `Sema::labels` — which
            // holds only this function's — that picks them out; sorting is
            // what keeps the number each one's address is from depending on a
            // hash order.
            let mut taken: Vec<ir::LabelId> = self
                .labels
                .values()
                .map(|label| label.id)
                .filter(|id| self.label_addrs.contains(id))
                .collect();
            taken.sort_unstable();
            // A dispatch table whose contents are known for good has its
            // labels numbered first, in its order, so that `table[e]` is
            // `e + 1` without reading it; see `crate::cfg`'s table fold.
            let table = self.foldable_table(&body, &taken, first_object, first_function);
            if let Some((_, order)) = &table {
                taken.retain(|id| !order.contains(id));
                let mut ordered = order.clone();
                ordered.append(&mut taken);
                taken = ordered;
            }
            let table = table.map(|(object, _)| object);
            // Where a computed `goto` puts its target on the way to the
            // dispatch; see `crate::cfg`. Any integer type holds `1..=n`.
            let goto_value = (!taken.is_empty()).then(|| {
                self.new_object(
                    "__cinrs_goto",
                    Ty::ULong,
                    Storage::Automatic,
                    false,
                    def.body.range,
                )
            });
            // What each label was called, so that a loop the relooper recovers
            // can carry the C name of the label it heads.
            let names: HashMap<ir::LabelId, String> = self
                .labels
                .iter()
                .map(|(name, label)| (label.id, name.clone()))
                .collect();
            ir::Body::Cfg(crate::cfg::lower(
                body,
                &params,
                &self.program.objects,
                &taken,
                goto_value,
                table,
                &names,
            ))
        } else {
            ir::Body::Structured(body)
        };
        let last_object = self.program.objects.len() as u32;
        // A nested function's own objects are inside this range too, and they
        // are its locals rather than this one's; the level each object was
        // created at is what separates them. So are the hidden environment
        // parameters, which are parameters and not `let` bindings.
        let hidden: Vec<ObjectId> = self
            .program
            .function(id)
            .env
            .iter()
            .map(|entry| entry.param)
            .collect();
        let locals: Vec<ObjectId> = (first_object..last_object)
            .map(ObjectId)
            .filter(|object| {
                self.program.object(*object).storage == Storage::Automatic
                    && self.object_level(*object) == level as usize
                    && !hidden.contains(object)
            })
            .collect();
        let entry = &mut self.program.functions[id.0 as usize];
        entry.params = params;
        entry.locals = locals;
        entry.uses_arena = self.func_uses_arena;
        entry.body = Some(body);
        self.nest.pop();
        if let Some(saved) = saved {
            self.restore_function_state(saved);
        }
    }

    /// Puts the state of the function being checked aside, so that a nested
    /// definition can be checked in the middle of it.
    fn save_function_state(&mut self) -> Box<SavedFunc> {
        Box::new(SavedFunc {
            ret_ty: self.ret_ty,
            func_name: std::mem::take(&mut self.func_name),
            func_variadic: self.func_variadic,
            func_params: std::mem::take(&mut self.func_params),
            va_param: self.va_param.take(),
            cfg_mode: self.cfg_mode,
            region_labels: std::mem::take(&mut self.region_labels),
            labels: std::mem::take(&mut self.labels),
            breakables: std::mem::take(&mut self.breakables),
            switch_stack: std::mem::take(&mut self.switch_stack),
            vla_scopes: std::mem::take(&mut self.vla_scopes),
            label_vla_scopes: std::mem::take(&mut self.label_vla_scopes),
            goto_scopes: std::mem::take(&mut self.goto_scopes),
            switch_vla_depths: std::mem::take(&mut self.switch_vla_depths),
            func_uses_arena: self.func_uses_arena,
            // A `cleanup` owed by the enclosing block is not owed by the
            // nested function's `return`.
            cleanup_depth: std::mem::take(&mut self.cleanup_depth),
            next_loop: self.next_loop,
            next_switch: self.next_switch,
        })
    }

    fn restore_function_state(&mut self, saved: Box<SavedFunc>) {
        let saved = *saved;
        self.ret_ty = saved.ret_ty;
        self.func_name = saved.func_name;
        self.func_variadic = saved.func_variadic;
        self.func_params = saved.func_params;
        self.va_param = saved.va_param;
        self.cfg_mode = saved.cfg_mode;
        self.region_labels = saved.region_labels;
        self.labels = saved.labels;
        self.breakables = saved.breakables;
        self.switch_stack = saved.switch_stack;
        self.vla_scopes = saved.vla_scopes;
        self.label_vla_scopes = saved.label_vla_scopes;
        self.goto_scopes = saved.goto_scopes;
        self.switch_vla_depths = saved.switch_vla_depths;
        self.func_uses_arena = saved.func_uses_arena;
        self.cleanup_depth = saved.cleanup_depth;
        self.next_loop = saved.next_loop;
        self.next_switch = saved.next_switch;
    }

    // -- static initialisers ------------------------------------------------

    /// Reduces an initialiser for an object with static storage duration to
    /// something the generated `static mut` item can hold.
    pub(super) fn static_init(&mut self, expr: Expr, what: &str) -> Option<Expr> {
        // GNU's *label difference*, `&&a - &&b`: an integer constant in GCC,
        // and the difference of two label numbers here. Neither is known until
        // the function's taken labels have all been seen, so it goes
        // through unevaluated and code generation folds it — which Rust does
        // in a `const` too, the two operands being literals by then.
        if is_label_difference(&expr) {
            return Some(expr);
        }
        let (ty, range) = (expr.ty, expr.range);
        match expr.kind {
            // `int i = (1, 2);` — a comma operator is not part of a *constant
            // expression* (6.6p3), and the initialiser of an object with
            // static storage duration is supposed to be one. Both GCC and
            // Clang take it all the same, and only `-pedantic-errors` refuses
            // it, so the value of the right operand is the initialiser here
            // too — as long as the left one is itself a constant, since
            // nothing here could evaluate a call. WG14 DR035 (`drs/dr0xx.c`).
            //
            // Where C asks for an *integer constant expression* — an
            // enumerator, an array bound, a `case` label, `_Static_assert` —
            // the comma is still refused, which is what GCC does there
            // ("enumerator value for 'e' is not an integer constant") and what
            // this crate's strict entry points do everywhere.
            ExprKind::Comma { lhs, rhs } if self.const_eval(&lhs).is_some() => {
                self.static_init(*rhs, what)
            }
            ExprKind::RecordLit { record, fields } => {
                let fields: Option<Vec<Expr>> = fields
                    .into_iter()
                    .map(|f| self.static_init(f, what))
                    .collect();
                Some(Expr::new(
                    ExprKind::RecordLit {
                        record,
                        fields: fields?,
                    },
                    ty,
                    range,
                ))
            }
            ExprKind::UnionLit {
                record,
                index,
                value,
            } => {
                let value = self.static_init(*value, what)?;
                Some(Expr::new(
                    ExprKind::UnionLit {
                        record,
                        index,
                        value: Box::new(value),
                    },
                    ty,
                    range,
                ))
            }
            ExprKind::ArrayLit(items) => {
                let items: Option<Vec<Expr>> = items
                    .into_iter()
                    .map(|e| self.static_init(e, what))
                    .collect();
                Some(Expr::new(ExprKind::ArrayLit(items?), ty, range))
            }
            ExprKind::ArrayRepeat { value, len } => {
                let value = self.static_init(*value, what)?;
                Some(Expr::new(
                    ExprKind::ArrayRepeat {
                        value: Box::new(value),
                        len,
                    },
                    ty,
                    range,
                ))
            }
            ExprKind::Zeroed => Some(Expr::new(ExprKind::Zeroed, ty, range)),
            // A compound literal at file scope is an object of its own, and
            // reading one where a constant expression has to go is reading a
            // value that was constant when it was written. ISO C does not
            // allow it; GCC does, and c-testsuite `00216` writes it.
            ExprKind::Load(Place {
                kind: PlaceKind::Object(id),
                ..
            }) if self.static_literals.contains_key(&id) => {
                let at = self.static_literals[&id];
                let value = self.program.statics[at].init.clone();
                self.static_init(value, what)
            }
            _ if ty.is_arithmetic() => {
                let value = self.const_eval_at(&expr, what)?;
                Some(self.const_to_expr(value, ty, range))
            }
            _ if ty.is_pointer() => {
                // C99 6.6p9 lets an address constant be offset by *any*
                // integer constant expression, not only by a literal:
                // `&sqlite3UpperToLower[256-OP_Ne]` is SQLite's, and a
                // hand-written `SQLITE_INT_TO_PTR(i|(b*JSON_BLOB))` is the
                // same thing one cast further out. Nothing below recognises
                // an unfolded subscript, so the integer parts are folded
                // first — which also keeps the emitted `static` free of
                // arithmetic Rust would have to redo.
                let expr = self.fold_pointer_constant(expr);
                // `(char *) 1 + 2` is a constant, but a Rust `.offset()` on a
                // pointer with no provenance is not: the arithmetic is done
                // here instead, and what is left is one integer cast.
                if let Some(folded) = self.fold_integer_pointer(&expr) {
                    return Some(folded);
                }
                if self.is_address_constant(&expr) {
                    return Some(expr);
                }
                self.error(
                    range,
                    format!("{what} is not a compile-time constant expression"),
                );
                None
            }
            // `static __m128d k = {1, 2};` — the lanes are built by a call to
            // `core::arch`, which a Rust `static` cannot make, and the vector
            // types have no constant constructor.
            _ if ty.is_vector() => {
                let name = self.tyname(ty);
                self.error(
                    range,
                    format!(
                        "{what} is not a compile-time constant expression: a '{name}' with \
                         static storage duration cannot be given lanes here, because building a \
                         vector is a call to core::arch, which Rust cannot run in a 'static'. \
                         Leave it zero and assign the lanes in a function, or keep the constants \
                         in a 'static const double[]' and load them with _mm_loadu_pd"
                    ),
                );
                None
            }
            _ => {
                self.error(
                    range,
                    format!("{what} is not a compile-time constant expression"),
                );
                None
            }
        }
    }

    /// Folds the integer constant subexpressions of a pointer value, leaving
    /// its shape alone.
    ///
    /// The shapes an *address constant* may take are listed in
    /// [`Sema::is_address_constant`], and each of them has room for an integer
    /// constant expression: the subscript of `&a[i]`, the offset of `p + i`,
    /// the integer of `(T *) i`. C99 6.6p9 asks only that it *be* a constant
    /// expression, so folding it here is what makes
    ///
    /// ```c
    /// static const unsigned char *aLTb = &sqlite3UpperToLower[256-OP_Ne];
    /// ```
    ///
    /// an address constant rather than a diagnostic. Anything that does not
    /// fold is left exactly as it was, so the caller's check — and its error —
    /// still see the expression the program wrote.
    fn fold_pointer_constant(&mut self, expr: Expr) -> Expr {
        let (ty, range) = (expr.ty, expr.range);
        if ty.is_integer() {
            return match self.const_eval(&expr) {
                Some(ConstValue::Int(value)) => Expr::int(value, ty, range),
                _ => expr,
            };
        }
        let kind = match expr.kind {
            ExprKind::Cast(inner) => ExprKind::Cast(Box::new(self.fold_pointer_constant(*inner))),
            ExprKind::PtrOffset { ptr, index, sub } => ExprKind::PtrOffset {
                ptr: Box::new(self.fold_pointer_constant(*ptr)),
                index: Box::new(self.fold_pointer_constant(*index)),
                sub,
            },
            ExprKind::AddrOf(place) => ExprKind::AddrOf(self.fold_place_constant(place)),
            other => other,
        };
        Expr::new(kind, ty, range)
    }

    /// [`Sema::fold_pointer_constant`] for the place under an `&`.
    fn fold_place_constant(&mut self, place: Place) -> Place {
        let kind = match place.kind {
            PlaceKind::Index { base, index } => PlaceKind::Index {
                base: Box::new(self.fold_pointer_constant(*base)),
                index: Box::new(self.fold_pointer_constant(*index)),
            },
            PlaceKind::Field {
                base,
                record,
                index,
            } => PlaceKind::Field {
                base: Box::new(self.fold_place_constant(*base)),
                record,
                index,
            },
            PlaceKind::Deref(ptr) => PlaceKind::Deref(Box::new(self.fold_pointer_constant(*ptr))),
            other => other,
        };
        Place { kind, ..place }
    }

    /// Folds a pointer value built entirely out of integer constants into one
    /// integer cast to the pointer type, or `None` when it is not one.
    ///
    /// `(unsigned int *) 0xa000` needs nothing, but `(char *) 1 + 2` would
    /// become a `.offset(2)` on a pointer with no provenance, which is a
    /// const-evaluation error in Rust rather than an address. Doing the
    /// arithmetic here leaves one cast, which is a constant everywhere.
    fn fold_integer_pointer(&mut self, expr: &Expr) -> Option<Expr> {
        let ty = expr.ty;
        if !ty.is_pointer() {
            return None;
        }
        let value = self.integer_pointer_value(expr)?;
        let size = self.size_ty();
        let base = Expr::int(value, size, expr.range);
        Some(Expr::new(ExprKind::Cast(Box::new(base)), ty, expr.range))
    }

    /// The address an all-integer pointer expression names, in bytes.
    ///
    /// The address of a *place* is one of these when the place is reached from
    /// a constant pointer rather than from an object: `&((struct s *)0)->m` is
    /// the hand-written `offsetof` half the world's C still defines, and GCC
    /// folds it to the member's offset. See [`Sema::place_offset`].
    pub(super) fn integer_pointer_value(&mut self, expr: &Expr) -> Option<i128> {
        match &expr.kind {
            ExprKind::Int(v) => Some(*v),
            ExprKind::Zeroed if expr.ty.is_pointer() => Some(0),
            ExprKind::Cast(inner) if inner.ty.is_integer() || inner.ty.is_pointer() => {
                self.integer_pointer_value(inner)
            }
            ExprKind::AddrOf(place) if self.gating.dialect.is_gnu() => {
                let place = place.clone();
                self.place_offset(&place)
            }
            ExprKind::PtrOffset { ptr, index, sub } => {
                // The base has to be an integer, or this is an ordinary
                // address constant and `is_address_constant` will take it.
                let base = self.integer_pointer_value(ptr)?;
                let ExprKind::Int(count) = index.kind else {
                    return None;
                };
                let pointee = self.pointee(ptr.ty)?;
                let size = i128::from(self.size_of(pointee).unwrap_or(1));
                let delta = count.checked_mul(size)?;
                if *sub {
                    base.checked_sub(delta)
                } else {
                    base.checked_add(delta)
                }
            }
            _ => None,
        }
    }

    /// The constant address of a *place*, in bytes, when it has one.
    ///
    /// A place has one only when it is reached from a pointer that is itself a
    /// constant — which is exactly the shape of the `offsetof` every C program
    /// wrote before `<stddef.h>` had one:
    ///
    /// ```c
    /// #define offsetof(T, m) ((size_t) &((T *) 0)->m)
    /// ```
    ///
    /// GCC folds it, calls the folding an extension, and rejects it under
    /// `-pedantic-errors`; the GNU dialects do the same here and the strict
    /// entry points keep the "not a compile-time constant expression" error.
    /// A named object is deliberately absent — its address is the linker's
    /// answer, not one this can give — and so is a bit-field, which has no
    /// address at all.
    fn place_offset(&mut self, place: &Place) -> Option<i128> {
        match &place.kind {
            PlaceKind::Deref(ptr) => self.integer_pointer_value(ptr),
            PlaceKind::Field {
                base,
                record,
                index,
            } => {
                let field = self.types().record(*record).fields.get(*index)?;
                if field.bits.is_some() {
                    return None;
                }
                let offset = i128::from(field.offset);
                let base = base.as_ref().clone();
                self.place_offset(&base)?.checked_add(offset)
            }
            PlaceKind::Index { base, index } => {
                let ExprKind::Int(count) = index.kind else {
                    return None;
                };
                let pointee = self.pointee(base.ty)?;
                let size = i128::from(self.size_of(pointee).unwrap_or(1));
                let base = self.integer_pointer_value(base)?;
                base.checked_add(count.checked_mul(size)?)
            }
            _ => None,
        }
    }

    /// Whether a pointer value is one the linker can work out: a null pointer,
    /// the address of something with static storage duration, or a constant
    /// offset from one.
    ///
    /// An *integer* constant converted to a pointer is here too. C11 6.6p9's
    /// list of address constants does not have it, but 6.6p10 lets an
    /// implementation accept other forms of constant expression and every one
    /// does: `(unsigned int *) 0xa000` is how a program names a memory-mapped
    /// register, and Rust's `0xa000 as *mut u32` is a constant expression as
    /// well. `execute/20021010-2` and `execute/pr23324` are the two in the
    /// torture suite.
    fn is_address_constant(&self, expr: &Expr) -> bool {
        match &expr.kind {
            // GNU makes `&&label` an address constant, which is what lets a
            // dispatch table be a block-scope `static void *t[] = { &&a };`.
            ExprKind::Zeroed
            | ExprKind::FuncAddr(_)
            | ExprKind::LabelAddr(_)
            | ExprKind::Int(_) => true,
            ExprKind::Cast(inner) => self.is_address_constant(inner),
            ExprKind::AddrOf(place) => self.is_static_place(place),
            ExprKind::PtrOffset { ptr, index, .. } => {
                self.is_address_constant(ptr) && matches!(index.kind, ExprKind::Int(_))
            }
            _ => false,
        }
    }

    fn is_static_place(&self, place: &Place) -> bool {
        match &place.kind {
            PlaceKind::Object(id) => {
                let storage = &self.program.object(*id).storage;
                // The address of a thread-local object is not a link-time
                // constant: there is one per thread, and no thread exists yet
                // when a static initialiser is evaluated. GCC says the same.
                !matches!(storage, Storage::Automatic) && !storage.is_thread_local()
            }
            PlaceKind::Str(_) => true,
            // `__real__ g` for a file-scope `g` is as static as `g` itself.
            PlaceKind::Field { base, .. } | PlaceKind::ComplexPart { base, .. } => {
                self.is_static_place(base)
            }
            PlaceKind::Index { base, index } => {
                self.is_address_constant(base) && matches!(index.kind, ExprKind::Int(_))
            }
            PlaceKind::Deref(ptr) => self.is_address_constant(ptr),
            // A block-scope compound literal has automatic storage duration,
            // so its address is not something the linker can work out; one at
            // file scope is an ordinary `Object` with static storage.
            PlaceKind::Temporary(_) | PlaceKind::CompoundLiteral { .. } => false,
        }
    }
}

/// Whether an expression is GNU's difference of two label addresses.
///
/// `&&a - &&b` is an integer constant expression in GCC — the whole point of
/// the idiom being a `static` table of offsets — and here it is the difference
/// of two label numbers, which nothing knows until the function's labels have
/// all been seen. A conversion around it changes nothing: the array the table goes
/// into is usually narrower than `ptrdiff_t`.
fn is_label_difference(expr: &Expr) -> bool {
    match &expr.kind {
        ExprKind::Cast(inner) => is_label_difference(inner),
        ExprKind::PtrDiff { lhs, rhs } => is_label_address(lhs) && is_label_address(rhs),
        _ => false,
    }
}

impl Sema<'_> {
    /// The dispatch table of label addresses whose contents are known for
    /// good, and its labels in order; see `crate::cfg`'s table fold.
    ///
    /// A `static` the body defined (an object from `first_object` on), or an
    /// automatic array it defines exactly once, whose initialiser is the
    /// addresses of distinct labels of `taken` and nothing else, which the
    /// body only ever reads as `table[e]` and no other
    /// static's initialiser names — in a function that defines no function of
    /// its own (one from `first_function` on), which could name it too.
    fn foldable_table(
        &self,
        body: &[Stmt],
        taken: &[ir::LabelId],
        first_object: u32,
        first_function: usize,
    ) -> Option<(ObjectId, Vec<ir::LabelId>)> {
        if taken.is_empty()
            || self.program.functions[first_function..]
                .iter()
                .any(|func| func.body.is_some())
        {
            return None;
        }
        // A `static` the body defined, with the initialiser its item gets, and
        // then an automatic array with the one its only definition gives it.
        // The automatic's initialiser runs where it is declared, so a `goto`
        // from before the declaration could reach a read of it before then;
        // the fold is right all the same, because the folded value is the
        // label's number whatever the array holds — it is never read.
        let statics = self
            .program
            .statics
            .iter()
            .filter(|var| {
                var.object.0 >= first_object
                    && matches!(
                        self.program.object(var.object).storage,
                        Storage::Static { .. }
                    )
            })
            .map(|var| (var.object, &var.init));
        let automatics = (first_object..self.program.objects.len() as u32)
            .map(ObjectId)
            .filter(|id| self.program.object(*id).storage == Storage::Automatic)
            .filter_map(|id| match ir::lets_of(body, id).as_slice() {
                [init] => Some((id, *init)),
                _ => None,
            });
        'candidates: for (object, init) in statics.chain(automatics) {
            let ExprKind::ArrayLit(items) = &init.kind else {
                continue;
            };
            let mut order: Vec<ir::LabelId> = Vec::with_capacity(items.len());
            for item in items {
                let mut item = item;
                while let ExprKind::Cast(inner) = &item.kind {
                    item = inner;
                }
                let ExprKind::LabelAddr(id) = item.kind else {
                    continue 'candidates;
                };
                if !taken.contains(&id) || order.contains(&id) {
                    continue 'candidates;
                }
                order.push(id);
            }
            if order.is_empty()
                || ir::stmts_use_object_beyond_reads(body, object)
                || self
                    .program
                    .statics
                    .iter()
                    .any(|other| other.object != object && ir::mentions_object(&other.init, object))
            {
                continue;
            }
            return Some((object, order));
        }
        None
    }
}

/// Whether an expression is a label address, through any conversions.
fn is_label_address(expr: &Expr) -> bool {
    match &expr.kind {
        ExprKind::LabelAddr(_) => true,
        ExprKind::Cast(inner) => is_label_address(inner),
        _ => false,
    }
}

/// Whether a declarator's type is one only its *initialiser* can complete.
///
/// C23's `auto x = e;` (and GNU's `__auto_type`) takes the whole type from the
/// initialiser, and `T x[] = { … }` takes the array's length from it. Those
/// two are checked together by [`Sema::typed_initializer`]; every other form
/// resolves its type from the declarator alone, so that the object can be in
/// scope for its own initialiser (C99 6.2.1p7). See [`Sema::declarator`].
fn type_from_initializer(declarator: &ast::InitDeclarator) -> bool {
    match &declarator.ty.kind {
        ast::TypeKind::Auto => true,
        // `auto *p = &a;` — the deduction happens through the declarator; see
        // [`auto_pointer_depth`].
        ast::TypeKind::Pointer(_) => {
            auto_pointer_depth(&declarator.ty).is_some() && declarator.init.is_some()
        }
        // `T x[] = { … }` takes its length from the list; `T x[];` with no
        // list at all is an *incomplete* array type, which is a declaration
        // rather than a mistake in the two places C99 6.9.2 allows it.
        ast::TypeKind::Array {
            size: ast::ArraySize::Unspecified,
            ..
        } => declarator.init.is_some(),
        _ => false,
    }
}

/// How many `*` stand between `auto` and the identifier, when the declarator
/// is nothing but a run of them.
///
/// C23 6.7.1p? asks the declarator of an inferred declaration to be "a plain
/// identifier, possibly with attributes", and GCC says so ("'auto' requires a
/// plain identifier ... as declarator"). Clang takes the pointer forms as a
/// documented extension — `auto *ptr = &a;` deduces `int` from an `int *`
/// initialiser and gives `ptr` the initialiser's own type — and `cinrs` takes
/// them too, exactly as it takes GCC's own extensions in every entry point.
/// `C23/n3007.c` is where both halves are checked: the deduction has to work,
/// and `auto *ptr2 = a;` with an `int` initialiser has to be refused.
///
/// `None` for anything that is not `auto` under a run of pointer derivations,
/// including a plain `auto` (which is [`ast::TypeKind::Auto`] and needs none
/// of this) and an array or function declarator, which C23 refuses outright.
fn auto_pointer_depth(ty: &ast::Type) -> Option<usize> {
    match &ty.kind {
        ast::TypeKind::Pointer(inner) => match &inner.kind {
            ast::TypeKind::Auto => Some(1),
            _ => auto_pointer_depth(inner).map(|depth| depth + 1),
        },
        _ => None,
    }
}

/// Where `auto` was written inside a function prototype, if it was.
///
/// C23 has it only on a declaration with an initialiser, so a parameter cannot
/// have it; a `typedef` stores the failure to resolve its type rather than
/// reporting it — the diagnostic belongs where the name is *used* — and this
/// is the one shape whose mistake is in the declaration itself, which is what
/// `C23/n3007.c`'s `typedef void (*fp)(auto);` asks about.
fn auto_in_prototype(ty: &ast::Type) -> Option<SourceRange> {
    match &ty.kind {
        ast::TypeKind::Pointer(inner) => auto_in_prototype(inner),
        ast::TypeKind::Array { elem, .. } => auto_in_prototype(elem),
        ast::TypeKind::Function(func) => func
            .params
            .iter()
            .find_map(|param| {
                matches!(param.ty.kind, ast::TypeKind::Auto)
                    .then_some(param.ty.range)
                    .or_else(|| auto_in_prototype(&param.ty))
            })
            .or_else(|| auto_in_prototype(&func.ret)),
        _ => None,
    }
}

/// The `int` a parameter no declaration list entry named has (C89 6.5.2).
fn implicit_int_type(range: SourceRange) -> ast::Type {
    ast::Type::plain(
        ast::TypeKind::Int {
            sign: ast::Sign::Signed,
            size: ast::IntSize::Int,
        },
        range,
    )
}