cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
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
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
//! Symbolic executor for the typed C program: evaluates one path of a function
//! into terms over the shared symbolic inputs, recording external calls, world
//! memory writes, coverage and the conditions under which behaviour is defined.

use super::ast::*;
use crate::image::{Image, SymKind};
use crate::sym::{Ctx, Escaped, Event, Mem, Open, R, Stop, UNINIT_EPOCH};
use crate::term::{T, mask};
use std::collections::{HashMap, HashSet};

/// Placement of the program's objects in the binary's address space.
#[derive(Clone)]
pub struct CEnv<'a> {
    pub prog: &'a Program,
    pub global_addr: Vec<Option<u32>>,
    /// Structures the compiler broke up into one object per member (LLVM's `name.0`,
    /// `name.1`, ...): (offset in the structure, size, address) of each part.  Such a structure
    /// has no address; only its members do.
    pub split: HashMap<u32, Vec<(u32, u32, u32)>>,
    pub func_addr: Vec<Option<u32>>,
    pub str_addr: Vec<Option<u32>>,
    /// Read-only data as the *source* defines it: (address, bytes).
    pub rom: Vec<(u32, Vec<u8>)>,
    /// The address ranges `rom` covers, merged: [start, end).
    pub rom_ranges: Vec<(u32, u32)>,
    /// Where a store through a pointer cannot land: the read-only segments of the image
    /// that hold constants (no object of the program that may be modified lives in one),
    /// and the constants elsewhere.
    pub no_store: Vec<(u32, u32)>,
    /// The read-only segments of the image: [start, end).
    ro_segments: Vec<(u32, u32)>,
    pub addr_to_func: HashMap<u32, u32>,
    /// Functions without a body, by the (odd) address the binary uses for them.
    pub ext_funcs: HashMap<u32, u32>,
    /// Functions defined in the source and present in the binary, by address: the possible
    /// targets of a call through a pointer that is not pinned to one value.
    pub targets: Vec<(u32, u32)>,
    /// Source functions that several symbols of the image could be: (function, candidate addresses).
    pub ambiguous: Vec<(u32, Vec<u32>)>,
    /// Further addresses at which the image has the code of a source function under the
    /// function's own name, beyond `func_addr` (filled in by the verifier, see
    /// `verify::resolve_ambiguous`): address -> function.  Each is verified against the
    /// source on its own, and a call the binary makes to any of them is the call the source
    /// makes to the function.
    pub copies: HashMap<u32, u32>,
    /// Names without a definition in the source that the symbol table gives to several
    /// addresses whose code is not the same instructions: (name -> number of addresses).
    /// A call compared under such a name assumes that they are one function.
    pub one_name: HashMap<String, u32>,
    /// Every address of a name without a definition in the source that the symbol table
    /// gives to several addresses: (address, name).
    pub several: Vec<(u32, String)>,
    /// Initialised pointers to string literals that do not point to the literal's bytes.
    pub data_notes: Vec<String>,
    /// Objects with internal linkage that the program never writes and whose address it never
    /// takes: (address, initial bytes).  Nothing can change them, so both sides may rely on
    /// their initial contents although they are not `const`.
    pub frozen: Vec<(u32, Vec<u8>)>,
    /// Functions whose calls may be compared as events (filled in by the verifier; empty
    /// means none).
    pub callable: Vec<bool>,
    /// Those of the program's functions that stand for C library functions (see
    /// `is_library`) and can be compared as calls, whether or not `callable` is in use.
    pub library: Vec<bool>,
    /// Per function and parameter, the values its callers pass when the function can only
    /// be entered from them (see `c::callers`; filled in by the verifier).
    pub callers: crate::c::callers::Callers,
    /// Functions the binary only has as a clone GCC specialised for its callers
    /// (`f.isra.0`, `f.constprop.0`): the clone's symbol (filled in by the verifier, which
    /// says how such code is compared).
    pub clones: HashMap<u32, String>,
    /// A function the source only declares whose symbol is at the address of a function the
    /// source defines (`__attribute__((alias))`, a linker-script alias): another name of
    /// that definition, and a call to it is a call to the definition.
    pub alias_of: Vec<Option<u32>>,
    /// For a function symbol that shares its address with others: the one name by which
    /// calls to that code are compared (the first in the symbol table, which is the name
    /// the binary's side of a call gets).
    pub canon: HashMap<String, String>,
    /// For each function and parameter: a pointer the function only borrows (see
    /// `borrow::borrowed_params`; filled in by the verifier, empty means none).
    pub borrowed: Vec<Vec<bool>>,
    /// Functions whose code in this binary callers may not rely on: an object file defines
    /// them weakly, and the linker may put another definition in their place.  A call to one
    /// is always compared as a call.
    pub replaceable: Vec<bool>,
    /// For each function of `library`: whether the program's definition was proved to do
    /// what the library function of that name does (filled in by the verifier), and if it
    /// was found not to, how it differs.
    pub library_proved: Vec<bool>,
    pub library_differs: Vec<(u32, String)>,
    /// A hosted program: the compiler may rely on what the C library promises.
    pub hosted: bool,
    /// Which type-based aliasing rules the source is held to.
    pub aliasing: Aliasing,
}

impl CEnv<'_> {
    /// A function of the program that its callers were compiled to treat as the C library
    /// function of that name.
    ///
    /// In a hosted program `memcpy`, `memmove` and `memset` are reserved names: the compiler
    /// gives a call to one of them the library's meaning whether or not the program defines
    /// the function (clang turns a call to the program's `memcpy` into `__aeabi_memcpy`, or
    /// into loads and stores).  Such a call is therefore the library call on the source side
    /// as well; the definition is verified against its own code like any function.
    pub fn is_library(&self, f: &crate::c::ast::Func) -> bool {
        self.hosted
            && f.body.is_some()
            && !f.is_static
            && f.ty.params.len() == 3
            && matches!(&*f.name, "memcpy" | "memmove" | "memset")
    }
}

/// How much of "an object is only accessed with its own type" the source is held to.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Aliasing {
    /// Nothing: the code was compiled with `-fno-strict-aliasing`.
    Off,
    /// What C11 6.5p6-7 says: a declared object has its declared type, and memory is not read
    /// with a type incompatible with the one it was last stored with.  Allocated storage may
    /// be given a new type by storing to it.
    Standard,
    /// What GCC and clang implement under `-fstrict-aliasing`: in addition, two accesses
    /// through incompatible types, one of them a store, do not touch the same memory in
    /// whatever order they come.  This is how the compilers justify moving a store across a
    /// load or another store, and it is all they know: they do not track which stores give
    /// allocated storage a new type.
    #[default]
    Compiler,
}

/// Which symbol of the image each source function and object is.
pub struct Binding {
    pub funcs: Vec<Option<u32>>,
    pub globals: Vec<Option<u32>>,
    /// Source functions (with a body) that several symbols could be, with the candidates.
    pub ambiguous: Vec<(u32, Vec<u32>)>,
}

/// `app` for `src/app.c`, `build/app.c.o`, `libfw.a(app.o)`.
fn file_stem(path: &str) -> &str {
    let path = match (path.rfind('('), path.ends_with(')')) {
        (Some(i), true) => &path[i + 1..path.len() - 1],
        _ => path,
    };
    let mut name = path.rsplit(['/', '\\']).next().unwrap_or(path);
    while let Some(i) = name.rfind('.') {
        if i == 0 || !matches!(&name[i + 1..], "o" | "obj" | "c" | "lo" | "i") {
            break;
        }
        name = &name[..i];
    }
    name
}

/// Remove the suffixes link-time optimisation adds when it makes a local symbol unique
/// (`.lto_priv.0`, `.llvm.123`, and for functions a bare `.1`).
fn strip_unique(name: &str, bare_number: bool) -> &str {
    let mut name = name;
    loop {
        let Some(i) = name.rfind('.') else { return name };
        let (head, tail) = (&name[..i], &name[i + 1..]);
        if i == 0 || tail.is_empty() || !tail.bytes().all(|c| c.is_ascii_digit()) {
            return name;
        }
        if let Some(h) = head.strip_suffix(".lto_priv").or_else(|| head.strip_suffix(".llvm")) {
            name = h;
        } else if bare_number {
            name = head;
        } else {
            return name;
        }
    }
}

/// Decide which symbol each source function and object corresponds to.
///
/// A name with external linkage is the global symbol of that name.  A name with internal
/// linkage may exist once per translation unit: the image's record of which file a local
/// symbol comes from (ELF `FILE` symbols, link-map contributions) selects the right one.
/// Function-local statics are `name.N` (GCC, numbered in declaration order within the file)
/// or `function.name` (clang).  What cannot be decided is left unbound: it is then reported as
/// absent or unverified rather than checked against the wrong code.
pub fn bind_symbols(prog: &Program, image: &Image) -> Binding {
    let unit_stems: Vec<&str> = prog.units.iter().map(|u| file_stem(u)).collect();
    // The unit a symbol's file denotes, if it is one of the program's (and only one).
    let unit_of = |s: &crate::image::Symbol| -> Option<usize> {
        let stem = file_stem(s.file.as_deref()?);
        let mut it = unit_stems.iter().enumerate().filter(|(_, u)| **u == stem);
        match (it.next(), it.next()) {
            (Some((i, _)), None) => Some(i),
            _ => None,
        }
    };
    // Choose among local symbols for an internal-linkage definition of unit `unit`;
    // `rivals` says whether other units define the same static name.
    let pick_static = |cands: &[&crate::image::Symbol], unit: usize, rivals: bool| -> Result<Option<u32>, Vec<u32>> {
        let mut addrs: Vec<u32> = Vec::new();
        let mut unknown: Vec<u32> = Vec::new();
        for s in cands {
            match unit_of(s) {
                Some(u) if u == unit => addrs.push(s.addr),
                Some(_) => {}
                None => unknown.push(s.addr),
            }
        }
        addrs.sort_unstable();
        addrs.dedup();
        unknown.sort_unstable();
        unknown.dedup();
        match (addrs.len(), unknown.len()) {
            (1, _) => Ok(Some(addrs[0])),
            (0, 0) => Ok(None),
            (0, 1) if !rivals => Ok(Some(unknown[0])),
            (0, _) => Err(unknown),
            _ => Err(addrs),
        }
    };
    let mut out = Binding {
        funcs: Vec::new(),
        globals: Vec::new(),
        ambiguous: Vec::new(),
    };
    for (i, f) in prog.funcs.iter().enumerate() {
        if f.body.is_none() {
            out.funcs.push(None);
            continue;
        }
        let cands: Vec<&crate::image::Symbol> = image
            .symbols
            .iter()
            .filter(|s| s.kind == SymKind::Func && (s.name == *f.name || strip_unique(&s.name, true) == &*f.name))
            .collect();
        let exact_global: Vec<&&crate::image::Symbol> =
            cands.iter().filter(|s| s.global && s.name == *f.name).collect();
        let a = if !f.is_static && exact_global.len() == 1 {
            Some(exact_global[0].addr)
        } else if !f.is_static && !cands.is_empty() && cands.iter().all(|s| s.addr == cands[0].addr) {
            Some(cands[0].addr)
        } else if cands.is_empty() {
            None
        } else {
            let unit = prog.func_unit.get(i).copied().unwrap_or(0) as usize;
            let rivals = prog
                .funcs
                .iter()
                .enumerate()
                .any(|(j, g)| j != i && g.body.is_some() && g.name == f.name);
            let locals: Vec<&crate::image::Symbol> = if f.is_static && cands.iter().any(|s| !s.global) {
                cands.iter().copied().filter(|s| !s.global).collect()
            } else {
                cands.clone()
            };
            match pick_static(&locals, unit, rivals) {
                Ok(a) => a,
                Err(c) => {
                    out.ambiguous.push((i as u32, c));
                    None
                }
            }
        };
        out.funcs.push(a);
    }
    // The function a local static is declared in: the last one starting before it in its file.
    let enclosing = |g: &Global| -> Option<&Func> {
        prog.funcs
            .iter()
            .filter(|f| f.body.is_some() && f.loc.file == g.loc.file && f.loc.line <= g.loc.line)
            .max_by_key(|f| f.loc.line)
    };
    let digits = |r: &str| !r.is_empty() && r.bytes().all(|c| c.is_ascii_digit());
    for (i, g) in prog.globals.iter().enumerate() {
        let unit = prog.global_unit.get(i).copied().unwrap_or(0) as usize;
        let objects = || image.symbols.iter().filter(|s| s.kind != SymKind::Func);
        let a = if g.is_local_static {
            // clang: `function.name`, `function.name.N` for a second one of that name.
            let clang: Vec<&crate::image::Symbol> = enclosing(g)
                .map(|f| {
                    let prefix = format!("{}.{}", f.name, g.name);
                    objects()
                        .filter(|s| {
                            let n = strip_unique(&s.name, false);
                            n == prefix
                                || n.strip_prefix(&prefix)
                                    .and_then(|r| r.strip_prefix('.'))
                                    .is_some_and(digits)
                        })
                        .filter(|s| unit_of(s).is_none_or(|u| u == unit))
                        .collect()
                })
                .unwrap_or_default();
            // GCC: `name.N`.
            let prefix = format!("{}.", g.name);
            let mut gcc: Vec<(u32, &crate::image::Symbol)> = objects()
                .filter_map(|s| {
                    let r = strip_unique(&s.name, false).strip_prefix(&prefix)?;
                    digits(r).then(|| (r.parse().unwrap_or(u32::MAX), s))
                })
                .filter(|(_, s)| unit_of(s).is_none_or(|u| u == unit))
                .collect();
            gcc.sort_by_key(|c| c.0);
            // The local statics of that name this may be, in declaration order: within the
            // function for clang, within the translation unit for GCC.
            let same_name = |same_fn: bool| -> Vec<usize> {
                let me = enclosing(g).map(|f| &*f.name as *const str);
                (0..prog.globals.len())
                    .filter(|&j| {
                        let h = &prog.globals[j];
                        h.is_local_static
                            && h.name == g.name
                            && prog.global_unit.get(j).copied().unwrap_or(0) as usize == unit
                            && (!same_fn || enclosing(h).map(|f| &*f.name as *const str) == me)
                    })
                    .collect()
            };
            if !clang.is_empty() {
                let peers = same_name(true);
                let mut c = clang;
                c.sort_by_key(|s| (s.name.len(), s.name.clone()));
                (c.len() == peers.len())
                    .then(|| peers.iter().position(|&j| j == i).map(|k| c[k].addr))
                    .flatten()
            } else if gcc.len() == 1 && same_name(false).len() == 1 {
                Some(gcc[0].1.addr)
            } else {
                // Several of that name: GCC numbers them in the order it emits them, which
                // is not the order of their declarations (and what a function's literal
                // pool points at may be a neighbour the object is reached from).  Only the
                // size tells them apart: the one of this object's size, if the name has one
                // object of that size.  Otherwise it stays unbound, and what uses it is
                // reported as not verified.
                let size = prog.size_of(g.ty);
                let sized: Vec<u32> = (gcc.iter())
                    .filter(|(_, s)| Some(s.size) == size)
                    .map(|(_, s)| s.addr)
                    .collect();
                let peers = same_name(false);
                let alike = (peers.iter())
                    .filter(|&&j| prog.size_of(prog.globals[j].ty) == size)
                    .count();
                let sure = gcc.iter().all(|(_, s)| unit_of(s) == Some(unit)) || prog.units.len() == 1;
                (sure && gcc.len() == peers.len() && alike == 1 && sized.len() == 1).then(|| sized[0])
            }
        } else {
            let cands: Vec<&crate::image::Symbol> = objects()
                .filter(|s| s.name == *g.name || strip_unique(&s.name, false) == &*g.name)
                .collect();
            let exact_global: Vec<&&crate::image::Symbol> =
                cands.iter().filter(|s| s.global && s.name == *g.name).collect();
            if !g.is_static && !exact_global.is_empty() {
                Some(exact_global[0].addr)
            } else if !g.is_static && !cands.is_empty() && cands.iter().all(|s| s.addr == cands[0].addr) {
                Some(cands[0].addr)
            } else if cands.is_empty() || !g.is_static {
                None
            } else {
                let rivals = prog
                    .globals
                    .iter()
                    .enumerate()
                    .any(|(j, h)| j != i && h.is_static && !h.is_local_static && h.name == g.name);
                let locals: Vec<&crate::image::Symbol> = if cands.iter().any(|s| !s.global) {
                    cands.iter().copied().filter(|s| !s.global).collect()
                } else {
                    cands.clone()
                };
                match pick_static(&locals, unit, rivals) {
                    Ok(a) => a,
                    Err(c) => {
                        // Tell them apart by their initial contents, if those are plain bytes.
                        let want = g.init.as_ref().filter(|i| i.relocs.is_empty()).map(|i| {
                            let mut b = i.bytes.clone();
                            b.resize(prog.size_of(g.ty).unwrap_or(0) as usize, 0);
                            b
                        });
                        let same: Vec<u32> = match &want {
                            Some(w) if !w.is_empty() => c
                                .iter()
                                .copied()
                                .filter(|&a| image.read(a, w.len() as u32) == Some(&w[..]))
                                .collect(),
                            _ => Vec::new(),
                        };
                        // Unique here, and no other unit's object of that name looks the same.
                        let twin = prog.globals.iter().enumerate().any(|(j, h)| {
                            j != i
                                && h.is_static
                                && !h.is_local_static
                                && h.name == g.name
                                && h.init.as_ref().map(|i| &i.bytes) == g.init.as_ref().map(|i| &i.bytes)
                        });
                        (same.len() == 1 && !twin).then(|| same[0])
                    }
                }
            }
        };
        out.globals.push(a);
    }
    out
}

/// Globals that some expression of the program may modify or take the address of: every use
/// other than reading the object, one of its members or one of its elements.
fn touched_globals(prog: &Program) -> HashSet<u32> {
    fn lv(e: &Expr, out: &mut HashSet<u32>) {
        // `e` is an lvalue that is only read.
        match &e.kind {
            EK::Global(_) => {}
            EK::Member(b, _) | EK::BitField(b, ..) => lv(b, out),
            EK::Deref(ptr) => {
                // Element of an array: `*(&array + index)`.
                let mut q: &Expr = ptr;
                loop {
                    match &q.kind {
                        EK::PtrAdd(inner, idx, _) => {
                            rv(idx, out);
                            q = inner;
                        }
                        EK::Cast(inner) => q = inner,
                        _ => break,
                    }
                }
                match &q.kind {
                    EK::Addr(inner) => lv(inner, out),
                    _ => rv(q, out),
                }
            }
            _ => rv(e, out),
        }
    }
    fn rv(e: &Expr, out: &mut HashSet<u32>) {
        match &e.kind {
            EK::Global(g) => {
                out.insert(*g);
            }
            EK::Load(l) => lv(l, out),
            EK::Const(_) | EK::FConst(_) | EK::Str(_) | EK::Local(_) | EK::Func(_) | EK::Prev | EK::VlaLive(_) => {}
            EK::Deref(a)
            | EK::Member(a, _)
            | EK::BitField(a, ..)
            | EK::Bits(a, ..)
            | EK::Addr(a)
            | EK::Cast(a)
            | EK::Neg(a)
            | EK::BitNot(a)
            | EK::VaStart(a)
            | EK::VaArg(a)
            | EK::Alloca(a, ..)
            | EK::LogNot(a) => rv(a, out),
            EK::Asm(a) => {
                if let Some(x) = &a.input {
                    rv(x, out);
                }
            }
            EK::Bin(_, a, b)
            | EK::PtrAdd(a, b, _)
            | EK::PtrDiff(a, b, _)
            | EK::LogAnd(a, b)
            | EK::LogOr(a, b)
            | EK::Comma(a, b)
            | EK::Assign(a, b)
            | EK::AssignOp(a, b, _) => {
                rv(a, out);
                rv(b, out);
            }
            EK::Cond(a, b, c) => {
                rv(a, out);
                rv(b, out);
                rv(c, out);
            }
            EK::Compound { items, .. } => items.iter().for_each(|(_, x)| rv(x, out)),
            EK::Call(f, args) => {
                rv(f, out);
                args.iter().for_each(|x| rv(x, out));
            }
        }
    }
    let mut out = HashSet::new();
    for g in &prog.globals {
        if let Some(init) = &g.init {
            for (_, sym, _) in &init.relocs {
                if let SymRef::Global(i) = sym {
                    out.insert(*i);
                }
            }
        }
    }
    for f in &prog.funcs {
        let Some(body) = &f.body else { continue };
        for b in &body.blocks {
            for op in &b.ops {
                match &op.kind {
                    OpKind::Eval(e) => rv(e, &mut out),
                    OpKind::Init { items, .. } => items.iter().for_each(|(_, x)| rv(x, &mut out)),
                }
            }
            match &b.term {
                Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => rv(e, &mut out),
                _ => {}
            }
        }
    }
    out
}

/// Addresses given to frozen objects the binary has no symbol for (the compiler folded every use).
const FROZEN_BASE: u32 = 0xf7f0_0000;

fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    hay.windows(needle.len()).position(|w| w == needle)
}

impl<'a> CEnv<'a> {
    pub fn new(prog: &'a Program, image: &Image) -> CEnv<'a> {
        crate::timing::mark("environment: start");
        let binding = bind_symbols(prog, image);
        crate::timing::mark("environment: bind symbols");
        let mut func_addr = Vec::new();
        let mut addr_to_func = HashMap::new();
        let mut ext_funcs = HashMap::new();
        for (i, f) in prog.funcs.iter().enumerate() {
            let a = if f.body.is_some() {
                binding.funcs[i]
            } else {
                // Defined elsewhere: a function of a linked image, or an undefined symbol of an object file.
                let a = image.func(&f.name).map(|s| s.addr).or_else(|| {
                    let mut it = image.externals.iter().filter(|(_, n)| **n == *f.name);
                    match (it.next(), it.next()) {
                        (Some((a, _)), None) => Some(*a & !1),
                        _ => None,
                    }
                });
                if let Some(a) = a {
                    ext_funcs.insert(a | 1, i as u32);
                }
                a
            };
            if let Some(a) = a
                && f.body.is_some()
            {
                addr_to_func.insert(a, i as u32);
            }
            func_addr.push(a);
        }
        let mut targets: Vec<(u32, u32)> = addr_to_func.iter().map(|(a, f)| (*a, *f)).collect();
        targets.sort_unstable();
        crate::timing::mark("environment: functions");
        let global_addr = binding.globals;
        // Where each string literal lives.  A literal an initialised object points to is where
        // the binary's copy of that object points, provided the source's bytes are there.  Any
        // other literal is looked up by content, outside the named objects (an object may hold
        // the same bytes without being the literal); the comparison of pointer values later
        // accepts any read-only copy of the same bytes, so the choice among copies is immaterial.
        let mut str_addr: Vec<Option<u32>> = vec![None; prog.strings.len()];
        let mut data_notes: Vec<String> = Vec::new();
        for (i, g) in prog.globals.iter().enumerate() {
            let (Some(addr), Some(init), true) = (global_addr[i], &g.init, g.defined) else {
                continue;
            };
            for (off, target, add) in &init.relocs {
                let SymRef::Str(sid) = target else { continue };
                let lit = &prog.strings[*sid as usize];
                let Some(ptr) = image.read(addr.wrapping_add(*off), 4) else {
                    continue;
                };
                let at = u32::from_le_bytes([ptr[0], ptr[1], ptr[2], ptr[3]]).wrapping_sub(*add as u32);
                if image.read_const(at, lit.len() as u32) == Some(&lit[..]) {
                    str_addr[*sid as usize] = Some(at);
                } else {
                    data_notes.push(format!(
                        "{}: the pointer at offset {off} does not point to the string literal \"{}\"",
                        g.name,
                        lit.escape_ascii().to_string().trim_end_matches("\\x00")
                    ));
                }
            }
        }
        // Labels the compiler made up for literals (`.L.str.12`, which clang keeps in the
        // symbol table of position-independent objects) do not name objects of the program.
        let in_object = |a: u32| {
            (image.symbols.iter()).any(|s| {
                s.kind == SymKind::Object
                    && s.size > 0
                    && a >= s.addr
                    && a - s.addr < s.size
                    && !s.name.starts_with(".L")
            })
        };
        // (The same literal occurs once per translation unit that includes its header.)
        let mut placed: HashMap<&[u8], Option<u32>> = HashMap::new();
        for (i, lit) in prog.strings.iter().enumerate() {
            if str_addr[i].is_some() || lit.is_empty() {
                continue;
            }
            if let Some(a) = placed.get(&lit[..]) {
                str_addr[i] = *a;
                continue;
            }
            str_addr[i] = image.segments.iter().filter(|seg| !seg.writable).find_map(|seg| {
                let mut from = 0;
                while let Some(o) = find_bytes(&seg.data[from..], lit) {
                    let a = seg.addr + (from + o) as u32;
                    if !in_object(a) {
                        return Some(a);
                    }
                    from += o + 1;
                }
                None
            });
            placed.insert(&lit[..], str_addr[i]);
        }
        crate::timing::mark("environment: string literals");
        let mut global_addr = global_addr;
        let touched = touched_globals(prog);
        let frozen_ids: Vec<usize> = (0..prog.globals.len())
            .filter(|&i| {
                let g = &prog.globals[i];
                g.is_static && g.defined && !g.is_volatile && !touched.contains(&(i as u32))
            })
            .collect();
        // A frozen object without a symbol gets an address of its own: nothing but its contents matters.
        let mut next = FROZEN_BASE;
        let mut made_up = Vec::new();
        for &i in &frozen_ids {
            if global_addr[i].is_none() && image.object(&prog.globals[i].name).is_none() {
                made_up.push(i);
                global_addr[i] = Some(next);
                next += prog.size_of(prog.globals[i].ty).unwrap_or(4).next_multiple_of(16) + 16;
            }
        }
        let mut env = CEnv {
            prog,
            split: split_globals(prog, image, &global_addr),
            global_addr,
            func_addr,
            str_addr,
            rom: Vec::new(),
            rom_ranges: Vec::new(),
            no_store: Vec::new(),
            ro_segments: Vec::new(),
            addr_to_func,
            ext_funcs,
            targets,
            frozen: Vec::new(),
            ambiguous: binding.ambiguous,
            copies: HashMap::new(),
            one_name: HashMap::new(),
            several: Vec::new(),
            data_notes,
            callable: Vec::new(),
            library: Vec::new(),
            callers: Default::default(),
            clones: HashMap::new(),
            alias_of: Vec::new(),
            canon: HashMap::new(),
            borrowed: Vec::new(),
            replaceable: Vec::new(),
            library_proved: Vec::new(),
            library_differs: Vec::new(),
            hosted: crate::c::target::Target::for_image(image).hosted != Some(false),
            aliasing: Aliasing::default(),
        };
        // An object that exists only in the source and whose contents are not known (it
        // points to something that was not located in the binary) is not an object of the
        // world with arbitrary contents: what uses it cannot be verified.
        for &i in &made_up {
            if env.init_bytes(i as u32).is_none() {
                env.global_addr[i] = None;
            }
        }
        for &i in &frozen_ids {
            if let (Some(addr), Some(bytes)) = (env.global_addr[i], env.init_bytes(i as u32)) {
                env.rom.push((addr, bytes.clone()));
                env.frozen.push((addr, bytes));
            }
        }
        for (i, s) in prog.strings.iter().enumerate() {
            if let Some(a) = env.str_addr[i] {
                env.rom.push((a, s.to_vec()));
            }
        }
        for (i, g) in prog.globals.iter().enumerate() {
            if !g.is_const || !g.defined {
                continue;
            }
            let Some(addr) = env.global_addr[i] else { continue };
            if let Some(bytes) = env.init_bytes(i as u32) {
                env.rom.push((addr, bytes));
            }
        }
        env.ro_segments = (image.segments.iter())
            .filter(|s| !s.writable)
            .map(|s| (s.addr, s.addr + s.data.len() as u32))
            .collect();
        env.merge_rom_ranges();
        crate::timing::mark("environment: constants");
        env
    }

    fn merge_rom_ranges(&mut self) {
        let mut ranges: Vec<(u32, u32)> = self
            .rom
            .iter()
            .filter(|(_, b)| !b.is_empty())
            .map(|(a, b)| (*a, a + b.len() as u32))
            .collect();
        ranges.sort_unstable();
        self.rom_ranges.clear();
        for (lo, hi) in ranges {
            match self.rom_ranges.last_mut() {
                // Alignment gaps between constants are not objects either: merge across small gaps.
                Some(last) if lo <= last.1 + 8 => last.1 = last.1.max(hi),
                _ => self.rom_ranges.push((lo, hi)),
            }
        }
        self.no_store.clear();
        // Nothing the program may store to lives in memory the image marks read-only: what is
        // there is code, objects defined `const`, string literals and the compiler's own
        // constants.  (Taken as a whole where that is a handful of ranges; an object file
        // with a section per function has too many to state for every store.)
        let mut ro = self.ro_segments.clone();
        ro.sort_unstable();
        let mut merged: Vec<(u32, u32)> = Vec::new();
        for (lo, hi) in ro {
            match merged.last_mut() {
                Some(last) if lo <= last.1 + 64 => last.1 = last.1.max(hi),
                _ => merged.push((lo, hi)),
            }
        }
        if merged.len() <= 4 {
            // (Constants the source has and the image does not are placed outside it.)
            let outside: Vec<(u32, u32)> = (self.rom_ranges.iter().copied())
                .filter(|r| !merged.iter().any(|s| r.0 >= s.0 && r.1 <= s.1))
                .collect();
            self.no_store = merged;
            self.no_store.extend(outside);
            return;
        }
        for i in 0..self.rom_ranges.len() {
            let (lo, hi) = self.rom_ranges[i];
            let seg = self.ro_segments.iter().find(|s| lo >= s.0 && hi <= s.1);
            let r = seg.map_or((lo, hi), |&s| s);
            if !self.no_store.contains(&r) {
                self.no_store.push(r);
            }
        }
    }

    /// Place (or displace, or with `None` remove) source function `fid`, whatever the symbol
    /// table says: discovery decides by proof which code a function is.
    pub fn set_func(&mut self, fid: u32, addr: Option<u32>) {
        if let Some(old) = self.func_addr[fid as usize].take() {
            if self.addr_to_func.get(&old) == Some(&fid) {
                self.addr_to_func.remove(&old);
            }
            self.targets.retain(|t| t.1 != fid);
        }
        self.ambiguous.retain(|a| a.0 != fid);
        if let Some(a) = addr {
            self.bind_func(fid, a);
        }
    }

    /// Place object `gid` at `addr`, whatever the symbol table says.  String literals its
    /// initialiser points to are then where the image's copy of the object points, as for an
    /// object placed by its symbol.
    pub fn set_global(&mut self, image: &Image, gid: u32, addr: u32) {
        let g = &self.prog.globals[gid as usize];
        let old = self.global_addr[gid as usize].replace(addr);
        let mut was_frozen = false;
        if let Some(old) = old {
            was_frozen = self.frozen.iter().any(|r| r.0 == old);
            self.rom.retain(|r| r.0 != old);
            self.frozen.retain(|r| r.0 != old);
        }
        for (off, target, add) in g.init.iter().flat_map(|i| &i.relocs) {
            let SymRef::Str(sid) = target else { continue };
            let lit = &self.prog.strings[*sid as usize];
            let Some(ptr) = image.read(addr.wrapping_add(*off), 4) else {
                continue;
            };
            let at = u32::from_le_bytes([ptr[0], ptr[1], ptr[2], ptr[3]]).wrapping_sub(*add as u32);
            if image.read_const(at, lit.len() as u32) == Some(&lit[..]) && self.str_addr[*sid as usize] != Some(at) {
                self.str_addr[*sid as usize] = Some(at);
                self.rom.push((at, lit.to_vec()));
            }
        }
        if g.defined
            && (g.is_const || was_frozen)
            && let Some(bytes) = self.init_bytes(gid)
        {
            if was_frozen {
                self.frozen.push((addr, bytes.clone()));
            }
            self.rom.push((addr, bytes));
        }
        self.merge_rom_ranges();
    }

    /// Does the image hold the initial value of object `gid` at `at`?  Pointers to string
    /// literals may point to any copy of the literal.
    pub fn matches_at(&self, image: &Image, gid: u32, at: u32) -> bool {
        let g = &self.prog.globals[gid as usize];
        let Some(size) = self.prog.size_of(g.ty) else {
            return false;
        };
        let Some(have) = image.read_const(at, size) else {
            return false;
        };
        let mut want = g.init.as_ref().map(|i| i.bytes.clone()).unwrap_or_default();
        want.resize(size as usize, 0);
        let mut skip = vec![false; size as usize];
        for (off, target, add) in g.init.iter().flat_map(|i| &i.relocs) {
            let o = *off as usize;
            let Some(w) = have.get(o..o + 4) else { return false };
            let w = u32::from_le_bytes([w[0], w[1], w[2], w[3]]).wrapping_sub(*add as u32);
            let ok = match target {
                SymRef::Str(s) => {
                    let lit = &self.prog.strings[*s as usize];
                    image.read_const(w, lit.len() as u32) == Some(&lit[..])
                }
                SymRef::Global(i) => self.global_addr[*i as usize] == Some(w),
                SymRef::Func(i) => self.func_addr[*i as usize].map(|a| a | 1) == Some(w),
            };
            if !ok {
                return false;
            }
            skip[o..o + 4].fill(true);
        }
        (0..size as usize).all(|i| skip[i] || want[i] == have[i])
    }

    /// Is `addr` an address this environment invented for an object the binary does not contain?
    pub fn is_synthetic(&self, addr: u32) -> bool {
        addr >= FROZEN_BASE && self.frozen.iter().any(|(a, _)| *a == addr)
    }

    /// Record that source function `fid` is the code at `addr`.
    pub fn bind_func(&mut self, fid: u32, addr: u32) {
        self.func_addr[fid as usize] = Some(addr);
        self.addr_to_func.insert(addr, fid);
        self.targets.push((addr, fid));
        self.targets.sort_unstable();
    }

    /// Initial bytes of a defined global with relocations resolved; None if a referenced address is unknown.
    pub fn init_bytes(&self, g: u32) -> Option<Vec<u8>> {
        let gl = &self.prog.globals[g as usize];
        let size = self.prog.size_of(gl.ty)? as usize;
        let Some(init) = &gl.init else {
            return Some(vec![0; size]);
        };
        // Longer than the type when a flexible array member is initialised.
        let mut bytes = init.bytes.clone();
        if bytes.len() < size {
            bytes.resize(size, 0);
        }
        for (off, sym, add) in &init.relocs {
            let base = match sym {
                SymRef::Global(i) => self.global_addr[*i as usize]?,
                SymRef::Func(i) => self.func_addr[*i as usize]? | 1,
                SymRef::Str(i) => self.str_addr[*i as usize]?,
            };
            let v = base.wrapping_add(*add as u32);
            bytes
                .get_mut(*off as usize..*off as usize + 4)?
                .copy_from_slice(&v.to_le_bytes());
        }
        Some(bytes)
    }

    fn rom_read(&self, addr: u32, size: u8) -> Option<u64> {
        for (base, bytes) in &self.rom {
            if addr >= *base && (addr - base) as usize + size as usize <= bytes.len() {
                let o = (addr - base) as usize;
                let mut v = 0u64;
                for i in (0..size as usize).rev() {
                    v = v << 8 | bytes[o + i] as u64;
                }
                return Some(v);
            }
        }
        None
    }

    fn in_rom(&self, addr: u32) -> bool {
        self.rom
            .iter()
            .any(|(b, d)| addr >= *b && ((addr - b) as usize) < d.len())
    }

    /// Value of never-written memory as seen by the C program.
    pub fn initial(&self, ctx: &mut Ctx, addr: T, size: u8, epoch: u32) -> T {
        if ctx.region(addr).is_some() {
            return ctx.tm.load(UNINIT_EPOCH, addr, size);
        }
        let (_, k) = ctx.tm.linear(addr);
        if self.in_rom(k as u32) {
            if let Some(a) = ctx.unique_value(addr)
                && let Some(v) = self.rom_read(a as u32, size)
            {
                return ctx.tm.konst(size * 8, v);
            }
            return ctx.tm.load(0, addr, size);
        }
        ctx.tm.load(epoch, addr, size)
    }
}

/// Result of comparing two constant byte strings with `strcmp`/`memcmp`: zero when equal, otherwise
/// a symbol of which only the sign is known.  The symbol is named after the operands so that the
/// machine side, should it make the same library call, obtains the same value.
pub fn compare_result(ctx: &mut Ctx, a: &[u8], b: &[u8]) -> T {
    let zero = ctx.tm.konst(32, 0);
    if a == b {
        return zero;
    }
    let hex = |s: &[u8]| s.iter().map(|b| format!("{b:02x}")).collect::<String>();
    let v = ctx.named_sym(&format!("cmp:{}:{}", hex(a), hex(b)), 32);
    ctx.unspecified.insert(v);
    let sign = if a < b {
        ctx.tm.slt(v, zero)
    } else {
        ctx.tm.slt(zero, v)
    };
    // A fact about the library function, recorded with the path's side conditions.
    if !ctx.ub.contains(&sign) {
        ctx.ub.push(sign);
    }
    v
}

/// The bytes before the first NUL in `s`, as `strcmp` sees them.
pub fn c_str(s: &[u8]) -> Option<&[u8]> {
    s.iter().position(|&b| b == 0).map(|n| &s[..n])
}

/// Leading zeros of a 64-bit value as a 32-bit count.
fn clz64(ctx: &mut Ctx, v: T) -> T {
    let hi = ctx.tm.extract(v, 32, 32);
    let lo = ctx.tm.extract(v, 0, 32);
    let hz = ctx.tm.nonzero(hi);
    let a = ctx.tm.clz(hi);
    let b = ctx.tm.clz(lo);
    let b = ctx.tm.add_const(b, 32);
    ctx.tm.ite(hz, a, b)
}

/// The operands that stand beside the old value (`EK::Prev`) in the new value of a compound
/// assignment, from left to right.  False if the old value is not reached through
/// conversions, unary and binary operators only (nothing is then evaluated ahead).
fn beside_prev<'e>(e: &'e Expr, out: &mut Vec<&'e Expr>) -> bool {
    fn has_prev(e: &Expr) -> bool {
        matches!(e.kind, EK::Prev) || e.children().into_iter().any(has_prev)
    }
    match &e.kind {
        EK::Prev => true,
        EK::Bin(_, a, b) => match (has_prev(a), has_prev(b)) {
            (true, false) => {
                let ok = beside_prev(a, out);
                out.push(b);
                ok
            }
            (false, true) => {
                out.push(a);
                beside_prev(b, out)
            }
            _ => false,
        },
        _ => {
            let kids = e.children();
            kids.len() == 1 && beside_prev(kids[0], out)
        }
    }
}

/// Library functions of one `int` whose value a compiler of a hosted program computes itself
/// (GCC and clang treat them as built-in): the value, as both sides of a proof see it.
/// `isdigit` and `isascii` are specified to return "non-zero"; the value here is the one the
/// compilers produce, 1 (see `Ctx::library_values` for a binary that calls the library).
pub fn library_value(ctx: &mut Ctx, name: &str, v: T) -> Option<T> {
    if ctx.tm.width(v) != 32 {
        return None;
    }
    let tm = &mut ctx.tm;
    Some(match name {
        "isdigit" => {
            let d = tm.add_const(v, (-48i64) as u64);
            let ten = tm.konst(32, 10);
            let b = tm.ult(d, ten);
            tm.zext(b, 32)
        }
        "isascii" => {
            let lim = tm.konst(32, 128);
            let b = tm.ult(v, lim);
            tm.zext(b, 32)
        }
        "toascii" => {
            let m = tm.konst(32, 0x7f);
            tm.and(v, m)
        }
        "abs" | "labs" => {
            let z = tm.konst(32, 0);
            let neg = tm.slt(v, z);
            let n = tm.neg(v);
            tm.ite(neg, n, v)
        }
        "ffs" | "ffsl" => {
            let nz = tm.nonzero(v);
            let t = ctz(ctx, v);
            let t1 = ctx.tm.add_const(t, 1);
            let zero = ctx.tm.konst(32, 0);
            ctx.tm.ite(nz, t1, zero)
        }
        _ => return None,
    })
}

/// One plus the index of the lowest set bit, zero for zero, as a 32-bit count.
pub fn ffs(tm: &mut crate::term::Terms, v: T) -> T {
    let nz = tm.nonzero(v);
    let c = tm.ctz(v);
    let c = tm.resize(c, 32, false);
    let c1 = tm.add_const(c, 1);
    let zero = tm.konst(32, 0);
    tm.ite(nz, c1, zero)
}

/// The number of leading bits equal to the sign bit, less the sign bit itself, as a 32-bit
/// count.
pub fn clrsb(tm: &mut crate::term::Terms, v: T) -> T {
    let w = tm.width(v);
    let sign = tm.ashr_c(v, w as u32 - 1);
    let y = tm.xor(v, sign);
    let nz = tm.nonzero(y);
    let lz = tm.clz(y);
    let lz = tm.resize(lz, 32, false);
    let lz1 = tm.add_const(lz, u32::MAX as u64);
    let all = tm.konst(32, w as u64 - 1);
    tm.ite(nz, lz1, all)
}

/// Where `strchr(s, c)` finds `c` in the string `s` (given without its terminator, which is
/// part of what is searched).
pub fn strchr_index(s: &[u8], c: u64) -> Option<usize> {
    let c = c as u8;
    if c == 0 {
        Some(s.len())
    } else {
        s.iter().position(|&b| b == c)
    }
}

/// `memcmp` of one byte, as the compilers expand it: the difference of the two bytes.
pub fn byte_difference(ctx: &mut Ctx, a: T, b: T) -> T {
    let (a, b) = (ctx.tm.zext(a, 32), ctx.tm.zext(b, 32));
    ctx.tm.sub(a, b)
}

/// Trailing zeros (of a non-zero 32- or 64-bit value) as a 32-bit count: the lowest set bit
/// `v & -v` has `width - 1 - ctz` leading zeros.
fn ctz(ctx: &mut Ctx, v: T) -> T {
    let w = ctx.tm.width(v);
    let n = ctx.tm.neg(v);
    let low = ctx.tm.and(v, n);
    let lz = if w == 64 { clz64(ctx, low) } else { ctx.tm.clz(low) };
    let k = ctx.tm.konst(32, w as u64 - 1);
    ctx.tm.sub(k, lz)
}

/// Number of set bits as a 32-bit count.
fn popcount(ctx: &mut Ctx, v: T) -> T {
    let w = ctx.tm.width(v);
    let mut terms = Vec::with_capacity(w as usize);
    for i in 0..w {
        let b = ctx.tm.extract(v, i, 1);
        terms.push((ctx.tm.zext(b, 32), 1u64));
    }
    ctx.tm.mk_sum(32, terms, 0)
}

/// Assigning an object to one that partly overlaps it is undefined (C11 6.5.16.1p3), as is
/// memcpy between overlapping objects: record that the two are identical or disjoint.
/// Whether an object of type `outer` may hold an object of type `inner`: the same type, an
/// array or structure with such a member, or a large enough character array or a union,
/// which are routinely reused as storage for anything.
fn may_contain(p: &Program, outer: TypeId, inner: TypeId) -> bool {
    let outer = p.unqual(outer);
    if outer == inner {
        return true;
    }
    match p.ty(outer) {
        Type::Array(el, _) if matches!(p.ty(p.unqual(*el)), Type::Int { size: 1, .. }) => {
            p.size_of(outer).is_none_or(|n| n >= p.size_of(inner).unwrap_or(0))
        }
        Type::Array(el, _) => may_contain(p, *el, inner),
        Type::Record(r) => {
            let r = &p.records[*r as usize];
            r.is_union || r.fields.iter().any(|f| may_contain(p, f.ty, inner))
        }
        _ => false,
    }
}

/// How a scalar type takes part in type-based aliasing: None for character types (they may
/// access anything) and for aggregates.  Integers of one size are one class whatever their
/// signedness, and so are all pointers: nothing a compiler distinguishes is merged.
fn alias_class(p: &Program, ty: TypeId) -> Option<(u8, u8)> {
    match p.ty(p.unqual(ty)) {
        Type::Int { size: 1, .. } => None,
        Type::Int { size, .. } => Some((0, *size)),
        Type::Ptr(_) => Some((1, 4)),
        Type::Float { size } => Some((2, *size)),
        Type::Bool => Some((3, 1)),
        _ => None,
    }
}

/// Can an object declared with type `decl` hold a scalar of the given aliasing class?
fn may_hold(p: &Program, decl: TypeId, class: (u8, u8)) -> bool {
    match p.ty(p.unqual(decl)) {
        Type::Array(el, _) => may_hold(p, *el, class),
        Type::Record(r) => {
            let r = &p.records[*r as usize];
            r.is_union || r.fields.iter().any(|f| f.bits.is_some() || may_hold(p, f.ty, class))
        }
        Type::Void | Type::Func(_) => true,
        _ => alias_class(p, decl).is_none_or(|c| c == class),
    }
}

/// The least number of characters `printf` produces for a format: the literal characters
/// plus what each conversion cannot go below.  Anything not understood counts as nothing.
fn printf_min_len(fmt: &[u8]) -> u32 {
    let fmt = &fmt[..fmt.iter().position(|&c| c == 0).unwrap_or(fmt.len())];
    let (mut n, mut i) = (0u32, 0);
    while i < fmt.len() {
        if fmt[i] != b'%' {
            n += 1;
            i += 1;
            continue;
        }
        i += 1;
        while i < fmt.len() && b"-+ #0".contains(&fmt[i]) {
            i += 1;
        }
        let mut width = 0u32;
        while i < fmt.len() && fmt[i].is_ascii_digit() {
            width = width.saturating_mul(10).saturating_add((fmt[i] - b'0') as u32);
            i += 1;
        }
        let mut plain = true;
        if i < fmt.len() && fmt[i] == b'*' {
            i += 1;
        }
        if i < fmt.len() && fmt[i] == b'.' {
            plain = false;
            i += 1;
            while i < fmt.len() && (fmt[i].is_ascii_digit() || fmt[i] == b'*') {
                i += 1;
            }
        }
        while i < fmt.len() && b"hljztL".contains(&fmt[i]) {
            i += 1;
        }
        let least = match fmt.get(i) {
            Some(b'%') => 1,
            Some(b'd' | b'i' | b'u' | b'x' | b'X' | b'o' | b'c') if plain => 1,
            _ => 0,
        };
        n += least.max(width.min(4095));
        i += 1;
    }
    n.min(i32::MAX as u32)
}

fn no_partial_overlap(ctx: &mut Ctx, dst: T, src: T, size: u32) {
    if dst == src || size == 0 {
        return;
    }
    let n = ctx.tm.konst(32, size as u64);
    let d1 = ctx.tm.sub(dst, src);
    let d2 = ctx.tm.sub(src, dst);
    let a = ctx.tm.ult(d1, n);
    let b = ctx.tm.ult(d2, n);
    let same = ctx.tm.eq(dst, src);
    let far = ctx.tm.or(a, b);
    let far = ctx.tm.not(far);
    let ok = ctx.tm.or(same, far);
    if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
        ctx.ub.push(ok);
    }
}

/// Largest `alloca` block or variable-length array, in bytes: a program that allocates more
/// than its stack can hold has no defined behaviour, and no stack of a microcontroller holds
/// this much.  (The bound also keeps a frame well inside the megabyte below the entry stack
/// pointer that the machine model takes to be the function's own.)
pub const MAX_DYN: u32 = 0x1_0000;

/// Most objects of dynamic size created on one path.
const MAX_DYN_OBJECTS: u32 = 8;

/// Longest memset/memcpy that is modelled as individual memory writes.
pub const MAX_MEM_INLINE: u64 = 1024;

/// Fill `n` bytes at `dst` with `byte` (an 8-bit term).
pub fn mem_fill(ctx: &mut Ctx, mem: &mut Mem, dst: T, byte: T, n: u32) {
    let b2 = ctx.tm.concat(byte, byte);
    let b4 = ctx.tm.concat(b2, b2);
    let mut off = 0;
    while off < n {
        let (sz, v) = if n - off >= 4 {
            (4, b4)
        } else if n - off >= 2 {
            (2, b2)
        } else {
            (1, byte)
        };
        let a = ctx.tm.add_const(dst, off as u64);
        ctx.mem_write(mem, a, sz, v);
        off += sz as u32;
    }
}

#[derive(Clone, PartialEq)]
struct Frame {
    func: u32,
    locals: Vec<T>,
    /// Objects allocated with `alloca` or for variable-length arrays; they die with the frame.
    allocas: Vec<T>,
    /// Live variable-length arrays: (declaration, object).
    vlas: Vec<(u32, T)>,
    /// Base of the variable-argument area of a variadic function.
    va: Option<T>,
}

/// Position, in the AAPCS argument word sequence (r0-r3 are words 0-3, the stack follows), of
/// the first variable argument of a function whose named parameters have the given shapes.
pub fn va_start_word(shapes: &[(u32, bool)], first_reg: u8) -> u32 {
    let mut next = first_reg as u32;
    for locs in crate::sym::arg_words(shapes, first_reg) {
        for l in locs {
            next = next.max(match l {
                crate::sym::WordLoc::Reg(n) => n as u32 + 1,
                crate::sym::WordLoc::Stack(off) => 4 + off / 4 + 1,
            });
        }
    }
    next
}

/// One access to world memory through a typed lvalue (or an untyped copy), for the aliasing
/// rules of the language.
#[derive(Clone, Debug)]
struct Access {
    seq: u64,
    addr: T,
    size: u32,
    /// Type of the object the access path starts from (what the dereferenced pointer points
    /// to, or the declared type), and type of the lvalue itself.
    base: TypeId,
    refty: TypeId,
    /// Where in that object the lvalue is, for a path of members only (`p->a.b`).
    off: Option<u32>,
    store: bool,
    /// Number of sequence points passed when the access was made.
    sp: u64,
    /// The access was made in an arm of a merged region: only where this condition holds.
    guard: Option<T>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Class {
    /// Character types: may be used to access any object.
    Char,
    Bool,
    Int(u8),
    Float(u8),
    Ptr,
    Other,
}

fn class(p: &Program, t: TypeId) -> Class {
    match p.ty(p.unqual(t)) {
        Type::Int { size: 1, .. } => Class::Char,
        Type::Bool => Class::Bool,
        Type::Int { size, .. } => Class::Int(*size),
        Type::Float { size } => Class::Float(*size),
        Type::Ptr(_) => Class::Ptr,
        _ => Class::Other,
    }
}

fn strip_arrays(p: &Program, mut t: TypeId) -> TypeId {
    while let Type::Array(e, _) = p.ty(p.unqual(t)) {
        t = *e;
    }
    p.unqual(t)
}

fn record_of(p: &Program, t: TypeId) -> Option<u32> {
    match p.ty(strip_arrays(p, t)) {
        Type::Record(r) => Some(*r),
        _ => None,
    }
}

/// Does record `a` contain an object of record type `b` (or is it `b`)?
fn record_contains_record(p: &Program, a: u32, b: u32, depth: u32) -> bool {
    p.records_may_match(a, b)
        || depth < 16
            && p.records[a as usize]
                .fields
                .iter()
                .any(|f| record_of(p, f.ty).is_some_and(|r| record_contains_record(p, r, b, depth + 1)))
}

/// Does record `r` contain a scalar of class `c` (or a character, which stands for anything)?
fn record_contains_class(p: &Program, r: u32, c: Class, depth: u32) -> bool {
    p.records[r as usize].fields.iter().any(|f| match record_of(p, f.ty) {
        Some(inner) => depth < 16 && record_contains_class(p, inner, c, depth + 1),
        None => {
            let fc = class(p, strip_arrays(p, f.ty));
            fc == c || fc == Class::Char || fc == Class::Other
        }
    })
}

/// May two lvalues designate overlapping memory as far as their types are concerned
/// (C11 6.5p7, read the way GCC and clang implement it)?
fn types_may_alias(p: &Program, x: &Access, y: &Access) -> bool {
    if p.may_alias {
        // Some type of the program is declared `may_alias`: which accesses go through it is
        // not tracked, so no access is told apart from another by its type.
        return true;
    }
    let (rx, ry) = (class(p, x.refty), class(p, y.refty));
    // Members of two structure types neither of which is part of the other: GCC tells them
    // apart by the structure types alone, whatever the type of the members (a `uint8_t`
    // member included).
    if let (Some(a), Some(b)) = (record_of(p, x.base), record_of(p, y.base))
        && !record_contains_record(p, a, b, 0)
        && !record_contains_record(p, b, a, 0)
    {
        return false;
    }
    if rx == Class::Char || ry == Class::Char || rx == Class::Other || ry == Class::Other {
        return true;
    }
    match (record_of(p, x.base), record_of(p, y.base)) {
        // Members of two structure types: only if one type is part of the other.
        (Some(a), Some(b)) => record_contains_record(p, a, b, 0) || record_contains_record(p, b, a, 0),
        (Some(a), None) => rx == ry && record_contains_class(p, a, ry, 0),
        (None, Some(b)) => rx == ry && record_contains_class(p, b, rx, 0),
        (None, None) => rx == ry,
    }
}

/// The same by the letter of C11 6.5p7 alone: only the types of the two lvalues count.  A
/// member of character type, or two members of the same scalar type in two structure types,
/// may be the same bytes (telling them apart by the structure types is the compilers'
/// reading, see `types_may_alias`).
fn lvalues_may_alias(p: &Program, x: &Access, y: &Access) -> bool {
    if p.may_alias {
        return true;
    }
    let (rx, ry) = (class(p, x.refty), class(p, y.refty));
    // (Whatever the compilers' reading lets overlap does here too: unions, related types.)
    types_may_alias(p, x, y)
        || rx == Class::Char
        || ry == Class::Char
        || rx == Class::Other
        || ry == Class::Other
        || rx == ry
}

/// The type an access path starts from: for `p->a.b[i]` the type `p` points to, for a
/// declared object its declared type.
fn access_base(e: &Expr) -> TypeId {
    match &e.kind {
        EK::Member(b, _) | EK::BitField(b, ..) => access_base(b),
        EK::Deref(ptr) => {
            let mut q: &Expr = ptr;
            while let EK::PtrAdd(inner, ..) = &q.kind {
                q = inner;
            }
            match &q.kind {
                EK::Addr(inner) => access_base(inner),
                _ => e.ty,
            }
        }
        _ => e.ty,
    }
}

/// Where the lvalue lies in the object its access path starts from (see `access_base`), if
/// the path is made of members only.
fn access_offset(e: &Expr) -> Option<u32> {
    match &e.kind {
        EK::Member(b, off) => Some(access_offset(b)? + off),
        EK::BitField(..) => None,
        EK::Deref(ptr) => match &ptr.kind {
            EK::PtrAdd(..) => None,
            EK::Addr(inner) => access_offset(inner),
            _ => Some(0),
        },
        _ => Some(0),
    }
}

/// Accesses remembered per path for the aliasing rules.
const MAX_ACCESSES: usize = 96;

/// Bounds of the object an lvalue belongs to: (base address, size in bytes).
type Bounds = Option<(T, u32)>;

#[derive(Clone)]
pub struct CExec<'a> {
    pub env: &'a CEnv<'a>,
    pub mem: Mem,
    pub events: Vec<Event>,
    /// Calls that may return twice, made from an activation that has since ended: (index of
    /// the event, number of events made when the activation ended).  A second return after
    /// that is undefined (C11 7.13.2.1p2).
    pub rt_ended: Vec<(usize, usize)>,
    /// The path ended by running off the end of a `naked` function.
    pub fell_off: bool,
    /// Such calls made from activations still running: (index of the event, depth).
    rt_open: Vec<(usize, usize)>,
    /// After such a call the path (reads, writes) a volatile local.  Unlike other locals it
    /// has, after the second return, the value last stored: not the one of the first return
    /// that the proof of the path assumes.
    pub rt_volatile: (bool, bool),
    /// Coverage points reached on this path.
    pub cov: Vec<u32>,
    frames: Vec<Frame>,
    prev: Vec<T>,
    activations: u32,
    strs_ready: HashSet<u32>,
    /// Live variable-argument areas: base -> (position of the first word, number of words).
    va_areas: HashMap<T, (u32, u32)>,
    /// Constants without storage in the binary whose private copy has been initialised.
    consts_ready: HashSet<u32>,
    /// Private objects holding string literals that were not located in the image: base -> string index.
    pub str_bases: HashMap<T, u32>,
    /// Every local variable created on this path, live or not: base -> (size, alignment, name).
    pub local_shapes: HashMap<T, (u32, u32, String)>,
    /// Live local objects: base -> (size, name).
    objs: HashMap<T, (u32, String)>,
    /// Declared types of the local variables among them.
    obj_types: HashMap<T, TypeId>,
    /// Alignment of the objects that have one other than a word's: the binary must give an
    /// object whose address a callee receives a place aligned for its type.
    obj_aligns: HashMap<T, u32>,
    /// Those among them whose size is not a constant: base -> size in bytes.
    dyn_objs: HashMap<T, T>,
    /// Number of objects of dynamic size created on this path.
    dyn_count: u32,
    /// Live local objects whose address has been passed to an external function.
    escaped: Vec<T>,
    /// Targets of calls through pointers to unknown code: (index into `events`, pointer value).
    pub indirect: Vec<(usize, T)>,
    /// Functions (by index) whose calls are observable events although the source defines
    /// them: the binary calls their code, which is verified on its own.
    pub opaque: std::sync::Arc<Vec<bool>>,
    /// A call through a pointer that is not pinned to one function is an event (with the
    /// pointer as its target) instead of a case split over every function of the program.
    pub modular: bool,
    /// Accesses to volatile objects, in order.
    pub volatile: Vec<VolAccess>,
    temps: u32,
    /// Structure objects accessed through pointers on this path: (address, type).
    claims: Vec<(T, TypeId)>,
    /// Global variables accessed by name on this path.
    touched: Vec<u32>,
    /// Pointers that the lvalue being evaluated dereferences; the access itself makes a null
    /// pointer among them undefined.
    deref_roots: Vec<T>,
    /// Earlier accesses to world memory on this path.
    accesses: Vec<Access>,
    /// Value-bit masks of the arguments collected for the call being made.
    pending_masks: Vec<(usize, u64)>,
    /// For the next event: the arguments that the callee only borrows.
    pending_borrow: Vec<bool>,
    /// While an event's escapes are collected: locals handed over by a borrowed pointer and
    /// by nothing else so far.
    borrowing: Vec<T>,
    plain: Vec<(T, u32)>,
    access_seq: u64,
    /// Loads made so far (see `activity`).
    loads: u64,
    /// Values of expressions evaluated ahead of their turn (see `Ctx::order`): the next
    /// evaluation of the expression is that value.
    pre: Vec<(*const Expr, T)>,
    /// Sequence points passed so far inside expressions (C11 6.5p2, Annex C).
    seq_points: u64,
    /// Live `restrict` pointers: (the pointer's value, number of the first access made while it is live).
    restricts: Vec<(T, u64)>,
    /// Blocks of the outermost function at which a proof segment may end (loop cut points).
    pub cut_blocks: Vec<usize>,
    /// Number of arrivals at cut blocks after which execution stops.
    pub cut_stop: usize,
    /// Only arrivals at this block count towards `cut_stop` (the others are recorded).
    pub cut_only: Option<usize>,
    /// State at each arrival at a cut block.
    pub cut_snaps: Vec<CutSnap>,
    /// The conditional branch that led directly into the current block: (block, taken).
    pub last_br: Option<(usize, bool)>,
}

/// The C-side state when control reached a cut block.
#[derive(Clone, Debug)]
pub struct CutSnap {
    pub block: usize,
    pub mem: Mem,
    pub last_br: Option<(usize, bool)>,
    /// Events performed before this arrival.
    pub nev: u32,
}

/// How the execution of a function body ended.
pub enum BodyEnd {
    Ret(Option<T>),
    /// Stopped on arrival at a cut block; the frame is still live.
    Cut(usize),
    /// An arm of a region being merged reached the block where the arms meet.
    Join,
}

/// How an arm of a conditional region ended, and how the merged region does.
#[derive(Clone, Copy)]
enum ArmEnd {
    /// The value of an expression.
    Val(T),
    /// At the block where the arms meet.
    Join,
    /// By returning from the function.
    Ret(Option<T>),
}

/// Most blocks in a conditional region of the source that is merged.
const MAX_REGION_BLOCKS: usize = 12;

/// Can evaluating the expression be one arm of a merged region?  Not if it calls anything
/// or allocates.
fn mergeable(e: &Expr) -> bool {
    !matches!(
        e.kind,
        EK::Call(..)
            | EK::VaStart(_)
            | EK::VaArg(_)
            | EK::Alloca(..)
            | EK::VlaLive(_)
            | EK::Asm(_)
            | EK::Compound { .. }
    ) && e.children().into_iter().all(mergeable)
}

/// The block at which the two sides of the conditional branch ending block `b` meet again,
/// if what lies between is a few blocks without loops, calls or `switch`:
/// `Some(usize::MAX)` when every way through it returns from the function.
fn region_join(body: &Body, b: usize) -> Option<usize> {
    region_join_of(body, b, &mergeable)
}

/// `region_join` with `fits` deciding which expressions an arm may contain.
fn region_join_of(body: &Body, b: usize, fits: &dyn Fn(&Expr) -> bool) -> Option<usize> {
    const EXIT: usize = usize::MAX;
    let Term::Br(_, t, f) = &body.blocks[b].term else {
        return None;
    };
    let succs = |x: usize| -> Vec<usize> {
        match &body.blocks[x].term {
            Term::Jump(t) => vec![*t],
            Term::Br(_, t, f) => vec![*t, *f],
            Term::Switch(_, cases, d) => cases.iter().map(|c| c.2).chain([*d]).collect(),
            Term::Ret(_) => vec![EXIT],
            Term::Unreachable => Vec::new(),
        }
    };
    // Blocks reachable from the branch without passing `stop`, nearest first, and whether
    // that is all of them (the search gives up beyond a few).
    let reach = |stop: usize, cap: usize| -> (Vec<usize>, bool) {
        let mut seen: Vec<usize> = Vec::new();
        let mut queue: std::collections::VecDeque<usize> = [*t, *f].into();
        while let Some(x) = queue.pop_front() {
            if x == stop || x == EXIT || seen.contains(&x) {
                continue;
            }
            if seen.len() >= cap {
                return (seen, false);
            }
            seen.push(x);
            queue.extend(succs(x));
        }
        (seen, true)
    };
    // The meeting point is the nearest block every way from the branch passes: one without
    // which nothing that leaves the function is left.
    let (near, whole) = reach(EXIT, 3 * MAX_REGION_BLOCKS);
    let mut found: Option<(usize, Vec<usize>)> = None;
    for &j in &near {
        let (region, all) = reach(j, MAX_REGION_BLOCKS);
        if !all || region.iter().any(|&x| succs(x).contains(&EXIT)) {
            continue;
        }
        if found.as_ref().is_none_or(|r| region.len() < r.1.len()) {
            found = Some((j, region));
        }
    }
    let (join, region) = match found {
        Some(r) => r,
        None if whole && near.len() <= MAX_REGION_BLOCKS => (EXIT, near),
        None => return None,
    };
    if region.contains(&b) {
        return None;
    }
    // No cycle inside the region, and nothing that cannot be an arm.
    let mut order: HashMap<usize, u32> = HashMap::new();
    fn depth(
        x: usize,
        join: usize,
        succs: &dyn Fn(usize) -> Vec<usize>,
        order: &mut HashMap<usize, u32>,
    ) -> Option<u32> {
        if x == join || x == usize::MAX {
            return Some(0);
        }
        match order.get(&x) {
            Some(0) => return None,
            Some(&d) => return Some(d),
            None => {}
        }
        order.insert(x, 0);
        let mut d = 0;
        for y in succs(x) {
            d = d.max(depth(y, join, succs, order)?);
        }
        order.insert(x, d + 1);
        Some(d + 1)
    }
    depth(*t, join, &succs, &mut order)?;
    depth(*f, join, &succs, &mut order)?;
    for &x in &region {
        let blk = &body.blocks[x];
        let ops = blk.ops.iter().all(|op| match &op.kind {
            OpKind::Eval(e) => fits(e),
            OpKind::Init { items, .. } => items.iter().all(|i| fits(&i.1)),
        });
        let term = match &blk.term {
            Term::Jump(_) | Term::Unreachable | Term::Ret(None) => true,
            Term::Br(c, ..) => fits(c),
            Term::Ret(Some(e)) => fits(e),
            Term::Switch(..) => false,
        };
        if !ops || !term {
            return None;
        }
    }
    Some(join)
}

/// Why the conditional region at block `b` is not one `region_join` accepts (for the fork
/// profile printed under `CVERIF_DEBUG`).
fn region_obstacle(body: &Body, b: usize) -> &'static str {
    fn calls(e: &Expr) -> bool {
        matches!(e.kind, EK::Call(..)) || e.children().into_iter().any(calls)
    }
    if region_join_of(body, b, &|_| true).is_none() {
        "shape"
    } else if region_join_of(body, b, &|e| mergeable(e) || calls(e)).is_some() {
        "call"
    } else {
        "construct"
    }
}

/// One access to a volatile object: an observable effect the binary must reproduce.
#[derive(Clone, Debug)]
pub struct VolAccess {
    pub write: bool,
    pub addr: T,
    /// Size in bytes.
    pub size: u8,
    /// Value written, or the symbol standing for the value read.
    pub val: T,
    /// Number of external-call events that precede the access.
    pub event: usize,
}

/// Functions that may return a second time, besides those declared `returns_twice`: the
/// standard ones (which compilers recognise by name) and MicroPython's `nlr_push`, an
/// assembly routine with the same contract.
pub const RETURNS_TWICE: &[&str] = &["setjmp", "_setjmp", "__sigsetjmp", "sigsetjmp", "vfork", "nlr_push"];

/// Label of a branch decided path by path that merging could have joined (`Ctx::fork_why`).
pub const MERGEABLE: &str = "mergeable";

/// Event name of a call through a pointer to unknown code.
pub const INDIRECT: &str = "<indirect call>";

const NORETURN: &[&str] = &[
    "abort",
    "exit",
    "_exit",
    "_Exit",
    "__assert_fail",
    "__assert_func",
    "__builtin_abort",
];

/// Is block `b` the start of a cycle of blocks that do nothing and jump unconditionally?
fn endless(body: &Body, b: usize) -> bool {
    let mut at = b;
    for _ in 0..=body.blocks.len() {
        let blk = &body.blocks[at];
        if !blk.ops.is_empty() {
            return false;
        }
        at = match &blk.term {
            Term::Jump(t) => *t,
            Term::Br(c, t, f) => match c.kind {
                EK::Const(0) => *f,
                EK::Const(_) => *t,
                _ => return false,
            },
            _ => return false,
        };
        if at == b {
            return true;
        }
    }
    false
}

impl<'a> CExec<'a> {
    pub fn new(env: &'a CEnv<'a>) -> CExec<'a> {
        CExec {
            env,
            mem: Mem::default(),
            events: Vec::new(),
            rt_ended: Vec::new(),
            fell_off: false,
            rt_open: Vec::new(),
            rt_volatile: (false, false),
            cov: Vec::new(),
            frames: Vec::new(),
            prev: Vec::new(),
            activations: 0,
            strs_ready: HashSet::new(),
            va_areas: HashMap::new(),
            consts_ready: HashSet::new(),
            str_bases: HashMap::new(),
            objs: HashMap::new(),
            local_shapes: HashMap::new(),
            obj_types: HashMap::new(),
            obj_aligns: HashMap::new(),
            dyn_objs: HashMap::new(),
            dyn_count: 0,
            escaped: Vec::new(),
            indirect: Vec::new(),
            opaque: Default::default(),
            modular: false,
            volatile: Vec::new(),
            temps: 0,
            claims: Vec::new(),
            touched: Vec::new(),
            deref_roots: Vec::new(),
            accesses: Vec::new(),
            pending_masks: Vec::new(),
            pending_borrow: Vec::new(),
            borrowing: Vec::new(),
            plain: Vec::new(),
            access_seq: 0,
            loads: 0,
            pre: Vec::new(),
            seq_points: 0,
            restricts: Vec::new(),
            cut_blocks: Vec::new(),
            cut_stop: usize::MAX,
            cut_only: None,
            cut_snaps: Vec::new(),
            last_br: None,
        }
    }

    fn prog(&self) -> &'a Program {
        self.env.prog
    }

    /// A structure of type `ty` at `a` (implied by a member access through a pointer) does not
    /// overlap a declared object that cannot contain one: a variable's effective type is its
    /// declared type (C11 6.5p6), and compilers rely on it.
    fn not_inside_global(&mut self, ctx: &mut Ctx, a: T, ty: TypeId, g: u32, base: T) {
        let p = self.prog();
        if self.env.aliasing == Aliasing::Off || p.may_alias {
            return;
        }
        let gty = p.globals[g as usize].ty;
        let (Some(size), Some(gsize)) = (p.size_of(ty), p.size_of(gty)) else {
            return;
        };
        if gsize == 0 || size == 0 || (gsize >= size && may_contain(p, gty, p.unqual(ty))) {
            return;
        }
        let d1 = ctx.tm.sub(a, base);
        let n1 = ctx.tm.konst(32, gsize as u64);
        let in1 = ctx.tm.ult(d1, n1);
        let d2 = ctx.tm.sub(base, a);
        let n2 = ctx.tm.konst(32, size as u64);
        let in2 = ctx.tm.ult(d2, n2);
        let any = ctx.tm.or(in1, in2);
        let ok = ctx.tm.not(any);
        if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
            ctx.ub.push(ok);
        }
    }

    fn unsupported<V>(&self, what: &str, e: &Expr) -> R<V> {
        let file = self.prog().files.get(e.loc.file as usize).cloned().unwrap_or_default();
        Err(Stop::Unsupported(format!("{what} ({file}:{})", e.loc.line)))
    }

    // ----- memory ---------------------------------------------------------

    fn read(&mut self, ctx: &mut Ctx, addr: T, size: u8) -> T {
        self.loads += 1;
        let env = self.env;
        let epoch = self.mem.epoch;
        let mut init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
        ctx.mem_read(&self.mem, addr, size, &mut init)
    }

    fn check_bounds(&mut self, ctx: &mut Ctx, addr: T, size: u32, bounds: Bounds) -> R<()> {
        // A pointer computed from the address of a local variable designates that variable
        // or nothing: arithmetic that leaves the object (but for one past its end) and an
        // access outside it are undefined (C11 6.5.6p8), whatever route the value took.
        let bounds = bounds.or_else(|| {
            let (base, _) = ctx.private_split(addr)?;
            let n = self.objs.get(&base)?.0;
            (n > 0 && self.obj_types.contains_key(&base)).then_some((base, n))
        });
        let Some((base, osize)) = bounds else { return Ok(()) };
        if size > osize {
            return Err(Stop::Undefined);
        }
        let off = ctx.tm.sub(addr, base);
        let lim = ctx.tm.konst(32, (osize - size) as u64 + 1);
        let ok = ctx.tm.ult(off, lim);
        ctx.assume(ok)
    }

    /// An access through a pointer of unknown target either lies wholly inside an exposed local
    /// or does not touch it: a pointer into the object cannot be used to reach beyond it.
    ///
    /// A variable's effective type is its declared type (C11 6.5p6): an lvalue of a type the
    /// variable cannot hold (a pointer read where an `int` lives) does not access it at all.
    fn whole_object_access(&mut self, ctx: &mut Ctx, addr: T, size: u32, ty: TypeId) -> R<()> {
        if self.mem.exposed.is_empty() || ctx.region(addr).is_some() {
            return Ok(());
        }
        let class = alias_class(self.prog(), ty);
        for e in self.mem.exposed.clone() {
            if !ctx.may_point_into(addr, &e) {
                continue;
            }
            if let (Some(class), Some(&decl)) = (class, self.obj_types.get(&e.base))
                && self.env.aliasing != Aliasing::Off
                && !self.prog().may_alias
                && !may_hold(self.prog(), decl, class)
            {
                self.assume_disjoint(ctx, addr, size, e.base, e.size)?;
                continue;
            }
            if e.dyn_size.is_none() && size > e.size {
                continue;
            }
            let off = ctx.tm.sub(addr, e.base);
            let (within, osize) = match e.dyn_size {
                Some(total) => {
                    let n = ctx.tm.konst(32, size as u64);
                    let fits = ctx.tm.ule(n, total);
                    let room = ctx.tm.sub(total, n);
                    let low = ctx.tm.ule(off, room);
                    (ctx.tm.and(fits, low), total)
                }
                None => {
                    let lim = ctx.tm.konst(32, (e.size - size) as u64 + 1);
                    (ctx.tm.ult(off, lim), ctx.tm.konst(32, e.size as u64))
                }
            };
            let after = ctx.tm.ule(osize, off);
            let back = ctx.tm.sub(e.base, addr);
            let n = ctx.tm.konst(32, size as u64);
            let before = ctx.tm.ule(n, back);
            let apart = ctx.tm.and(after, before);
            let ok = ctx.tm.or(within, apart);
            ctx.assume(ok)?;
        }
        Ok(())
    }

    /// An assignment is about to store to `addr`.  The stores its operands made as side
    /// effects (`a[i++] = v`) with no sequence point since are unsequenced relative to it,
    /// and two unsequenced side effects on one scalar object are undefined (C11 6.5p2):
    /// compilers order them as they please.
    fn unsequenced(&mut self, ctx: &mut Ctx, seq0: u64, addr: T, ty: TypeId) -> R<()> {
        if ctx.region(addr).is_some() {
            return Ok(());
        }
        let Some(size) = self.prog().size_of(ty) else {
            return Ok(());
        };
        let sp = self.seq_points;
        let side: Vec<(T, u32)> = (self.accesses.iter())
            .filter(|y| y.store && y.seq > seq0 && y.sp == sp && y.addr != addr && y.guard.is_none())
            .map(|y| (y.addr, y.size))
            .collect();
        for (a, n) in side {
            // Where the two are known to lie relative to each other (members of one object)
            // there is nothing to assume.
            if ctx.tm.const_diff(addr, a).is_some() {
                continue;
            }
            self.assume_disjoint(ctx, addr, size, a, n)?;
        }
        Ok(())
    }

    /// The access `x` being made does not overlap the earlier access `y`, where `y` was made
    /// at all; `model`: in the compilers' reading of the language only.
    fn assume_apart(&mut self, ctx: &mut Ctx, x: &Access, y: &Access, model: bool) -> R<()> {
        let mut ok = self.disjoint(ctx, x.addr, x.size, y.addr, y.size);
        if let Some(g) = y.guard {
            let ng = ctx.tm.not(g);
            ok = ctx.tm.or(ng, ok);
        }
        if model { ctx.assume_model(ok) } else { ctx.assume(ok) }
    }

    fn assume_disjoint(&mut self, ctx: &mut Ctx, a: T, an: u32, b: T, bn: u32) -> R<()> {
        let ok = self.disjoint(ctx, a, an, b, bn);
        ctx.assume(ok)
    }

    fn disjoint(&mut self, ctx: &mut Ctx, a: T, an: u32, b: T, bn: u32) -> T {
        let d1 = ctx.tm.sub(a, b);
        let d2 = ctx.tm.sub(b, a);
        let (kb, ka) = (ctx.tm.konst(32, bn as u64), ctx.tm.konst(32, an as u64));
        let c1 = ctx.tm.ule(kb, d1);
        let c2 = ctx.tm.ule(ka, d2);
        ctx.tm.and(c1, c2)
    }

    /// Record an access to world memory and add what the language guarantees about it:
    ///
    /// * a load does not read memory last stored through an lvalue of an incompatible type
    ///   (C11 6.5p7), so it does not overlap an earlier such store unless something compatible
    ///   was stored there since;
    /// * an object modified while a `restrict` pointer is live is accessed either only through
    ///   that pointer or never through it (C11 6.7.3.1).
    ///
    /// Like other conditions for defined behaviour these are only used where the plain path
    /// condition does not settle a question.
    fn note_access(
        &mut self,
        ctx: &mut Ctx,
        (addr, size): (T, u32),
        (base, off): (TypeId, Option<u32>),
        refty: TypeId,
        store: bool,
    ) -> R<()> {
        if ctx.region(addr).is_some() || size == 0 {
            return Ok(());
        }
        if ctx.tm.as_const(addr).is_some() && !self.plain.contains(&(addr, size)) {
            self.plain.push((addr, size));
        }
        let p = self.prog();
        self.access_seq += 1;
        let x = Access {
            seq: self.access_seq,
            addr,
            size,
            base,
            refty,
            off,
            store,
            sp: self.seq_points,
            guard: None,
        };
        let earlier = std::mem::take(&mut self.accesses);
        let mut result = Ok(());
        let typed = self.env.aliasing != Aliasing::Off;
        'outer: for (i, y) in earlier.iter().enumerate() {
            if y.addr == x.addr || ctx.tm.const_diff(x.addr, y.addr).is_some() {
                continue;
            }
            // Type-based rule: this load against an earlier store.
            if typed && !x.store && y.store && !lvalues_may_alias(p, &x, y) {
                let superseded = earlier[i + 1..]
                    .iter()
                    .any(|z| z.store && z.addr == x.addr && z.size >= x.size && lvalues_may_alias(p, &x, z));
                if !superseded {
                    result = self.assume_apart(ctx, &x, y, false);
                    if result.is_err() {
                        break 'outer;
                    }
                    continue;
                }
            }
            // The same rule the other way round: this store against an earlier load.  The
            // stored-to object was already accessed with this store's type before that
            // load, with no store in between that could have given it another type; had the
            // load read it with its incompatible type, that would have been undefined.
            if typed
                && x.store
                && !y.store
                && !lvalues_may_alias(p, &x, y)
                && earlier[..i].iter().rev().take_while(|z| !z.store).any(|z| {
                    z.guard.is_none() && z.addr == x.addr && z.size == x.size && z.refty == x.refty && z.base == x.base
                })
            {
                result = self.assume_apart(ctx, &x, y, false);
                if result.is_err() {
                    break 'outer;
                }
                continue;
            }
            // The compilers' model: no two accesses of incompatible types, one of them a
            // store, touch the same memory.  The cases above are the part of it that the
            // standard states; the rest (a store after a load or after another store, which
            // for allocated storage gives the memory a new type) is what `-fstrict-aliasing`
            // means in GCC and clang, and is kept apart so that a proof resting on it says so.
            if self.env.aliasing == Aliasing::Compiler && (x.store || y.store) && !types_may_alias(p, &x, y) {
                result = self.assume_apart(ctx, &x, y, true);
                if result.is_err() {
                    break 'outer;
                }
                continue;
            }
            // Where the types do not tell them apart, two members of one structure type
            // that do not share a byte: the structures
            // they belong to are the same object or two objects, which do not overlap in
            // part, so the members are apart whatever their types.  The compilers tell such
            // accesses apart by their paths (GCC's component references, clang's
            // structure-path type information), character-typed members included.
            // (Used for a load against a store where one of them has a character type,
            // which is where the types say nothing and a compiler's reordering shows: for
            // every pair of members it made the conditions of a path several times larger.)
            if self.env.aliasing == Aliasing::Compiler
                && x.store != y.store
                && [x.refty, y.refty]
                    .iter()
                    .any(|&t| matches!(p.unqual(t), UCHAR | SCHAR | BOOL) || p.size_of(t) == Some(1))
                && !p.may_alias
                && let (Some(ox), Some(oy)) = (x.off, y.off)
                && let (Type::Record(a), Type::Record(b)) = (p.ty(p.unqual(x.base)), p.ty(p.unqual(y.base)))
                && a == b
                && (ox + x.size <= oy || oy + y.size <= ox)
            {
                result = self.assume_apart(ctx, &x, y, true);
                if result.is_err() {
                    break 'outer;
                }
                continue;
            }
            // restrict: one access through the pointer, one not, at least one of them a store.
            if x.store || y.store {
                for k in 0..self.restricts.len() {
                    let (ptr, since) = self.restricts[k];
                    if y.seq < since {
                        continue;
                    }
                    let (bx, by) = (ctx.mentions(x.addr, ptr), ctx.mentions(y.addr, ptr));
                    if bx == by {
                        continue;
                    }
                    // The other pointer must provably not be derived from the restrict pointer:
                    // it is computed from the function's other inputs alone.
                    let other = if bx { y.addr } else { x.addr };
                    if !ctx.pristine(other) {
                        continue;
                    }
                    result = self.assume_apart(ctx, &x, y, false);
                    if result.is_err() {
                        break 'outer;
                    }
                    break;
                }
            }
        }
        self.accesses = earlier;
        result?;
        if !self.accesses.iter().any(|y| {
            y.guard.is_none()
                && y.addr == x.addr
                && y.size == x.size
                && y.store == x.store
                && y.refty == x.refty
                && y.base == x.base
        }) || x.store
        {
            if self.accesses.len() >= MAX_ACCESSES {
                self.accesses.remove(0);
            }
            self.accesses.push(x);
        }
        Ok(())
    }

    /// Constant addresses (address, size) accessed through ordinary (non-volatile) lvalues on this path.
    pub fn plain_accesses(&self, ctx: &Ctx) -> Vec<(u32, u32)> {
        self.plain
            .iter()
            .filter_map(|&(a, n)| Some((ctx.tm.as_const(a)? as u32, n)))
            .collect()
    }

    fn note_lvalue(&mut self, ctx: &mut Ctx, lv: &Expr, addr: T, store: bool) -> R<()> {
        let size = self.prog().size_of(lv.ty).unwrap_or(0);
        self.note_access(ctx, (addr, size), (access_base(lv), access_offset(lv)), lv.ty, store)
    }

    /// The access being made dereferences the pointers collected while its lvalue was
    /// evaluated: none of them is null.
    fn deref_nonnull(&mut self, ctx: &mut Ctx) -> R<()> {
        while let Some(pv) = self.deref_roots.pop() {
            let zero = ctx.tm.konst(32, 0);
            let ok = ctx.tm.ne(pv, zero);
            ctx.assume(ok)?;
        }
        Ok(())
    }

    fn load(&mut self, ctx: &mut Ctx, addr: T, ty: TypeId, bounds: Bounds) -> R<T> {
        let size = self.prog().size_of(ty).unwrap_or(4);
        self.deref_nonnull(ctx)?;
        self.check_bounds(ctx, addr, size, bounds)?;
        self.dyn_bounds(ctx, addr, size)?;
        self.whole_object_access(ctx, addr, size, ty)?;
        let v = self.read(ctx, addr, size as u8);
        if self.prog().unqual(ty) == BOOL {
            let two = ctx.tm.konst(8, 2);
            let ok = ctx.tm.ult(v, two);
            ctx.assume(ok)?;
        }
        Ok(v)
    }

    fn store(&mut self, ctx: &mut Ctx, addr: T, ty: TypeId, bounds: Bounds, v: T) -> R<()> {
        let size = self.prog().size_of(ty).unwrap_or(4);
        self.deref_nonnull(ctx)?;
        self.check_bounds(ctx, addr, size, bounds)?;
        self.dyn_bounds(ctx, addr, size)?;
        self.not_const_object(ctx, addr, size);
        self.whole_object_access(ctx, addr, size, ty)?;
        ctx.mem_write(&mut self.mem, addr, size as u8, v);
        Ok(())
    }

    /// Modifying an object defined `const`, or a string literal, is undefined (C11 6.7.3p6,
    /// 6.4.5p7): record that a store through a pointer does not land in one.  Compilers rely
    /// on it when they keep or reorder loads from constant tables across stores.
    fn not_const_object(&mut self, ctx: &mut Ctx, addr: T, size: u32) {
        if ctx.region(addr).is_some() || size == 0 {
            return;
        }
        let env = self.env;
        if let Some(a) = ctx.tm.as_const(addr) {
            // A constant address is either fine or wrong on every path; nothing to assume.
            let _ = a;
            return;
        }
        for &(lo, hi) in &env.no_store {
            // The store [addr, addr + size) misses [lo, hi)  <=>  addr - (lo - size + 1) >= hi - lo + size - 1
            let span = (hi - lo) as u64 + size as u64 - 1;
            let off = ctx
                .tm
                .add_const(addr, (lo as u64).wrapping_neg().wrapping_add(size as u64 - 1));
            let k = ctx.tm.konst(32, span);
            let inside = ctx.tm.ult(off, k);
            let ok = ctx.tm.not(inside);
            if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
                ctx.ub.push(ok);
            }
        }
    }

    /// Read memory as the C program sees it at this point.
    pub fn read_bytes(&mut self, ctx: &mut Ctx, addr: T, size: u8) -> T {
        self.read(ctx, addr, size)
    }

    /// A new object of `n` bytes with automatic storage (`alloca`, a variable-length array).
    ///
    /// Its contents are indeterminate and it is private until its address is handed out, like
    /// any other local.  With a size the path pins to one value it *is* like any other local.
    /// Otherwise the size stays a term; the program is only defined if the block fits the
    /// stack, which is taken to mean at most [`MAX_DYN`] bytes.
    fn alloca(&mut self, ctx: &mut Ctx, n: T) -> R<T> {
        let n = ctx.tm.resize(n, 32, false);
        self.temps += 1;
        let fname = &self.prog().funcs[self.frames.last().unwrap().func as usize].name;
        let name = format!("&{fname}.<alloca>#{}@{}~{}", self.temps, self.activations, ctx.seg);
        let base = ctx.private_base(&name);
        match ctx.unique_value(n) {
            Some(c) if c <= MAX_DYN as u64 => {
                self.objs.insert(base, (c as u32, name));
            }
            Some(_) => return Err(Stop::Undefined),
            None => {
                self.dyn_count += 1;
                if self.dyn_count > MAX_DYN_OBJECTS {
                    return Err(Stop::Truncated("limit on dynamic stack allocations per path".into()));
                }
                let max = ctx.tm.konst(32, MAX_DYN as u64);
                let fits = ctx.tm.ule(n, max);
                ctx.assume(fits)?;
                self.objs.insert(base, (0, name));
                self.dyn_objs.insert(base, n);
            }
        }
        self.frames.last_mut().unwrap().allocas.push(base);
        Ok(base)
    }

    /// End the life of the variable-length arrays of the current activation whose declaration
    /// satisfies `dead`.
    fn kill_vlas(&mut self, dead: impl Fn(u32) -> bool) {
        let frame = self.frames.last_mut().unwrap();
        let mut gone = Vec::new();
        frame.vlas.retain(|&(d, base)| {
            if dead(d) {
                gone.push(base);
            }
            !dead(d)
        });
        frame.allocas.retain(|b| !gone.contains(b));
        for l in gone {
            self.dyn_objs.remove(&l);
            self.mem.private.remove(&l);
            self.objs.remove(&l);
            self.escaped.retain(|&e| e != l);
            self.mem.exposed.retain(|e| e.base != l);
        }
    }

    /// An access to an object of dynamic size lies inside it.
    fn dyn_bounds(&mut self, ctx: &mut Ctx, addr: T, size: u32) -> R<()> {
        if self.dyn_objs.is_empty() {
            return Ok(());
        }
        let Some((base, off)) = ctx.private_split(addr) else {
            return Ok(());
        };
        let Some(&total) = self.dyn_objs.get(&base) else {
            return Ok(());
        };
        let n = ctx.tm.konst(32, size as u64);
        let fits = ctx.tm.ule(n, total);
        let room = ctx.tm.sub(total, n);
        let low = ctx.tm.ule(off, room);
        let ok = ctx.tm.and(fits, low);
        ctx.assume(ok)
    }

    /// A fresh private object for a temporary (structure results, compound literals).
    fn temp(&mut self, ctx: &mut Ctx, what: &str) -> T {
        self.temps += 1;
        ctx.private_base(&format!("&tmp.{what}#{}~{}", self.temps, ctx.seg))
    }

    /// Is an access through `lv` at `addr` an access to a volatile object that the outside
    /// world can observe?  (A volatile local is ordinary private memory.)
    fn observable(&self, ctx: &Ctx, lv: &Expr, addr: T) -> bool {
        self.prog().is_volatile(lv.ty) && ctx.region(addr).is_none()
    }

    /// Note an access to a volatile local made after a call that may return twice.
    fn note_rt_volatile(&mut self, lv: &Expr, write: bool) {
        if (!self.rt_open.is_empty() || !self.rt_ended.is_empty()) && self.prog().is_volatile(lv.ty) {
            match write {
                true => self.rt_volatile.1 = true,
                false => self.rt_volatile.0 = true,
            }
        }
    }

    fn volatile_size(&self, lv: &Expr) -> R<u8> {
        match self.prog().size_of(lv.ty) {
            Some(n @ (1 | 2 | 4)) if self.prog().is_scalar(lv.ty) && !matches!(lv.kind, EK::BitField(..)) => {
                Ok(n as u8)
            }
            _ => self.unsupported("volatile access that is not a single 1, 2 or 4-byte integer", lv),
        }
    }

    fn volatile_read(&mut self, ctx: &mut Ctx, lv: &Expr, addr: T) -> R<T> {
        let size = self.volatile_size(lv)?;
        let val = ctx.event_sym(&format!("vol{}.{size}", self.volatile.len()), size * 8);
        self.volatile.push(VolAccess {
            write: false,
            addr,
            size,
            val,
            event: self.events.len(),
        });
        if self.prog().unqual(lv.ty) == BOOL {
            let two = ctx.tm.konst(8, 2);
            let ok = ctx.tm.ult(val, two);
            ctx.assume(ok)?;
        }
        Ok(val)
    }

    fn volatile_write(&mut self, ctx: &mut Ctx, lv: &Expr, addr: T, val: T) -> R<()> {
        let size = self.volatile_size(lv)?;
        let _ = ctx;
        self.volatile.push(VolAccess {
            write: true,
            addr,
            size,
            val,
            event: self.events.len(),
        });
        Ok(())
    }

    /// Read a bit-field: `w` bits starting at bit `bit` of the byte at `addr`, converted to type `ty`.
    fn bf_read(&mut self, ctx: &mut Ctx, addr: T, bounds: Bounds, bit: u8, w: u8, ty: TypeId) -> R<T> {
        let p = self.prog();
        let n = (bit as u32 + w as u32).div_ceil(8);
        if n > 8 || w == 0 {
            return Err(Stop::Unsupported("bit-field wider than 57 bits".into()));
        }
        self.check_bounds(ctx, addr, n, bounds)?;
        let unit = self.read(ctx, addr, n as u8);
        let f = ctx.tm.extract(unit, bit, w);
        Ok(ctx.tm.resize(f, p.bits(ty), p.is_signed(ty)))
    }

    /// Store `v` into a bit-field, leaving the other bits of the bytes it shares untouched.
    /// Returns the value the field then holds, converted to type `ty`.
    #[allow(clippy::too_many_arguments)]
    fn bf_write(&mut self, ctx: &mut Ctx, addr: T, bounds: Bounds, bit: u8, w: u8, ty: TypeId, v: T) -> R<T> {
        let p = self.prog();
        let n = (bit as u32 + w as u32).div_ceil(8);
        if n > 8 || w == 0 {
            return Err(Stop::Unsupported("bit-field wider than 57 bits".into()));
        }
        self.check_bounds(ctx, addr, n, bounds)?;
        let unit = self.read(ctx, addr, n as u8);
        let f = ctx.tm.resize(v, w, false);
        let mut acc = f;
        if bit > 0 {
            let lo = ctx.tm.extract(unit, 0, bit);
            acc = ctx.tm.concat(acc, lo);
        }
        let top = bit + w;
        if (top as u32) < n * 8 {
            let hi = ctx.tm.extract(unit, top, (n * 8) as u8 - top);
            acc = ctx.tm.concat(hi, acc);
        }
        ctx.mem_write(&mut self.mem, addr, n as u8, acc);
        Ok(ctx.tm.resize(f, p.bits(ty), p.is_signed(ty)))
    }

    /// Initialise the object at `base`: optionally zero it, then store each item.
    fn init_object(&mut self, ctx: &mut Ctx, base: T, ty: TypeId, zero: bool, items: &[(u32, Expr)]) -> R<()> {
        let p = self.prog();
        // Evaluate first: an initialiser may read the object it replaces (a compound literal in a loop).
        let mut vals = Vec::with_capacity(items.len());
        for (_, e) in items {
            vals.push(match &e.kind {
                EK::Bits(x, ..) => self.eval(ctx, x)?,
                _ => self.eval(ctx, e)?,
            });
        }
        // Structure values are designated by address: copy them out before the object is overwritten.
        let mut copies = Vec::new();
        for ((_, e), v) in items.iter().zip(&mut vals) {
            if let Type::Record(_) = p.ty(e.ty) {
                let size = p.size_of(e.ty).unwrap_or(0);
                let t = self.temp(ctx, "init");
                self.copy(ctx, t, *v, size);
                copies.push(t);
                *v = t;
            }
        }
        if zero {
            // The members an initialiser list does not name are zero; the padding between
            // members is not given a value by it (C11 6.7.9p10 speaks of static objects only,
            // and compilers leave the padding of an automatic object as it was).
            let size = p.size_of(ty).unwrap_or(0);
            let mut at = 0;
            for (off, len) in p.padding(ty).into_iter().chain([(size, 0)]) {
                if off > at {
                    let a = ctx.tm.add_const(base, at as u64);
                    self.zero(ctx, a, off - at);
                }
                at = off + len;
            }
        }
        for ((off, e), v) in items.iter().zip(vals) {
            let a = ctx.tm.add_const(base, *off as u64);
            match (&e.kind, p.ty(e.ty)) {
                (EK::Bits(_, bit, w), _) => {
                    self.bf_write(ctx, a, None, *bit, *w, e.ty, v)?;
                }
                (_, Type::Record(_)) => self.copy(ctx, a, v, p.size_of(e.ty).unwrap_or(0)),
                _ => ctx.mem_write(&mut self.mem, a, p.size_of(e.ty).unwrap_or(4) as u8, v),
            }
        }
        for t in copies {
            self.mem.private.remove(&t);
        }
        Ok(())
    }

    fn copy(&mut self, ctx: &mut Ctx, dst: T, src: T, size: u32) {
        // An untyped copy gives the destination a new effective type: remember it as a
        // character-typed store, which is compatible with every later load.
        let _ = self.note_access(ctx, (dst, size), (UCHAR, None), UCHAR, true);
        let mut off = 0;
        let mut chunks = Vec::new();
        while off < size {
            let n = if size - off >= 4 {
                4
            } else if size - off >= 2 {
                2
            } else {
                1
            };
            let a = ctx.tm.add_const(src, off as u64);
            chunks.push((off, n, self.read(ctx, a, n as u8)));
            off += n;
        }
        for (off, n, v) in chunks {
            let a = ctx.tm.add_const(dst, off as u64);
            ctx.mem_write(&mut self.mem, a, n as u8, v);
        }
    }

    fn zero(&mut self, ctx: &mut Ctx, dst: T, size: u32) {
        let mut off = 0;
        while off < size {
            let n = if size - off >= 4 {
                4
            } else if size - off >= 2 {
                2
            } else {
                1
            };
            let a = ctx.tm.add_const(dst, off as u64);
            let z = ctx.tm.konst(n as u8 * 8, 0);
            ctx.mem_write(&mut self.mem, a, n as u8, z);
            off += n;
        }
    }

    // ----- addresses --------------------------------------------------------

    fn global_addr(&mut self, ctx: &mut Ctx, g: u32) -> T {
        match self.env.global_addr[g as usize] {
            Some(a) => ctx.tm.konst(32, a as u64),
            None => {
                let gl = &self.prog().globals[g as usize];
                // A constant the compiler folded into the code has no storage in the binary:
                // give the source its own copy with the contents the source defines.
                if gl.is_const
                    && gl.defined
                    && !gl.is_volatile
                    && let Some(bytes) = self.env.init_bytes(g)
                {
                    let base = ctx.private_base(&format!("&{}#g{g}", gl.name));
                    if self.consts_ready.insert(g) {
                        let mut off = 0usize;
                        while off < bytes.len() {
                            let n = (bytes.len() - off).min(4);
                            let v = bytes[off..off + n].iter().rev().fold(0u64, |v, &b| v << 8 | b as u64);
                            let a = ctx.tm.add_const(base, off as u64);
                            let v = ctx.tm.konst(n as u8 * 8, v);
                            ctx.mem_write(&mut self.mem, a, n as u8, v);
                            off += n;
                        }
                    }
                    return base;
                }
                ctx.named_sym(&format!("&{}#g{g}", gl.name), 32)
            }
        }
    }

    fn func_addr(&mut self, ctx: &mut Ctx, f: u32) -> T {
        match self.env.func_addr[f as usize] {
            Some(a) => ctx.tm.konst(32, (a | 1) as u64),
            None => ctx.named_sym(&format!("&{}#f{f}", self.prog().funcs[f as usize].name), 32),
        }
    }

    fn str_addr(&mut self, ctx: &mut Ctx, s: u32) -> T {
        if let Some(a) = self.env.str_addr[s as usize] {
            return ctx.tm.konst(32, a as u64);
        }
        // Not found in the image: a private object holding the literal's bytes.
        let base = ctx.private_base(&format!("&str#{s}"));
        self.str_bases.insert(base, s);
        if self.strs_ready.insert(s) {
            for (i, &b) in self.prog().strings[s as usize].iter().enumerate() {
                let a = ctx.tm.add_const(base, i as u64);
                let v = ctx.tm.konst(8, b as u64);
                ctx.mem_write(&mut self.mem, a, 1, v);
            }
        }
        base
    }

    fn lvalue(&mut self, ctx: &mut Ctx, e: &Expr) -> R<(T, Bounds)> {
        let p = self.prog();
        match &e.kind {
            EK::Local(i) => {
                let base = self.frames.last().unwrap().locals[*i as usize];
                Ok((base, p.size_of(e.ty).map(|s| (base, s))))
            }
            EK::Global(g) => {
                let base = self.global_addr(ctx, *g);
                if !self.touched.contains(g) && self.touched.len() < 32 && ctx.region(base).is_none() {
                    self.touched.push(*g);
                    for i in 0..self.claims.len() {
                        let (a, ty) = self.claims[i];
                        self.not_inside_global(ctx, a, ty, *g, base);
                    }
                }
                Ok((base, p.size_of(p.globals[*g as usize].ty).map(|s| (base, s))))
            }
            EK::Str(s) => {
                let base = self.str_addr(ctx, *s);
                Ok((base, Some((base, p.strings[*s as usize].len() as u32))))
            }
            EK::Func(f) => Ok((self.func_addr(ctx, *f), None)),
            EK::Deref(ptr) => {
                let (a, bounds) = self.pointer(ctx, ptr)?;
                let a = ctx.settle(a)?;
                let bounds = match bounds {
                    Some((base, size)) => Some((ctx.settle(base)?, size)),
                    None => None,
                };
                // Accessing an object through a pointer that is not suitably aligned for its
                // type is undefined (C11 6.3.2.3p7); compilers rely on it.
                let align = p.align_of(e.ty);
                if align > 1 && align.is_power_of_two() {
                    let low = ctx.tm.extract(a, 0, align.trailing_zeros() as u8);
                    let zero = ctx.tm.konst(align.trailing_zeros() as u8, 0);
                    let ok = ctx.tm.eq(low, zero);
                    if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
                        ctx.ub.push(ok);
                    }
                }
                // Two objects of the same structure type are the same object or do not overlap:
                // a member access through `p->m` implies such an object at `p`.
                if let Type::Record(_) = p.ty(e.ty)
                    && let Some(size) = p.size_of(e.ty).filter(|&s| s > 0)
                    && !self.claims.contains(&(a, e.ty))
                {
                    for &(other, ty) in &self.claims {
                        if ty == e.ty {
                            no_partial_overlap(ctx, a, other, size);
                        } else if self.env.aliasing == Aliasing::Compiler
                            && !p.may_alias
                            && let Some(osize) = p.size_of(ty)
                            && !may_contain(p, ty, p.unqual(e.ty))
                            && !may_contain(p, e.ty, p.unqual(ty))
                        {
                            // Structures of unrelated types are distinct objects.  Not so
                            // by the letter of the standard: allocated storage may be reused
                            // for another type, and a load followed by a store of the other
                            // type is then defined.  It is what GCC and clang assume all the
                            // same (they exchange the two), so it belongs to the compilers'
                            // model: used last, and a proof that needs it says so.
                            let d1 = ctx.tm.sub(a, other);
                            let n1 = ctx.tm.konst(32, osize as u64);
                            let in1 = ctx.tm.ult(d1, n1);
                            let d2 = ctx.tm.sub(other, a);
                            let n2 = ctx.tm.konst(32, size as u64);
                            let in2 = ctx.tm.ult(d2, n2);
                            let any = ctx.tm.or(in1, in2);
                            let ok = ctx.tm.not(any);
                            ctx.assume_model(ok)?;
                        }
                    }
                    if self.claims.len() < 64 {
                        self.claims.push((a, e.ty));
                        for i in 0..self.touched.len() {
                            let g = self.touched[i];
                            let base = self.global_addr(ctx, g);
                            self.not_inside_global(ctx, a, e.ty, g, base);
                        }
                    }
                }
                // A constant address is a device register or the like, except zero: that
                // is a null pointer however it came about.
                if ctx.tm.as_const(a).is_none_or(|a| a == 0) && ctx.region(a).is_none() {
                    self.deref_roots.push(a);
                }
                Ok((a, bounds))
            }
            EK::Member(b, off) => {
                // A member of a structure the compiler broke up: the part that holds it.
                let (mut root, mut total) = (&**b, *off);
                while let EK::Member(inner, o) = &root.kind {
                    (root, total) = (&**inner, total + *o);
                }
                if let EK::Global(g) = root.kind
                    && let Some(parts) = self.env.split.get(&g)
                {
                    let size = p.size_of(e.ty).unwrap_or(u32::MAX);
                    let Some(&(o, n, addr)) =
                        (parts.iter()).find(|x| total >= x.0 && (total - x.0).saturating_add(size) <= x.1)
                    else {
                        return self.unsupported(
                            "member of a structure that the compiler broke up into separate objects and did not keep",
                            e,
                        );
                    };
                    let base = ctx.tm.konst(32, addr as u64);
                    return Ok((ctx.tm.add_const(base, (total - o) as u64), Some((base, n))));
                }
                let (a, bounds) = self.lvalue(ctx, b)?;
                Ok((ctx.tm.add_const(a, *off as u64), bounds))
            }
            EK::Compound { var, zero, items } => {
                let base = self.frames.last().unwrap().locals[*var as usize];
                self.init_object(ctx, base, e.ty, *zero, items)?;
                Ok((base, p.size_of(e.ty).map(|s| (base, s))))
            }
            // A structure rvalue is designated by the address of the temporary that holds it.
            _ if matches!(p.ty(e.ty), Type::Record(_)) && !matches!(e.kind, EK::BitField(..)) => {
                let base = self.eval(ctx, e)?;
                Ok((base, p.size_of(e.ty).map(|s| (base, s))))
            }
            _ => self.unsupported("expression is not an lvalue", e),
        }
    }

    /// Evaluate a pointer-valued expression, tracking the object it points into when that is syntactically evident.
    fn pointer(&mut self, ctx: &mut Ctx, e: &Expr) -> R<(T, Bounds)> {
        match &e.kind {
            EK::Addr(lv) => {
                // Taking an address does not access the object.
                let n = self.deref_roots.len();
                let r = self.lvalue(ctx, lv);
                self.deref_roots.truncate(n);
                r
            }
            EK::PtrAdd(ptr, idx, es) => {
                let (pv, bounds) = self.pointer(ctx, ptr)?;
                let iv = self.eval(ctx, idx)?;
                let iv = ctx.tm.resize(iv, 32, true);
                let scaled = ctx.tm.scale(iv, *es as u64);
                let sum = ctx.tm.add(pv, scaled);
                // An object does not wrap around the end of the address space and pointer
                // arithmetic stays within one: adding a count that cannot be negative
                // does not give a lower address.
                let p = self.prog();
                let mut count = &**idx;
                while let EK::Cast(x) = &count.kind
                    && p.size_of(x.ty) == Some(4)
                    && p.size_of(count.ty) == Some(4)
                {
                    count = x;
                }
                let counted = matches!(p.ty(p.unqual(count.ty)), Type::Int { signed: false, size: 4 });
                if counted && ctx.region(pv).is_none() && ctx.tm.as_const(iv).is_none() {
                    let ok = ctx.tm.ule(pv, sum);
                    if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
                        ctx.ub.push(ok);
                    }
                    // Nor is any object larger than PTRDIFF_MAX bytes (GCC and clang create
                    // none, and compile `p + n` as an offset that has a sign): a count that
                    // reaches further leaves every object the pointer could point into.
                    // (Said of a count that is a variable as it stands.  A computed one,
                    // `p + (n - 1)` with `n` zero, is a step back in every compiler: nothing
                    // more is assumed of it than the line above.)
                    let plain = matches!(count.kind, EK::Load(_));
                    let most = ctx.tm.konst(32, (i32::MAX as u64) / (*es).max(1) as u64);
                    let ok = ctx.tm.ule(iv, most);
                    if plain && ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
                        ctx.ub.push(ok);
                    }
                } else if let Some(c) = ctx.tm.as_const(iv)
                    && ctx.region(pv).is_none()
                    && (c as u32 as i32) < 0
                {
                    // A step back stays below the pointer: `--s` does not pass address zero
                    // and come out above `s`.  (The same holds of a step forward, which is
                    // left out: it is everywhere, and nothing was seen to need it.)
                    let ok = ctx.tm.ule(sum, pv);
                    if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
                        ctx.ub.push(ok);
                    }
                }
                Ok((sum, bounds))
            }
            EK::Cast(x) if self.prog().is_ptr(x.ty) && self.prog().is_ptr(e.ty) => {
                // A cast to another pointer type keeps the object but not the element type; keep the bounds.
                self.pointer(ctx, x)
            }
            _ => Ok((self.eval(ctx, e)?, None)),
        }
    }

    // ----- expressions ------------------------------------------------------

    /// A pointer into a local object and a pointer that cannot have been derived from that
    /// object's address (it existed before the address was known to anyone) are not equal.
    fn distinct_objects(&mut self, ctx: &mut Ctx, a: T, b: T) -> R<()> {
        let Some((base, _)) = ctx.private_split(a) else {
            return Ok(());
        };
        if !self.objs.contains_key(&base) || ctx.mentions_private(b) {
            return Ok(());
        }
        if let Some(e) = self.mem.exposed.iter().find(|e| e.base == base)
            && ctx.may_point_into(b, e)
        {
            return Ok(());
        }
        let ne = ctx.tm.ne(a, b);
        ctx.assume(ne)
    }

    fn bool_to_int(&mut self, ctx: &mut Ctx, b: T) -> T {
        ctx.tm.zext(b, 32)
    }

    /// What has been done so far that another party can observe (calls, volatile accesses),
    /// and how many loads were made.
    fn activity(&self) -> (usize, u64) {
        (self.events.len() + self.volatile.len(), self.loads)
    }

    /// Two parts of an expression were evaluated one after the other where the language
    /// leaves the order open (`before`, `mid`, and now): another order is a different
    /// execution if one part did something observable and the other observed or did
    /// something too.  Remembered for the driver, which then tries the other orders before
    /// it reports a difference.
    fn note_order(&mut self, ctx: &mut Ctx, kind: u8, before: (usize, u64), mid: (usize, u64)) {
        let now = self.activity();
        let (x_obs, x_loads) = (mid.0 != before.0, mid.1 != before.1);
        let (y_obs, y_loads) = (now.0 != mid.0, now.1 != mid.1);
        if (x_obs && (y_obs || y_loads)) || (y_obs && x_loads) {
            ctx.order_seen |= kind;
        }
    }

    /// Evaluates `e` now; its next evaluation yields the value without doing anything.
    fn eval_ahead(&mut self, ctx: &mut Ctx, e: &Expr) -> R<()> {
        let v = self.eval(ctx, e)?;
        self.pre.push((e as *const Expr, v));
        Ok(())
    }

    pub fn eval(&mut self, ctx: &mut Ctx, e: &Expr) -> R<T> {
        if !self.pre.is_empty()
            && let Some(i) = self.pre.iter().position(|x| std::ptr::eq(x.0, e))
        {
            return Ok(self.pre.swap_remove(i).1);
        }
        let p = self.prog();
        let w = p.bits(e.ty);
        match &e.kind {
            EK::Const(v) => Ok(ctx.tm.konst(w, *v)),
            EK::FConst(f) => Ok(ctx.tm.konst(
                w,
                if w == 32 {
                    (*f as f32).to_bits() as u64
                } else {
                    f.to_bits()
                },
            )),
            EK::Str(_)
            | EK::Local(_)
            | EK::Global(_)
            | EK::Func(_)
            | EK::Deref(_)
            | EK::Member(..)
            | EK::BitField(..)
            | EK::Compound { .. }
            | EK::Bits(..) => self.unsupported("unexpected lvalue", e),
            EK::Addr(lv) => {
                let n = self.deref_roots.len();
                let r = self.lvalue(ctx, lv);
                self.deref_roots.truncate(n);
                Ok(r?.0)
            }
            EK::Load(lv) => {
                if let EK::BitField(b, off, bit, bw) = &lv.kind {
                    if p.is_volatile(lv.ty) {
                        return self.unsupported("volatile bit-field", e);
                    }
                    let (addr, bounds) = self.lvalue(ctx, b)?;
                    let addr = ctx.tm.add_const(addr, *off as u64);
                    return self.bf_read(ctx, addr, bounds, *bit, *bw, e.ty);
                }
                let (addr, bounds) = self.lvalue(ctx, lv)?;
                if self.observable(ctx, lv, addr) {
                    return self.volatile_read(ctx, lv, addr);
                }
                self.note_rt_volatile(lv, false);
                match p.ty(e.ty) {
                    Type::Record(_) => Ok(addr),
                    _ => {
                        self.note_lvalue(ctx, lv, addr, false)?;
                        self.load(ctx, addr, e.ty, bounds)
                    }
                }
            }
            EK::Cast(x) => {
                let v = self.eval(ctx, x)?;
                if e.ty == VOID {
                    return Ok(v);
                }
                // A structure passed to a function defined in another translation unit: the two
                // units' declarations of the type must be compatible (C11 6.2.7), so it is the
                // same object representation.
                if matches!(p.ty(e.ty), Type::Record(_))
                    && matches!(p.ty(x.ty), Type::Record(_))
                    && p.size_of(e.ty).is_some()
                    && p.size_of(e.ty) == p.size_of(x.ty)
                {
                    return Ok(v);
                }
                if !p.is_scalar(e.ty) || !p.is_scalar(x.ty) {
                    return self.unsupported("cast of a non-scalar value", e);
                }
                if p.is_float(e.ty) || p.is_float(x.ty) {
                    return self.float_cast(ctx, e, x, v);
                }
                if e.ty == BOOL {
                    let nz = ctx.tm.nonzero(v);
                    return Ok(ctx.tm.zext(nz, 8));
                }
                Ok(ctx.tm.resize(v, w, p.is_signed(x.ty)))
            }
            EK::Neg(x) => {
                let v = self.eval(ctx, x)?;
                if p.is_float(e.ty) {
                    return Ok(crate::fp::fneg(&mut ctx.tm, v));
                }
                if p.is_signed(e.ty) {
                    let min = ctx.tm.konst(w, 1u64 << (w - 1));
                    let ok = ctx.tm.ne(v, min);
                    ctx.assume(ok)?;
                }
                Ok(ctx.tm.neg(v))
            }
            EK::BitNot(x) => {
                let v = self.eval(ctx, x)?;
                Ok(ctx.tm.not(v))
            }
            EK::LogNot(x) => {
                let v = self.eval(ctx, x)?;
                let nz = self.truth(ctx, v, x.ty);
                let z = ctx.tm.not(nz);
                Ok(self.bool_to_int(ctx, z))
            }
            EK::Bin(op, a, b) => {
                let t0 = self.activity();
                let (va, vb) = if ctx.order & crate::sym::ORDER_OPERANDS != 0 {
                    let vb = self.eval(ctx, b)?;
                    let t1 = self.activity();
                    let va = self.eval(ctx, a)?;
                    self.note_order(ctx, crate::sym::ORDER_OPERANDS, t0, t1);
                    (va, vb)
                } else {
                    let va = self.eval(ctx, a)?;
                    let t1 = self.activity();
                    let vb = self.eval(ctx, b)?;
                    self.note_order(ctx, crate::sym::ORDER_OPERANDS, t0, t1);
                    (va, vb)
                };
                if p.is_float(a.ty) || p.is_float(b.ty) {
                    if a.ty != b.ty && p.bits(a.ty) != p.bits(b.ty) {
                        return self.unsupported("floating-point operands of different types", e);
                    }
                    return self.float_binop(ctx, e, *op, va, vb);
                }
                if matches!(op, BinOp::Eq | BinOp::Ne) && p.is_ptr(a.ty) {
                    self.distinct_objects(ctx, va, vb)?;
                    self.distinct_objects(ctx, vb, va)?;
                }
                self.binop(ctx, *op, va, vb, p.is_signed(a.ty))
            }
            EK::PtrAdd(..) => Ok(self.pointer(ctx, e)?.0),
            EK::PtrDiff(a, b, es) => {
                let va = self.eval(ctx, a)?;
                let vb = self.eval(ctx, b)?;
                let d = ctx.tm.sub(va, vb);
                // Pointers into the same array differ by a multiple of the element size, so the
                // division is exact: shift out the power of two, multiply by the inverse of the odd part.
                let tz = es.trailing_zeros();
                let odd = es >> tz;
                if tz > 0 {
                    let low = ctx.tm.extract(d, 0, tz as u8);
                    let z = ctx.tm.konst(tz as u8, 0);
                    let ok = ctx.tm.eq(low, z);
                    ctx.assume(ok)?;
                }
                let q = ctx.tm.ashr_c(d, tz);
                if odd == 1 {
                    return Ok(q);
                }
                let mut inv = 1u32;
                for _ in 0..5 {
                    inv = inv.wrapping_mul(2u32.wrapping_sub(odd.wrapping_mul(inv)));
                }
                let r = ctx.tm.scale(q, inv as u64);
                // r * odd == q modulo 2^32; the signed difference is a multiple of the element
                // size exactly when that product does not wrap, i.e. when r is a small quotient.
                let hi = ctx.tm.konst(32, (i32::MAX / odd as i32) as u32 as u64);
                let lo = ctx.tm.konst(32, (i32::MIN / odd as i32) as u32 as u64);
                let a = ctx.tm.sle(r, hi);
                let b = ctx.tm.sle(lo, r);
                let ok = ctx.tm.and(a, b);
                ctx.assume(ok)?;
                // Equivalently, the truncating division is exact.  Stated as well because a
                // compiler may divide instead of multiplying by the inverse.
                let k = ctx.tm.konst(32, odd as u64);
                let dv = ctx.tm.sdiv(q, k);
                let same = ctx.tm.eq(dv, r);
                ctx.assume(same)?;
                if tz > 0 {
                    // ... or divide the whole difference by the element size.
                    let k = ctx.tm.konst(32, *es as u64);
                    let dv = ctx.tm.sdiv(d, k);
                    let same = ctx.tm.eq(dv, r);
                    ctx.assume(same)?;
                }
                Ok(r)
            }
            EK::LogAnd(a, b) | EK::LogOr(a, b) => {
                let is_and = matches!(e.kind, EK::LogAnd(..));
                let va = self.eval(ctx, a)?;
                self.seq_points += 1;
                let nz = self.truth(ctx, va, a.ty);
                if ctx.merge && mergeable(b) {
                    // The right operand is evaluated where the left one does not decide.
                    let go = if is_and { nz } else { ctx.tm.not(nz) };
                    let skip = ctx.tm.konst(1, !is_and as u64);
                    let mut arm = |s: &mut Self, ctx: &mut Ctx, taken: bool| -> R<ArmEnd> {
                        if !taken {
                            return Ok(ArmEnd::Val(skip));
                        }
                        let vb = s.eval(ctx, b)?;
                        Ok(ArmEnd::Val(s.truth(ctx, vb, b.ty)))
                    };
                    if let Some(ArmEnd::Val(r)) = self.merge_arms(ctx, go, &mut arm)? {
                        return Ok(self.bool_to_int(ctx, r));
                    }
                }
                ctx.fork_kind = if self.frames.len() > 1 { 6 } else { 1 };
                if !ctx.merge && mergeable(b) {
                    ctx.fork_why = Some(MERGEABLE);
                }
                if ctx.branch(nz)? != is_and {
                    return Ok(ctx.tm.konst(32, !is_and as u64));
                }
                let vb = self.eval(ctx, b)?;
                let nz = self.truth(ctx, vb, b.ty);
                Ok(self.bool_to_int(ctx, nz))
            }
            EK::Cond(c, a, b) => {
                let vc = self.eval(ctx, c)?;
                self.seq_points += 1;
                let nz = self.truth(ctx, vc, c.ty);
                if ctx.merge && mergeable(a) && mergeable(b) && p.is_scalar(e.ty) {
                    let mut arm = |s: &mut Self, ctx: &mut Ctx, taken: bool| -> R<ArmEnd> {
                        Ok(ArmEnd::Val(s.eval(ctx, if taken { a } else { b })?))
                    };
                    if let Some(ArmEnd::Val(r)) = self.merge_arms(ctx, nz, &mut arm)? {
                        return Ok(r);
                    }
                }
                ctx.fork_kind = if self.frames.len() > 1 { 6 } else { 2 };
                if !ctx.merge && mergeable(a) && mergeable(b) && p.is_scalar(e.ty) {
                    ctx.fork_why = Some(MERGEABLE);
                }
                if ctx.branch(nz)? {
                    self.eval(ctx, a)
                } else {
                    self.eval(ctx, b)
                }
            }
            EK::Comma(a, b) => {
                self.eval(ctx, a)?;
                self.seq_points += 1;
                self.eval(ctx, b)
            }
            EK::Assign(lv, rv) => {
                let seq0 = self.access_seq;
                // Which object is assigned to and what is assigned are found in either
                // order (C11 6.5.16p3).
                let t0 = self.activity();
                let whole = match &lv.kind {
                    EK::BitField(b, ..) => &**b,
                    _ => &**lv,
                };
                let first = (ctx.order & crate::sym::ORDER_ASSIGN != 0)
                    .then(|| self.lvalue(ctx, whole))
                    .transpose()?;
                let t1 = self.activity();
                let v = self.eval(ctx, rv)?;
                let t1 = if first.is_some() { t1 } else { self.activity() };
                let place = |s: &mut Self, ctx: &mut Ctx| -> R<(T, Bounds)> {
                    let r = match first {
                        Some(r) => r,
                        None => s.lvalue(ctx, whole)?,
                    };
                    s.note_order(ctx, crate::sym::ORDER_ASSIGN, t0, t1);
                    Ok(r)
                };
                if let EK::BitField(_, off, bit, bw) = &lv.kind {
                    if p.is_volatile(lv.ty) {
                        return self.unsupported("volatile bit-field", e);
                    }
                    let (addr, bounds) = place(self, ctx)?;
                    let addr = ctx.tm.add_const(addr, *off as u64);
                    return self.bf_write(ctx, addr, bounds, *bit, *bw, e.ty, v);
                }
                let (addr, bounds) = place(self, ctx)?;
                if self.observable(ctx, lv, addr) {
                    self.volatile_write(ctx, lv, addr, v)?;
                    return Ok(v);
                }
                self.note_rt_volatile(lv, true);
                if let Type::Record(_) = p.ty(lv.ty) {
                    let size = p.size_of(lv.ty).unwrap_or(0);
                    no_partial_overlap(ctx, addr, v, size);
                    self.deref_nonnull(ctx)?;
                    self.copy(ctx, addr, v, size);
                    return Ok(addr);
                }
                self.unsequenced(ctx, seq0, addr, lv.ty)?;
                self.note_lvalue(ctx, lv, addr, true)?;
                self.store(ctx, addr, lv.ty, bounds, v)?;
                Ok(v)
            }
            EK::AssignOp(lv, newv, post) => {
                if let EK::BitField(b, off, bit, bw) = &lv.kind {
                    if p.is_volatile(lv.ty) {
                        return self.unsupported("volatile bit-field", e);
                    }
                    let (addr, bounds) = self.lvalue(ctx, b)?;
                    let addr = ctx.tm.add_const(addr, *off as u64);
                    let old = self.bf_read(ctx, addr, bounds, *bit, *bw, e.ty)?;
                    self.prev.push(old);
                    let nv = self.eval(ctx, newv);
                    self.prev.pop();
                    let nv = self.bf_write(ctx, addr, bounds, *bit, *bw, e.ty, nv?)?;
                    return Ok(if *post { old } else { nv });
                }
                let seq0 = self.access_seq;
                let (addr, bounds) = self.lvalue(ctx, lv)?;
                let vol = self.observable(ctx, lv, addr);
                if !vol {
                    self.note_rt_volatile(lv, false);
                    self.note_rt_volatile(lv, true);
                }
                // In `a op= b` the value of `a` is read and `b` is evaluated in either order.
                let t0 = self.activity();
                let ahead = ctx.order & crate::sym::ORDER_COMPOUND != 0;
                if ahead {
                    let mut others = Vec::new();
                    if beside_prev(newv, &mut others) {
                        for o in others {
                            self.eval_ahead(ctx, o)?;
                        }
                    }
                }
                let t1 = self.activity();
                let old = if vol {
                    self.volatile_read(ctx, lv, addr)?
                } else {
                    self.note_lvalue(ctx, lv, addr, false)?;
                    self.load(ctx, addr, lv.ty, bounds)?
                };
                let t1 = if ahead { t1 } else { self.activity() };
                self.prev.push(old);
                let nv = self.eval(ctx, newv);
                self.prev.pop();
                let nv = nv?;
                self.note_order(ctx, crate::sym::ORDER_COMPOUND, t0, t1);
                if vol {
                    self.volatile_write(ctx, lv, addr, nv)?;
                } else {
                    self.unsequenced(ctx, seq0, addr, lv.ty)?;
                    self.note_lvalue(ctx, lv, addr, true)?;
                    self.store(ctx, addr, lv.ty, bounds, nv)?;
                }
                Ok(if *post { old } else { nv })
            }
            EK::Prev => Ok(*self.prev.last().expect("EK::Prev outside AssignOp")),
            EK::Call(callee, args) => {
                // The callee runs after its arguments are evaluated, and nothing in the
                // calling expression is interleaved with it.
                let r = self.call(ctx, e, callee, args);
                self.seq_points += 1;
                r
            }
            EK::VaStart(ap) => {
                let (a, _) = self.lvalue(ctx, ap)?;
                let Some(base) = self.frames.last().and_then(|f| f.va) else {
                    return self.unsupported("va_start outside a variadic function", e);
                };
                ctx.mem_write(&mut self.mem, a, 4, base);
                Ok(ctx.tm.konst(32, 0))
            }
            EK::VaArg(ap) => {
                let (a, _) = self.lvalue(ctx, ap)?;
                let cur = self.read(ctx, a, 4);
                let size = p.size_of(e.ty).unwrap_or(4);
                let wide = size == 8;
                let slot = if wide { 8 } else { 4 };
                let area = ctx.region(cur).and_then(|b| self.va_areas.get(&b).map(|&v| (b, v)));
                let at = if let Some((base, (start, words))) = area {
                    let (ts, c) = ctx.tm.linear(cur);
                    if ts.len() != 1 {
                        return self.unsupported("va_list position is not a constant", e);
                    }
                    let mut off = c as u32;
                    if wide && !(start + off / 4).is_multiple_of(2) {
                        off += 4;
                    }
                    if off + slot > 4 * words {
                        return Err(Stop::Truncated("variable arguments beyond the modelled area".into()));
                    }
                    ctx.tm.add_const(base, off as u64)
                } else if wide {
                    // A va_list from the caller: 64-bit arguments sit at 8-byte boundaries.
                    let up = ctx.tm.add_const(cur, 7);
                    let mask = ctx.tm.konst(32, 0xffff_fff8);
                    ctx.tm.and(up, mask)
                } else {
                    cur
                };
                let raw = self.read(ctx, at, slot as u8);
                let next = ctx.tm.add_const(at, slot as u64);
                ctx.mem_write(&mut self.mem, a, 4, next);
                Ok(ctx.tm.trunc(raw, p.bits(e.ty)))
            }
            EK::Alloca(count, es, decl) => {
                let n = self.eval(ctx, count)?;
                let n = ctx.tm.resize(n, 32, false);
                if let Some(d) = decl {
                    // An array has at least one element, and its size is representable.
                    let zero = ctx.tm.konst(32, 0);
                    let some = ctx.tm.ne(n, zero);
                    ctx.assume(some)?;
                    let max = ctx.tm.konst(32, (MAX_DYN / (*es).max(1)) as u64);
                    let fits = ctx.tm.ule(n, max);
                    ctx.assume(fits)?;
                    // Reaching the declaration again ends the life of the previous object.
                    self.kill_vlas(|x| x == *d);
                }
                let bytes = ctx.tm.scale(n, *es as u64);
                let base = self.alloca(ctx, bytes)?;
                // `alloca` memory suits any type; an array's elements are aligned for their
                // size at most.
                let align = match decl {
                    Some(_) => 1u32 << (*es).max(1).trailing_zeros().min(3),
                    None => 8,
                };
                self.obj_aligns.insert(base, align);
                if let Some(d) = decl {
                    self.frames.last_mut().unwrap().vlas.push((*d, base));
                }
                Ok(base)
            }
            EK::VlaLive(live) => {
                self.kill_vlas(|x| !live.contains(&x));
                Ok(ctx.tm.konst(32, 0))
            }
            EK::Asm(a) => {
                let mut args = Vec::new();
                if let Some(x) = &a.input {
                    args.push((self.eval(ctx, x)?, false));
                }
                self.pending_masks.clear();
                if a.block && self.frames.len() > 1 {
                    return self.unsupported(
                        "inline assembly compared as a block, in a function inlined into the one under verification",
                        e,
                    );
                }
                let name = format!("asm:{}", a.name);
                let ret = a.output.then_some((32, false));
                let r = if a.memory {
                    // Like a call to an unknown function, as far as memory is concerned.
                    self.event(ctx, &name, args, ret, a.noreturn)
                } else {
                    let k = self.events.len();
                    let ret = ret.map(|(w, signed)| (ctx.event_sym(&format!("ret{k}:{name}"), w), signed));
                    self.events.push(Event {
                        name,
                        args,
                        arg_masks: Vec::new(),
                        writes: Vec::new(),
                        epoch: self.mem.epoch,
                        ret,
                        noreturn: false,
                        escaped: Vec::new(),
                        exposed: self.mem.exposed.clone(),
                        asm: Some(false),
                        returns_twice: false,
                    });
                    ret.map(|r| r.0)
                };
                if let Some(ev) = self.events.last_mut() {
                    ev.asm = Some(a.memory);
                }
                if a.noreturn {
                    return Err(Stop::Halt);
                }
                Ok(r.unwrap_or_else(|| ctx.tm.konst(32, 0)))
            }
        }
    }

    /// The condition `v != 0` for a scalar of type `ty`.
    fn truth(&mut self, ctx: &mut Ctx, v: T, ty: TypeId) -> T {
        if self.prog().is_float(ty) {
            crate::fp::nonzero(&mut ctx.tm, v)
        } else {
            // The address of a live object, or of a place in it, is not null.
            if let Some((base, off)) = ctx.private_split(v)
                && let Some(&(size, _)) = self.objs.get(&base)
                && let Some(d) = ctx.tm.as_const(off)
                && d <= if self.dyn_objs.contains_key(&base) {
                    MAX_DYN
                } else {
                    size
                } as u64
            {
                return ctx.tm.tru();
            }
            ctx.tm.nonzero(v)
        }
    }

    /// A conversion to or from a floating-point type; `v` is the value of `x`.
    fn float_cast(&mut self, ctx: &mut Ctx, e: &Expr, x: &Expr, v: T) -> R<T> {
        use crate::fp;
        let p = self.prog();
        let w = p.bits(e.ty);
        match (p.is_float(x.ty), p.is_float(e.ty)) {
            (true, true) => Ok(fp::convert(&mut ctx.tm, v, w)),
            (false, true) => {
                if !(p.is_integer(x.ty) || x.ty == BOOL) {
                    return self.unsupported("conversion of a pointer to floating point", e);
                }
                // The integer promotions first; long long converts directly.
                let signed = p.is_signed(x.ty);
                let wide = ctx.tm.resize(v, p.bits(x.ty).max(32), signed);
                Ok(fp::from_int(&mut ctx.tm, wide, signed, w))
            }
            (true, false) => {
                if e.ty == BOOL {
                    let nz = fp::nonzero(&mut ctx.tm, v);
                    return Ok(ctx.tm.zext(nz, 8));
                }
                if !p.is_integer(e.ty) {
                    return self.unsupported("conversion of a floating-point value to a pointer", e);
                }
                // Undefined unless the truncated value fits the destination type.  Types narrower
                // than int are converted through int, which then holds the value.
                let signed = p.is_signed(e.ty);
                let iw = w.max(32);
                let conv_signed = signed || w < 32;
                let ok = fp::to_int_defined(&mut ctx.tm, v, signed, w);
                ctx.assume(ok)?;
                let r = fp::to_int(&mut ctx.tm, v, conv_signed, iw);
                let t = ctx.tm.trunc(r, w);
                if w < iw {
                    // The value fits the narrow type, so the int holds exactly that value.
                    let back = ctx.tm.resize(t, iw, signed);
                    let fits = ctx.tm.eq(back, r);
                    ctx.assume(fits)?;
                }
                Ok(t)
            }
            (false, false) => unreachable!(),
        }
    }

    fn float_binop(&mut self, ctx: &mut Ctx, e: &Expr, op: BinOp, a: T, b: T) -> R<T> {
        use crate::fp;
        let tm = &mut ctx.tm;
        let c = match op {
            BinOp::Add => return Ok(fp::fadd(tm, a, b)),
            BinOp::Sub => return Ok(fp::fsub(tm, a, b)),
            BinOp::Mul => return Ok(fp::fmul(tm, a, b)),
            BinOp::Div => return Ok(fp::fdiv(tm, a, b)),
            BinOp::Eq => fp::eq(tm, a, b),
            BinOp::Ne => {
                let c = fp::eq(tm, a, b);
                tm.not(c)
            }
            BinOp::Lt => fp::lt(tm, a, b),
            BinOp::Le => fp::le(tm, a, b),
            _ => return self.unsupported("operator on floating-point operands", e),
        };
        Ok(self.bool_to_int(ctx, c))
    }

    fn binop(&mut self, ctx: &mut Ctx, op: BinOp, a: T, b: T, signed: bool) -> R<T> {
        let tm = &mut ctx.tm;
        let w = tm.width(a);
        Ok(match op {
            BinOp::Add | BinOp::Sub => {
                let r = if op == BinOp::Add { tm.add(a, b) } else { tm.sub(a, b) };
                if signed {
                    // Signed overflow is undefined.
                    let x = if op == BinOp::Add { tm.xor(a, r) } else { tm.xor(a, b) };
                    let y = if op == BinOp::Add { tm.xor(b, r) } else { tm.xor(a, r) };
                    let both = tm.and(x, y);
                    let ovf = tm.extract(both, w - 1, 1);
                    let ok = tm.not(ovf);
                    ctx.assume(ok)?;
                }
                r
            }
            BinOp::Mul => {
                let r = crate::sym::mul64(tm, a, b);
                if signed && w <= 32 {
                    let (wa, wb) = (tm.sext(a, 2 * w), tm.sext(b, 2 * w));
                    let wide = tm.mul(wa, wb);
                    let back = tm.sext(r, 2 * w);
                    let ok = tm.eq(wide, back);
                    ctx.assume(ok)?;
                }
                r
            }
            BinOp::Div | BinOp::Rem => {
                let z = tm.konst(w, 0);
                let nz = tm.ne(b, z);
                ctx.assume(nz)?;
                let tm = &mut ctx.tm;
                if signed {
                    let min = tm.konst(w, 1u64 << (w - 1));
                    let m1 = tm.konst(w, mask(w));
                    let (e1, e2) = (tm.eq(a, min), tm.eq(b, m1));
                    let bad = tm.and(e1, e2);
                    let ok = tm.not(bad);
                    ctx.assume(ok)?;
                }
                let tm = &mut ctx.tm;
                match (op, signed) {
                    (BinOp::Div, true) => tm.sdiv(a, b),
                    (BinOp::Div, false) => tm.udiv(a, b),
                    (_, true) => tm.srem(a, b),
                    (_, false) => tm.urem(a, b),
                }
            }
            BinOp::And => tm.and(a, b),
            BinOp::Or => tm.or(a, b),
            BinOp::Xor => tm.xor(a, b),
            BinOp::Shl | BinOp::Shr => {
                let wb = tm.width(b);
                let lim = tm.konst(wb, w as u64);
                let ok = tm.ult(b, lim);
                ctx.assume(ok)?;
                let tm = &mut ctx.tm;
                let amt = tm.resize(b, w, false);
                match (op, signed) {
                    (BinOp::Shl, _) => tm.shl(a, amt),
                    (_, true) => tm.ashr(a, amt),
                    (_, false) => tm.lshr(a, amt),
                }
            }
            BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le => {
                // Two addresses within one local object compare as their offsets do: the
                // object does not wrap around the end of the address space.
                let (a, b) = match (op, w) {
                    (BinOp::Lt | BinOp::Le, 32) if !signed => match (ctx.private_split(a), ctx.private_split(b)) {
                        (Some((ba, oa)), Some((bb, ob))) if ba == bb && self.objs.contains_key(&ba) => {
                            let bias = ctx.tm.konst(32, 0x4000_0000);
                            (ctx.tm.add(oa, bias), ctx.tm.add(ob, bias))
                        }
                        _ => (a, b),
                    },
                    _ => (a, b),
                };
                let tm = &mut ctx.tm;
                let c = match (op, signed) {
                    (BinOp::Eq, _) => tm.eq(a, b),
                    (BinOp::Ne, _) => tm.ne(a, b),
                    (BinOp::Lt, true) => tm.slt(a, b),
                    (BinOp::Lt, false) => tm.ult(a, b),
                    (_, true) => tm.sle(a, b),
                    (_, false) => tm.ule(a, b),
                };
                tm.zext(c, 32)
            }
        })
    }

    // ----- calls ----------------------------------------------------------------

    /// A value of type `from` handed over in a register to code compiled to receive a value of
    /// type `to` there: an argument or a result of a call made through a declaration that
    /// disagrees with the function's definition (declarations of two translation units that
    /// drifted apart).  The language leaves such a call undefined (C11 6.5.2.2p9); each side
    /// was compiled for its own declaration, so what happens is what the calling convention
    /// says: an integer narrower than a register is passed extended to 32 bits as its type
    /// says, by whoever produces it, and whoever receives it relies on that.  Where the
    /// extension of `from` is one of `to` for every value, the receiver sees that value;
    /// otherwise it may see a value outside its type, which has no meaning in the source.
    fn through_abi(&self, ctx: &mut Ctx, v: T, from: TypeId, to: TypeId, f: &Func, what: &str) -> R<T> {
        let p = self.prog();
        if !p.is_scalar(from) || !p.is_scalar(to) {
            return Ok(v);
        }
        let (wf, wt) = (p.bits(from), p.bits(to));
        let (sf, st) = (p.is_signed(from), p.is_signed(to));
        // (A `_Bool` is received as 0 or 1 only from a `_Bool`.)
        let to_bool = p.unqual(to) == BOOL && p.unqual(from) != BOOL;
        if ctx.tm.width(v) != wf {
            // (Not a value of the type it is said to have: left for whoever uses it.)
            return Ok(v);
        }
        if wf == wt && (wf >= 32 || sf == st) && p.is_float(from) == p.is_float(to) && !to_bool {
            return Ok(v);
        }
        let fits = wf <= 32
            && !to_bool
            && !p.is_float(from)
            && !p.is_float(to)
            && (wt == 32 || (wf <= wt && wt < 32 && (sf == st || (!sf && wf < wt))));
        if !fits {
            return Err(Stop::Unsupported(format!(
                "{what} of {}: {} where it is defined and {} in the declaration this call is made through, \
                 which do not hold the same values in a register",
                f.name,
                p.type_name(if what == "result" { from } else { to }),
                p.type_name(if what == "result" { to } else { from }),
            )));
        }
        ctx.abi_calls.insert(f.name.to_string());
        let image = ctx.tm.resize(v, 32, sf);
        Ok(ctx.tm.resize(image, wt, false))
    }

    fn call(&mut self, ctx: &mut Ctx, e: &Expr, callee: &Expr, args: &[Expr]) -> R<T> {
        let p = self.prog();
        // The arguments are evaluated in any order (C11 6.5.2.2p10): here from the first to
        // the last, or the other way round.
        if args.len() > 1 && args.iter().all(|a| p.is_scalar(a.ty)) {
            let back = ctx.order & crate::sym::ORDER_ARGS != 0;
            let n = args.len();
            let mut seen = Vec::with_capacity(n + 1);
            seen.push(self.activity());
            for i in 0..n {
                self.eval_ahead(ctx, &args[if back { n - 1 - i } else { i }])?;
                seen.push(self.activity());
            }
            // (Any two of them: one that did something observable, another that looked.)
            let did = |i: usize| seen[i + 1].0 != seen[i].0;
            let looked = |i: usize| seen[i + 1].1 != seen[i].1;
            if (0..n).any(|i| did(i) && (0..n).any(|j| j != i && (did(j) || looked(j)))) {
                ctx.order_seen |= crate::sym::ORDER_ARGS;
            }
        }
        let fid = match &callee.kind {
            EK::Addr(f) if matches!(f.kind, EK::Func(_)) => {
                let EK::Func(id) = f.kind else { unreachable!() };
                id
            }
            _ => {
                let v = self.eval(ctx, callee)?;
                let ft = match p.pointee(callee.ty).map(|t| p.ty(t)) {
                    Some(Type::Func(ft)) => Some(&**ft),
                    _ => None,
                };
                // The address of a function the binary does not have under a symbol (the compiler
                // saw where the pointer comes from and inlined the function): the pointer is that
                // function, whatever address it would have had.
                if let crate::term::Node::Sym(id) = *ctx.tm.node(v)
                    && let Some((_, f)) = ctx.tm.sym_name(id).strip_prefix('&').and_then(|n| n.rsplit_once("#f"))
                    && let Ok(f) = f.parse::<u32>()
                    && self.env.func_addr.get(f as usize) == Some(&None)
                    && self.prog().funcs.get(f as usize).is_some_and(|g| g.body.is_some())
                {
                    f
                } else if self.modular && ctx.unique_value(v).is_none() {
                    // The binary may test the pointer against a function it has a copy of
                    // inline (speculative devirtualisation): the source makes the same
                    // distinction for the callees it follows.
                    let env = self.env;
                    let mut known = None;
                    for (id, _) in env
                        .callable
                        .iter()
                        .enumerate()
                        .filter(|&(id, &c)| c && !self.opaque[id])
                    {
                        let Some(addr) = env.func_addr[id] else { continue };
                        if ft.is_none_or(|ft| !p.funcs_may_be_compatible(ft, &p.funcs[id].ty, 0)) {
                            continue;
                        }
                        let k = ctx.tm.konst(32, (addr | 1) as u64);
                        let same = ctx.tm.eq(v, k);
                        ctx.fork_kind = 5;
                        if ctx.branch(same)? {
                            known = Some(id as u32);
                            break;
                        }
                    }
                    match known {
                        Some(id) => id,
                        None => return self.indirect_call(ctx, e, callee, v, args),
                    }
                } else {
                    match self.resolve_callee(ctx, v, ft)? {
                        Some(id) => id,
                        None => return self.indirect_call(ctx, e, callee, v, args),
                    }
                }
            }
        };
        let fid = (self.env.alias_of.get(fid as usize).copied().flatten()).unwrap_or(fid);
        let f = &p.funcs[fid as usize];
        let ret_ty = f.ty.ret;
        let void = ctx.tm.konst(32, 0);
        let opaque = f.body.is_some() && (f.opaque || self.opaque.get(fid as usize).copied().unwrap_or(false));
        // Compared as a call, one of the program's own `memcpy`, `memmove` or `memset` is
        // the library function of that name; followed, it is what its body says.
        let library = opaque && self.env.is_library(f);
        if library {
            ctx.library_used.insert(fid);
        }
        if f.body.is_some() && !opaque {
            // Structure arguments are designated by address; `run_function` copies them.
            let mut vals = Vec::with_capacity(args.len());
            for a in args {
                if !(p.is_scalar(a.ty) || matches!(p.ty(a.ty), Type::Record(_))) {
                    return self.unsupported("non-integer argument", a);
                }
                let v = self.eval(ctx, a)?;
                // (The argument was converted to the type the call site knows.)
                // (What the definition is passed: for an old-style one the promoted type.)
                vals.push(match f.ty.params.get(vals.len()) {
                    Some(&t) => self.through_abi(ctx, v, a.ty, t, f, "an argument")?,
                    None => v,
                });
            }
            // The program's own `strcmp` applied to two string literals, followed because the
            // binary makes no such call: a compiler for a hosted implementation evaluates the
            // library function itself.
            if self.env.hosted
                && &*f.name == "strcmp"
                && vals.len() == 2
                && let (Some(a), Some(b)) = (self.literal(ctx, vals[0]), self.literal(ctx, vals[1]))
                && let (Some(na), Some(nb)) = (a.iter().position(|&c| c == 0), b.iter().position(|&c| c == 0))
            {
                ctx.library_used.insert(u32::MAX);
                let (a, b) = (&a[..na], &b[..nb]);
                if a == b {
                    return Ok(void);
                }
                // Any value of the right sign is a correct result; the proof accepts one of
                // them (the one compilers produce), which can only make it stricter.
                let r = ctx.tm.konst(32, if a < b { u32::MAX as u64 } else { 1 });
                return Ok(r);
            }
            let r = self.run_function(ctx, fid, &vals)?;
            return match r {
                Some(r) => self.through_abi(ctx, r, ret_ty, e.ty, f, "result"),
                None => Ok(void),
            };
        }
        let vals = self.event_args(ctx, args)?;
        // Built-ins with known semantics (a function the source defines is what its body says).
        // (A function of one of these names declared with other types than the library's,
        // such as an `abs` of the program's own on bytes, is not the library function: its
        // calls are calls.  The `__builtin_` ones have the types the compiler gives them.)
        let as_library = f.name.starts_with("__builtin_")
            || f.name.starts_with("fabs")
            || matches!(&*f.name, "llabs" | "imaxabs" | "ffsll")
            || (vals.iter().all(|v| ctx.tm.width(v.0) == 32) && (ret_ty == VOID || p.bits(ret_ty) == 32));
        match if (opaque && !library) || !as_library {
            ""
        } else {
            &*f.name
        } {
            "__builtin_unreachable" => return Err(Stop::Undefined),
            "__builtin_trap" => {
                self.event(ctx, "<trap>", Vec::new(), None, true);
                return Err(Stop::Halt);
            }
            "__builtin_bswap16" | "__builtin_bswap32" | "__builtin_bswap64" if vals.len() == 1 => {
                return Ok(ctx.tm.bswap(vals[0].0));
            }
            "__builtin_ctz" | "__builtin_ctzl" | "__builtin_ctzll" if vals.len() == 1 => {
                // Undefined for zero.
                let v = vals[0].0;
                let nz = ctx.tm.nonzero(v);
                ctx.assume(nz)?;
                let c = ctx.tm.ctz(v);
                return Ok(ctx.tm.trunc(c, 32));
            }
            "__builtin_clzl" | "__builtin_clzll" if vals.len() == 1 => {
                let v = vals[0].0;
                let nz = ctx.tm.nonzero(v);
                ctx.assume(nz)?;
                let c = ctx.tm.clz(v);
                return Ok(ctx.tm.trunc(c, 32));
            }
            "__builtin_popcount" | "__builtin_popcountl" | "__builtin_popcountll" if vals.len() == 1 => {
                let c = ctx.tm.popcount(vals[0].0);
                return Ok(ctx.tm.trunc(c, 32));
            }
            "__builtin_parity" | "__builtin_parityl" | "__builtin_parityll" if vals.len() == 1 => {
                let b = ctx.tm.parity(vals[0].0);
                return Ok(ctx.tm.zext(b, 32));
            }
            "__builtin_ffsl" | "__builtin_ffsll" | "ffsll" if vals.len() == 1 => {
                return Ok(ffs(&mut ctx.tm, vals[0].0));
            }
            "__builtin_clrsb" | "__builtin_clrsbl" | "__builtin_clrsbll" if vals.len() == 1 => {
                return Ok(clrsb(&mut ctx.tm, vals[0].0));
            }
            "__builtin_llabs" | "__builtin_imaxabs" | "llabs" | "imaxabs"
                if vals.len() == 1 && ctx.tm.width(vals[0].0) == 64 =>
            {
                let v = vals[0].0;
                let min = ctx.tm.konst(64, 1 << 63);
                let ok = ctx.tm.ne(v, min);
                ctx.assume(ok)?;
                let z = ctx.tm.konst(64, 0);
                let neg = ctx.tm.slt(v, z);
                let n = ctx.tm.neg(v);
                return Ok(ctx.tm.ite(neg, n, v));
            }
            n if (n.starts_with("__builtin_rotateleft") || n.starts_with("__builtin_rotateright"))
                && vals.len() == 2 =>
            {
                let (v, by) = (vals[0].0, vals[1].0);
                let w = ctx.tm.width(v);
                let by = ctx.tm.resize(by, w, false);
                let m = ctx.tm.konst(w, w as u64 - 1);
                let k = ctx.tm.and(by, m);
                let nk = ctx.tm.neg(k);
                let back = ctx.tm.and(nk, m);
                let (k, back) = if n.contains("left") { (k, back) } else { (back, k) };
                let hi = ctx.tm.shl(v, k);
                let lo = ctx.tm.lshr(v, back);
                return Ok(ctx.tm.or(hi, lo));
            }
            // A string constant searched for a known character: a hosted program's
            // compiler does the search.
            "strchr" if vals.len() == 2 && self.env.hosted => {
                let known = (self.literal(ctx, vals[0].0).and_then(c_str))
                    .map(|s| s.to_vec())
                    .or_else(|| self.constant_string(ctx, vals[0].0));
                if let Some(s) = known
                    && let Some(c) = ctx.tm.as_const(vals[1].0)
                {
                    return Ok(match strchr_index(&s, c) {
                        Some(i) => {
                            // (A pointer into the string, which is not a null pointer.)
                            let at = ctx.tm.add_const(vals[0].0, i as u64);
                            let ok = ctx.tm.nonzero(at);
                            ctx.assume(ok)?;
                            at
                        }
                        None => ctx.tm.konst(32, 0),
                    });
                }
            }
            "__builtin_ffs" if vals.len() == 1 => {
                // One plus the index of the lowest set bit; zero for zero.
                let v = vals[0].0;
                let c = ctx.tm.ctz(v);
                let c1 = ctx.tm.add_const(c, 1);
                let z = ctx.tm.konst(32, 0);
                let nz = ctx.tm.nonzero(v);
                return Ok(ctx.tm.ite(nz, c1, z));
            }
            "memset" | "memcpy" | "memmove" if vals.len() == 3 => {
                // With a known length these are plain memory effects (the compiler may expand them inline).
                // (A length that is a choice made by a merged region is one length on each
                // side of it.)
                let len = ctx.settle(vals[2].0)?;
                if let Some(n) = ctx.unique_value(len)
                    && n <= MAX_MEM_INLINE
                {
                    let dst = vals[0].0;
                    if n > 0 {
                        self.not_const_object(ctx, dst, n as u32);
                    }
                    if &*f.name == "memset" {
                        let byte = ctx.tm.trunc(vals[1].0, 8);
                        mem_fill(ctx, &mut self.mem, dst, byte, n as u32);
                    } else {
                        if &*f.name == "memcpy" {
                            no_partial_overlap(ctx, dst, vals[1].0, n as u32);
                        }
                        self.copy(ctx, dst, vals[1].0, n as u32);
                    }
                    return Ok(dst);
                }
            }
            // Library string functions on string literals have a value known at compile time.
            "strlen" if vals.len() == 1 => {
                if let Some(s) = self.literal(ctx, vals[0].0)
                    && let Some(s) = c_str(s)
                {
                    return Ok(ctx.tm.konst(32, s.len() as u64));
                }
            }
            "strcmp" if vals.len() == 2 => {
                if let (Some(a), Some(b)) = (self.literal(ctx, vals[0].0), self.literal(ctx, vals[1].0))
                    && let (Some(a), Some(b)) = (c_str(a), c_str(b))
                {
                    return Ok(compare_result(ctx, a, b));
                }
            }
            "memcmp" if vals.len() == 3 => {
                if let Some(n) = ctx.tm.as_const(vals[2].0)
                    && let (Some(a), Some(b)) = (self.literal(ctx, vals[0].0), self.literal(ctx, vals[1].0))
                    && let (Some(a), Some(b)) = (a.get(..n as usize), b.get(..n as usize))
                {
                    return Ok(compare_result(ctx, a, b));
                }
                // One byte: what a hosted program's compiler expands the call to.
                if self.env.hosted && ctx.tm.as_const(vals[2].0) == Some(1) {
                    let a = self.read(ctx, vals[0].0, 1);
                    let b = self.read(ctx, vals[1].0, 1);
                    return Ok(byte_difference(ctx, a, b));
                }
            }
            "__builtin_clz" | "__builtin_clzl" if vals.len() == 1 => {
                let v = vals[0].0;
                let nz = ctx.tm.nonzero(v);
                ctx.assume(nz)?;
                return Ok(ctx.tm.clz(v));
            }
            "__builtin_clzll" if vals.len() == 1 => {
                let v = vals[0].0;
                let nz = ctx.tm.nonzero(v);
                ctx.assume(nz)?;
                return Ok(clz64(ctx, v));
            }
            "__builtin_ctz" | "__builtin_ctzl" | "__builtin_ctzll" if vals.len() == 1 => {
                let v = vals[0].0;
                let nz = ctx.tm.nonzero(v);
                ctx.assume(nz)?;
                return Ok(ctz(ctx, v));
            }
            "__builtin_ffs" | "__builtin_ffsl" if vals.len() == 1 => {
                let v = vals[0].0;
                let nz = ctx.tm.nonzero(v);
                let t = ctz(ctx, v);
                let t1 = ctx.tm.add_const(t, 1);
                let zero = ctx.tm.konst(32, 0);
                return Ok(ctx.tm.ite(nz, t1, zero));
            }
            "__builtin_popcount" | "__builtin_popcountl" | "__builtin_popcountll" if vals.len() == 1 => {
                return Ok(popcount(ctx, vals[0].0));
            }
            // What a hosted program's compiler computes in place of the call.
            "isdigit" | "isascii" | "toascii" | "ffs" | "ffsl" if vals.len() == 1 && self.env.hosted => {
                if let Some(v) = library_value(ctx, &f.name, vals[0].0) {
                    return Ok(v);
                }
            }
            "__builtin_isdigit" | "__builtin_isascii" | "__builtin_toascii" if vals.len() == 1 => {
                if let Some(v) = library_value(ctx, &f.name["__builtin_".len()..], vals[0].0) {
                    return Ok(v);
                }
            }
            "__builtin_fabsf" | "__builtin_fabs" | "__builtin_fabsl" | "fabsf" | "fabs" | "fabsl"
                if vals.len() == 1 && p.is_float(ret_ty) && ctx.tm.width(vals[0].0) == p.bits(ret_ty) =>
            {
                return Ok(crate::fp::fabs(&mut ctx.tm, vals[0].0));
            }
            "__builtin_abs" | "__builtin_labs" | "abs" | "labs" if vals.len() == 1 => {
                let v = vals[0].0;
                let min = ctx.tm.konst(32, 1 << 31);
                let ok = ctx.tm.ne(v, min);
                ctx.assume(ok)?;
                let z = ctx.tm.konst(32, 0);
                let neg = ctx.tm.slt(v, z);
                let n = ctx.tm.neg(v);
                return Ok(ctx.tm.ite(neg, n, v));
            }
            _ => {}
        }
        let noreturn = NORETURN.contains(&&*f.name) || p.noreturn.contains(&f.name);
        if let Type::Record(_) = p.ty(ret_ty)
            && let Some(size) = p.size_of(ret_ty).filter(|&s| s > 4)
            && !noreturn
        {
            // A larger structure comes back through memory: the caller passes the address of a
            // temporary as a hidden first argument and the callee fills it in.  The temporary is
            // reachable by the callee for the duration of this call only.
            let t = self.temp(ctx, "ret");
            self.objs.insert(t, (size, format!("&tmp.ret#{}", self.temps)));
            // (Aligned as its type requires, which may be less than a word.)
            self.obj_aligns.insert(t, p.align_of(ret_ty).clamp(1, 8));
            let mut vals = vals;
            vals.insert(0, (t, false));
            self.pending_masks.iter_mut().for_each(|m| m.0 += 1);
            self.event(ctx, &f.name, vals, None, false);
            self.escaped.retain(|&b| b != t);
            self.objs.remove(&t);
            return Ok(t);
        }
        let ret = self.event_ret(e, ret_ty)?.filter(|_| !noreturn);
        // What the C library promises about the result, which a compiler of a hosted
        // program relies on whoever provides the function: the formatted length.
        let at_least = match (&*f.name, self.env.hosted) {
            ("sprintf", true) => vals.get(1),
            ("snprintf", true) => vals.get(2),
            _ => None,
        }
        .and_then(|fmt| self.literal(ctx, fmt.0))
        .map(printf_min_len);
        // These return their first argument.
        let returns_dest = (self.env.hosted && (!opaque || library))
            .then(|| match (&*f.name, vals.len()) {
                ("memcpy" | "memmove" | "memset" | "strncpy" | "strncat", 3) | ("strcpy" | "strcat", 2) => {
                    Some(vals[0].0)
                }
                _ => None,
            })
            .flatten()
            // A function of the program that is compared as a call returns what its source
            // says: where that is plainly one of its parameters, the caller's compiler knew.
            .or_else(|| {
                // (Not of a definition the linker may replace: the one that runs may differ.)
                let fixed = !self.env.replaceable.get(fid as usize).copied().unwrap_or(false);
                let k = (opaque && fixed).then(|| p.returns_param(fid)).flatten()?;
                vals.get(k).filter(|v| ctx.tm.width(v.0) == 32).map(|v| v.0)
            });
        let twice = RETURNS_TWICE.contains(&&*f.name) || p.returns_twice.contains(&f.name);
        if opaque
            && !twice
            // (a definition the linker may replace says nothing about the one that runs)
            && !self.env.replaceable.get(fid as usize).copied().unwrap_or(false)
            && args.len() == vals.len()
            && let Some(b) = self.env.borrowed.get(fid as usize)
            && b.len() == vals.len()
        {
            // The callee's own source shows which pointers it does not keep; the caller's
            // compiler may have relied on that.
            self.pending_borrow = b.clone();
        }
        let r = self.event(ctx, &f.name, vals, ret, noreturn);
        if noreturn {
            return Err(Stop::Halt);
        }
        if let (Some(dest), Some(r)) = (returns_dest, r)
            && ctx.tm.width(r) == 32
        {
            let same = ctx.tm.eq(r, dest);
            ctx.assume(same)?;
        }
        if let (Some(n), Some(r)) = (at_least, r)
            && ctx.tm.width(r) == 32
        {
            let lo = ctx.tm.konst(32, n as u64);
            let ok = ctx.tm.sle(lo, r);
            ctx.assume(ok)?;
        }
        if twice && let Some(ev) = self.events.last_mut() {
            ev.returns_twice = true;
            self.rt_open.push((self.events.len() - 1, self.frames.len()));
        }
        let had = r.is_some();
        let r = self.event_result(ctx, ret_ty, r)?;
        if had && p.unqual(ret_ty) == BOOL {
            // A `_Bool` comes back as 0 or 1 (AAPCS 7.1.1), which the caller's code relies on
            // the way it relies on a narrow integer coming back extended.
            let two = ctx.tm.konst(ctx.tm.width(r), 2);
            let ok = ctx.tm.ult(r, two);
            ctx.assume(ok)?;
        }
        if had {
            self.through_abi(ctx, r, ret_ty, e.ty, f, "result")
        } else {
            Ok(r)
        }
    }

    /// Argument values of a call to unknown code, as the sequence of integers the AAPCS passes.
    fn event_args(&mut self, ctx: &mut Ctx, args: &[Expr]) -> R<Vec<(T, bool)>> {
        let p = self.prog();
        let mut vals = Vec::with_capacity(args.len());
        self.pending_masks.clear();
        for a in args {
            if let Type::Record(_) = p.ty(a.ty) {
                let addr = self.eval(ctx, a)?;
                // A structure is passed as its words; one that needs 8-byte alignment starts like a 64-bit integer.
                let size = p.size_of(a.ty).unwrap_or(0);
                if size == 0 {
                    return self.unsupported("empty structure passed by value to an external function", a);
                }
                // Padding (inside the structure and up to the next word) holds unspecified
                // bits: only the value bits of each word are compared with what the binary passes.
                let vm = p.value_mask(a.ty);
                let mut off = 0;
                while off < size {
                    let n = if off == 0 && p.align_of(a.ty) == 8 { 8 } else { 4 };
                    let have = n.min(size - off);
                    let w = ctx.tm.add_const(addr, off as u64);
                    let v = self.read(ctx, w, have as u8);
                    let v = ctx.tm.zext(v, (n * 8) as u8);
                    let m = (0..n).fold(0u64, |m, i| {
                        m | (vm.get((off + i) as usize).copied().unwrap_or(0) as u64) << (8 * i)
                    });
                    if m != mask((n * 8) as u8) {
                        self.pending_masks.push((vals.len(), m));
                    }
                    vals.push((v, false));
                    off += n;
                }
                continue;
            }
            if !p.is_scalar(a.ty) {
                return self.unsupported("non-integer argument", a);
            }
            vals.push((self.eval(ctx, a)?, p.is_signed(a.ty)));
        }
        Ok(vals)
    }

    /// How a call to unknown code returns a value of type `ret_ty`: (bits, signed) of the register value.
    fn event_ret(&self, e: &Expr, ret_ty: TypeId) -> R<Option<(u8, bool)>> {
        let p = self.prog();
        if ret_ty == VOID {
            return Ok(None);
        }
        if let Type::Record(_) = p.ty(ret_ty) {
            // Up to four bytes come back in r0; anything larger through a hidden pointer argument.
            return match p.size_of(ret_ty) {
                Some(1..=4) => Ok(Some((32, false))),
                _ => self.unsupported("external function returning a structure larger than 4 bytes", e),
            };
        }
        if !p.is_scalar(ret_ty) {
            return self.unsupported("call returning a non-integer value", e);
        }
        Ok(Some((p.bits(ret_ty), p.is_signed(ret_ty))))
    }

    /// The value of a call expression given the register value the callee returned.
    fn event_result(&mut self, ctx: &mut Ctx, ret_ty: TypeId, r: Option<T>) -> R<T> {
        let p = self.prog();
        let Some(r) = r else { return Ok(ctx.tm.konst(32, 0)) };
        if let Type::Record(_) = p.ty(ret_ty) {
            let size = p.size_of(ret_ty).unwrap_or(4) as u8;
            let t = self.temp(ctx, "call");
            let v = ctx.tm.trunc(r, size * 8);
            ctx.mem_write(&mut self.mem, t, size, v);
            return Ok(t);
        }
        Ok(r)
    }

    /// Which function does the pointer value `v` designate?  A value the path condition pins is
    /// looked up directly; otherwise every function of the program that the binary contains is
    /// tried in address order, as far as its type allows calling it through this pointer.  None
    /// when the pointer is none of them: the callee is unknown code.
    fn resolve_callee(&mut self, ctx: &mut Ctx, v: T, ft: Option<&FuncType>) -> R<Option<u32>> {
        if let Some(a) = ctx.unique_value(v) {
            let a = a as u32;
            return Ok(match self.env.addr_to_func.get(&(a & !1)) {
                Some(&id) => Some(id),
                None => self.env.ext_funcs.get(&(a | 1)).copied(),
            });
        }
        for &(addr, id) in &self.env.targets {
            let k = ctx.tm.konst(32, (addr | 1) as u64);
            let c = ctx.tm.eq(v, k);
            if ft.is_some_and(|ft| {
                !self
                    .prog()
                    .funcs_may_be_compatible(ft, &self.prog().funcs[id as usize].ty, 0)
            }) {
                // Calling a function through a pointer to an incompatible type is undefined.
                let ne = ctx.tm.not(c);
                ctx.assume(ne)?;
            } else {
                ctx.fork_kind = 5;
                if ctx.branch(c)? {
                    return Ok(Some(id));
                }
            }
        }
        Ok(None)
    }

    /// A call through a pointer to unknown code: an observable event whose target (compared
    /// with the address the binary branches to) is the pointer value itself.
    fn indirect_call(&mut self, ctx: &mut Ctx, e: &Expr, callee: &Expr, target: T, args: &[Expr]) -> R<T> {
        let p = self.prog();
        let ft = match p.pointee(callee.ty).map(|t| p.ty(t)) {
            Some(Type::Func(ft)) => ft.clone(),
            _ => return self.unsupported("call through a non-function pointer", e),
        };
        let vals = self.event_args(ctx, args)?;
        let ret = self.event_ret(e, ft.ret)?;
        self.indirect.push((self.events.len(), target));
        let r = self.event(ctx, INDIRECT, vals, ret, false);
        let had = r.is_some();
        let r = self.event_result(ctx, ft.ret, r)?;
        if had && self.prog().unqual(ft.ret) == BOOL {
            // A `_Bool` comes back as 0 or 1, whoever the callee is (see `call`).
            let two = ctx.tm.konst(ctx.tm.width(r), 2);
            let ok = ctx.tm.ult(r, two);
            ctx.assume(ok)?;
        }
        Ok(r)
    }

    fn event(
        &mut self,
        ctx: &mut Ctx,
        name: &str,
        args: Vec<(T, bool)>,
        ret: Option<(u8, bool)>,
        noreturn: bool,
    ) -> Option<T> {
        let name = self.env.canon.get(name).map_or(name, |n| n.as_str());
        let k = self.events.len();
        let ret = ret.map(|(w, signed)| (ctx.event_sym(&format!("ret{k}:{name}"), w), signed));
        let escaped = self.escapes(ctx, &args, k, noreturn);
        self.events.push(Event {
            name: name.to_string(),
            args,
            arg_masks: std::mem::take(&mut self.pending_masks),
            writes: std::mem::take(&mut self.mem.world),
            epoch: self.mem.epoch,
            ret,
            noreturn,
            escaped,
            exposed: self.mem.exposed.clone(),
            asm: None,
            returns_twice: false,
        });
        // The callee may have changed any world memory.
        self.mem.epoch += 1;
        ret.map(|r| r.0)
    }

    /// The rest of the string literal `ptr` points into, if it is a constant pointer into one.
    /// The string at `ptr` (without its terminator) if every byte of it is a constant of the
    /// program: a `const` array as well as a string literal.
    fn constant_string(&mut self, ctx: &mut Ctx, ptr: T) -> Option<Vec<u8>> {
        let mut s = Vec::new();
        for i in 0..256u64 {
            let a = ctx.tm.add_const(ptr, i);
            let loads = self.loads;
            let b = self.read(ctx, a, 1);
            self.loads = loads;
            match ctx.tm.as_const(b)? {
                0 => return Some(s),
                c => s.push(c as u8),
            }
        }
        None
    }

    fn literal(&self, ctx: &mut Ctx, ptr: T) -> Option<&'a [u8]> {
        let p = self.prog();
        if let Some(a) = ctx.tm.as_const(ptr) {
            return p.strings.iter().zip(&self.env.str_addr).find_map(|(s, sa)| {
                let o = (a as u32).checked_sub((*sa)?)? as usize;
                s.get(o..).filter(|r| !r.is_empty())
            });
        }
        let (base, off) = ctx.private_split(ptr)?;
        let sid = *self.str_bases.get(&base)?;
        let o = ctx.tm.as_const(off)? as usize;
        p.strings[sid as usize].get(o..)
    }

    /// If `v` points into a live local object, that object is from now on reachable from outside.
    fn note_escape(&mut self, ctx: &mut Ctx, v: T) {
        if ctx.tm.width(v) == 32
            && let Some((base, _)) = ctx.private_split(v)
            && self.objs.contains_key(&base)
        {
            if let Some(i) = self.borrowing.iter().position(|&b| b == base) {
                // Reachable some other way than through the borrowed pointer: handed over.
                self.borrowing.swap_remove(i);
            } else if !self.escaped.contains(&base) {
                self.escaped.push(base);
            }
        }
    }

    /// Local objects the callee of call number `k` can reach: those whose address is passed now or was
    /// passed to an earlier call, and those pointed to from inside such objects.  Their contents are
    /// recorded for comparison with the binary's stack and then replaced by fresh symbols, since the
    /// callee may have written to them.
    ///
    /// Bytes the C program never wrote hold indeterminate values; no conforming callee can depend on
    /// them, so the binary is free to hold anything there and they are not compared.
    fn escapes(&mut self, ctx: &mut Ctx, args: &[(T, bool)], k: usize, noreturn: bool) -> Vec<Escaped> {
        let borrow = std::mem::take(&mut self.pending_borrow);
        self.borrowing.clear();
        for (i, &(v, _)) in args.iter().enumerate() {
            if borrow.get(i) == Some(&true)
                && ctx.tm.width(v) == 32
                && let Some((base, _)) = ctx.private_split(v)
                && self.objs.contains_key(&base)
                && !self.dyn_objs.contains_key(&base)
                && !self.escaped.contains(&base)
            {
                // For the duration of this call only, unless something below says otherwise.
                self.escaped.push(base);
                self.borrowing.push(base);
            } else {
                self.note_escape(ctx, v);
            }
        }
        // A pointer to a local stored in memory the callee can read hands the local over as well.
        let stored: Vec<T> = self.mem.world.iter().filter(|w| w.size == 4).map(|w| w.val).collect();
        for v in stored {
            self.note_escape(ctx, v);
        }
        let mut out = Vec::new();
        let mut i = 0;
        while i < self.escaped.len() {
            let base = self.escaped[i];
            i += 1;
            let (size, name) = self.objs[&base].clone();
            if let Some(&total) = self.dyn_objs.get(&base) {
                // Every byte the program wrote is in the object's log; a pointer stored there
                // hands over what it points to.
                let log = ctx
                    .region(base)
                    .and_then(|r| self.mem.private.get(&r))
                    .cloned()
                    .unwrap_or_default();
                for w in &log {
                    if w.havoc.is_none() && w.size == 4 {
                        self.note_escape(ctx, w.val);
                    }
                }
                out.push(Escaped {
                    base,
                    align: self.obj_aligns.get(&base).copied().unwrap_or(4),
                    size: 0,
                    dynamic: Some(Box::new(crate::sym::DynEscaped {
                        size: total,
                        log,
                        havoc: None,
                    })),
                    name,
                    pre: Vec::new(),
                    post: Vec::new(),
                });
                continue;
            }
            let mut pre = Vec::new();
            let mut off = 0;
            while off < size {
                let n: u8 = if size - off >= 4 { 4 } else { 1 };
                let a = ctx.tm.add_const(base, off as u64);
                let v = self.read(ctx, a, n);
                if !ctx.mentions_uninit(v) {
                    pre.push((off, n, Some(v)));
                    self.note_escape(ctx, v);
                } else {
                    for j in 0..n as u32 {
                        let a = ctx.tm.add_const(base, (off + j) as u64);
                        let b = self.read(ctx, a, 1);
                        let b = if ctx.mentions_uninit(b) { None } else { Some(b) };
                        pre.push((off + j, 1, b));
                    }
                }
                off += n as u32;
            }
            out.push(Escaped {
                base,
                size,
                align: self.obj_aligns.get(&base).copied().unwrap_or(4),
                dynamic: None,
                name,
                pre,
                post: Vec::new(),
            });
        }
        // What the callee only borrowed is the caller's own again when it returns.
        let lent = std::mem::take(&mut self.borrowing);
        self.escaped.retain(|b| !lent.contains(b));
        // From the callee's return on, pointers of unknown origin may point into these objects.
        for e in &out {
            if !lent.contains(&e.base) && !self.mem.exposed.iter().any(|x| x.base == e.base) {
                self.mem.exposed.push(crate::sym::Exposed {
                    base: e.base,
                    size: e.size,
                    dyn_size: e.dynamic.as_ref().map(|d| d.size),
                    since: self.mem.epoch + 1,
                });
            }
        }
        if !noreturn {
            for (j, e) in out.iter_mut().enumerate() {
                if let Some(d) = &mut e.dynamic {
                    // The callee may have written all of it: unknown contents from here on.
                    let id = crate::sym::HAVOC_BASE
                        + ((ctx.seg & 0xff) << 20)
                        + ((k as u32 & 0x3fff) << 6)
                        + (j as u32 & 63);
                    d.havoc = Some(id);
                    ctx.mem_havoc(&mut self.mem, e.base, d.size, id, e.base);
                    continue;
                }
                let mut off = 0;
                while off < e.size {
                    let n: u8 = if e.size - off >= 4 { 4 } else { 1 };
                    let v = ctx.event_sym(&format!("esc{k}:{}+{off}", e.name), n * 8);
                    let a = ctx.tm.add_const(e.base, off as u64);
                    ctx.mem_write(&mut self.mem, a, n, v);
                    e.post.push((off, n, v));
                    off += n as u32;
                }
            }
        }
        out
    }

    /// Execute function `fid` with the given argument values.  Returns its value (None for void
    /// functions and for a missing `return` value).
    pub fn run_function(&mut self, ctx: &mut Ctx, fid: u32, args: &[T]) -> R<Option<T>> {
        match self.run_segment(ctx, fid, Some(args), 0, &[])? {
            BodyEnd::Ret(v) => Ok(v),
            BodyEnd::Cut(_) | BodyEnd::Join => {
                unreachable!("a segment from the entry of a callee ends at its return")
            }
        }
    }

    /// Run a function as one proof segment: from its entry (with `args`) or, for the outermost
    /// function, from block `start` with the memory already in `self.mem`, until it returns or
    /// reaches a cut block for the `cut_stop`-th time.  `assume` lists branch conditions known
    /// to hold at `start` (expression, truth value); they join the path condition.
    pub fn run_segment(
        &mut self,
        ctx: &mut Ctx,
        fid: u32,
        args: Option<&[T]>,
        start: usize,
        assume: &[(&Expr, bool)],
    ) -> R<BodyEnd> {
        let p = self.prog();
        let f = &p.funcs[fid as usize];
        let Some(body) = &f.body else {
            return Err(Stop::Unsupported(format!("function {} has no body", f.name)));
        };
        if let Some(why) = &f.unsupported {
            return Err(Stop::Unsupported(if self.frames.is_empty() {
                why.clone()
            } else {
                format!("calls {}: {why}", f.name)
            }));
        }
        if self.frames.len() >= ctx.limits.max_call_depth {
            return Err(Stop::Truncated("call depth limit".into()));
        }
        self.activations += 1;
        let act = self.activations;
        let mut locals = Vec::with_capacity(f.locals.len());
        for (i, l) in f.locals.iter().enumerate() {
            let name = format!("&{}.{}#{i}@{act}", f.name, l.name);
            let base = ctx.private_base(&name);
            if let Some(size) = p.size_of(l.ty) {
                self.local_shapes
                    .insert(base, (size, p.align_of(l.ty).clamp(1, 8), name.clone()));
            }
            // A variable is aligned as its type requires (C11 6.2.8); where the binary keeps
            // it is checked against that when the two are identified.
            // (Said for the objects whose address is what the code works with; a fact per
            // scalar would be carried by every question the prover is asked.)
            let align = p.align_of(l.ty).clamp(1, 8);
            if align > 1 && align.is_power_of_two() && matches!(p.ty(l.ty), Type::Array(..) | Type::Record(_)) {
                let bits = align.trailing_zeros() as u8;
                let low = ctx.tm.extract(base, 0, bits);
                let zero = ctx.tm.konst(bits, 0);
                let ok = ctx.tm.eq(low, zero);
                ctx.assume(ok)?;
            }
            self.objs.insert(base, (p.size_of(l.ty).unwrap_or(0), name));
            self.obj_types.insert(base, l.ty);
            self.obj_aligns.insert(base, p.align_of(l.ty).clamp(1, 8));
            locals.push(base);
        }
        for (i, &v) in args.unwrap_or(&[]).iter().enumerate().take(f.nparams) {
            let ty = f.locals[i].ty;
            if let Type::Record(_) = p.ty(ty) {
                // Passed by value: `v` is the address of the caller's object.
                self.copy(ctx, locals[i], v, p.size_of(ty).unwrap_or(0));
                continue;
            }
            if !p.is_scalar(ty) {
                return Err(Stop::Unsupported(format!(
                    "parameter {} of {} is not an integer or pointer",
                    i + 1,
                    f.name
                )));
            }
            let v = ctx.tm.resize(v, p.bits(ty), p.is_signed(ty));
            ctx.mem_write(&mut self.mem, locals[i], p.size_of(ty).unwrap_or(4) as u8, v);
        }
        let mut va = None;
        if f.variadic_def && args.is_none() {
            return Err(Stop::Unsupported(
                "loop proof: the function takes variable arguments".into(),
            ));
        }
        if let (true, Some(args)) = (f.variadic_def, args) {
            // Variable arguments follow the named ones in the AAPCS argument sequence: the
            // rest of r0-r3, then the stack.  The source sees them as one array of words
            // (what the binary builds by pushing the remaining registers below the stack
            // arguments).  `start` is the position of its first word in that sequence.
            let shapes: Vec<(u32, bool)> = f.locals[..f.nparams]
                .iter()
                .map(|l| (p.size_of(l.ty).unwrap_or(4), p.align_of(l.ty) == 8))
                .collect();
            let first = (matches!(p.ty(f.ty.ret), Type::Record(_)) && p.size_of(f.ty.ret).unwrap_or(0) > 4) as u8;
            let start = va_start_word(&shapes, first);
            let mut words = Vec::new();
            for &v in args.iter().skip(f.nparams) {
                if self.frames.is_empty() || ctx.tm.width(v) <= 32 {
                    words.push(ctx.tm.resize(v, 32, false));
                } else {
                    if !(start as usize + words.len()).is_multiple_of(2) {
                        words.push(ctx.tm.konst(32, 0));
                    }
                    words.push(ctx.tm.extract(v, 0, 32));
                    words.push(ctx.tm.extract(v, 32, 32));
                }
            }
            let name = format!("&{}.<va>@{act}", f.name);
            let base = ctx.private_base(&name);
            self.objs.insert(base, (4 * words.len() as u32, name));
            for (i, &w) in words.iter().enumerate() {
                let a = ctx.tm.add_const(base, 4 * i as u64);
                ctx.mem_write(&mut self.mem, a, 4, w);
            }
            self.va_areas.insert(base, (start, words.len() as u32));
            va = Some(base);
        }
        // A segment that starts inside a loop starts from pointers of unknown derivation, which
        // cannot be told from those based on a `restrict` parameter: only a segment from the
        // entry relies on `restrict`.
        let live_restricts = self.restricts.len();
        for (i, &v) in args.unwrap_or(&[]).iter().enumerate().take(f.nparams) {
            // Only a pointer whose value is an input symbol can be recognised in addresses derived from it.
            if p.restrict_params.contains(&(fid, i as u32)) && matches!(ctx.tm.node(v), crate::term::Node::Sym(..)) {
                self.restricts.push((v, self.access_seq + 1));
            }
        }
        self.frames.push(Frame {
            func: fid,
            locals,
            va,
            allocas: Vec::new(),
            vlas: Vec::new(),
        });
        for &(e, want) in assume {
            let v = self.eval(ctx, e)?;
            let nz = ctx.tm.nonzero(v);
            let c = if want { nz } else { ctx.tm.not(nz) };
            if ctx.tm.is_false(c) {
                return Err(Stop::Undefined);
            }
            if !ctx.tm.is_true(c) && !ctx.pc.contains(&c) {
                ctx.pc.push(c);
            }
        }
        let r = self.run_body(ctx, body, f.ty.ret, start, args.is_none(), None);
        if let Ok(BodyEnd::Cut(_)) = r {
            // Stopped at a cut point: the frame stays live for the state to be examined.
            return r;
        }
        if f.naked && r.is_ok() {
            // A naked function has no return sequence: what happens past its end is not
            // defined.  Everything it did before is, and is compared.
            self.fell_off = true;
            return Err(Stop::Halt);
        }
        self.restricts.truncate(live_restricts);
        if let Some(base) = va {
            self.mem.private.remove(&base);
            self.objs.remove(&base);
            self.va_areas.remove(&base);
            self.escaped.retain(|&e| e != base);
            self.mem.exposed.retain(|e| e.base != base);
        }
        let depth = self.frames.len();
        while let Some(&(ev, _)) = self.rt_open.last().filter(|o| o.1 >= depth) {
            self.rt_open.pop();
            self.rt_ended.push((ev, self.events.len()));
        }
        let frame = self.frames.pop().unwrap();
        // Locals die with the activation.
        for l in frame.locals.into_iter().chain(frame.allocas) {
            self.dyn_objs.remove(&l);
            self.mem.private.remove(&l);
            self.objs.remove(&l);
            self.escaped.retain(|&e| e != l);
            self.mem.exposed.retain(|e| e.base != l);
        }
        let _ = frame.func;
        r
    }

    /// Local objects external code can reach: those handed over and those it may still point into.
    pub fn escaped_objects(&self) -> Vec<(T, Option<T>)> {
        let mut out: Vec<(T, Option<T>)> = self.mem.exposed.iter().map(|e| (e.base, e.dyn_size)).collect();
        for &b in &self.escaped {
            if !out.iter().any(|o| o.0 == b) {
                out.push((b, self.dyn_objs.get(&b).copied()));
            }
        }
        out
    }

    /// Start with these local objects already handed over to external code.
    pub fn set_escaped(&mut self, bases: Vec<T>) {
        self.escaped = bases;
    }

    /// Size, alignment and name of a live local object.
    pub fn object(&self, base: T) -> Option<(u32, u32, String)> {
        let (size, name) = self.objs.get(&base)?.clone();
        Some((size, self.obj_aligns.get(&base).copied().unwrap_or(4), name))
    }

    /// Are there local objects whose address an external function has seen?
    pub fn has_escaped(&self) -> bool {
        !self.escaped.is_empty() || !self.mem.exposed.is_empty()
    }

    /// Execute both sides of the undetermined condition `cond` (`arm` runs one, from the
    /// current state) and continue with one state in which every value the sides left
    /// differently is a choice on `cond`.  None, with the state untouched, when the condition
    /// is settled, an arm does what cannot be merged (a call, a branch that needs a new path,
    /// an effect other than a few plain stores), or the prover cannot say that both sides
    /// are possible: the caller then branches as usual.
    ///
    /// What the source must not do inside an arm is assumed only where that arm is taken.
    /// An arm that is undefined outright leaves the other one, with the condition assumed.
    fn merge_arms(
        &mut self,
        ctx: &mut Ctx,
        cond: T,
        arm: &mut dyn FnMut(&mut Self, &mut Ctx, bool) -> R<ArmEnd>,
    ) -> R<Option<ArmEnd>> {
        if ctx.probe(cond) != Open::Both {
            return Ok(None);
        }
        ctx.check_deadline()?;
        let base = self.clone();
        let outer = ctx.guard();
        let mark = ctx.arm_begin(cond);
        let ra = arm(self, ctx, true);
        let ua = ctx.arm_end(&mark);
        let a = std::mem::replace(self, base.clone());
        let n = ctx.tm.not(cond);
        let mark_b = ctx.arm_begin(n);
        let rb = arm(self, ctx, false);
        let ub = ctx.arm_end(&mark_b);
        let ncov = base.cov.len();
        ctx.merge_note(|| {
            let show = |r: &R<ArmEnd>| match r {
                Ok(ArmEnd::Val(_)) => "value".to_string(),
                Ok(ArmEnd::Join) => "join".to_string(),
                Ok(ArmEnd::Ret(_)) => "return".to_string(),
                Err(e) => format!("{e:?}"),
            };
            format!("source arms: {} / {}", show(&ra), show(&rb))
        });
        let done = match (ra, rb) {
            (Ok(x), Ok(y)) => match self.join(ctx, cond, &base, a, x, y) {
                Some((end, cov_a)) => {
                    let cov_b = self.cov.split_off(ncov);
                    for (g, cov) in [(cond, cov_a), (n, cov_b)] {
                        let guard = ctx.tm.and(outer, g);
                        ctx.arms.push(crate::sym::Arm {
                            guard,
                            cov,
                            insns: Vec::new(),
                            data: Vec::new(),
                        });
                    }
                    ctx.arm_commit(cond, ua);
                    ctx.arm_commit(n, ub);
                    Some(end)
                }
                None => None,
            },
            (Err(Stop::Undefined), Ok(y)) => {
                ctx.assume(n)?;
                ctx.arm_commit(n, ub);
                Some(y)
            }
            (Ok(x), Err(Stop::Undefined)) => {
                *self = a;
                ctx.assume(cond)?;
                ctx.arm_commit(cond, ua);
                Some(x)
            }
            _ => None,
        };
        match done {
            Some(_) => ctx.merge_done(),
            None => {
                ctx.merge_note(|| "source: not merged".into());
                *self = base;
                ctx.arm_discard(&mark);
            }
        }
        Ok(done)
    }

    /// Make this state, left by the arm taken where `cond` is false, the state after the
    /// region whose other arm left `a`.  Returns how the region ended and the coverage
    /// points of the other arm; None if the arms differ in more than values.
    fn join(
        &mut self,
        ctx: &mut Ctx,
        cond: T,
        base: &Self,
        a: Self,
        x: ArmEnd,
        y: ArmEnd,
    ) -> Option<(ArmEnd, Vec<u32>)> {
        let b = &*self;
        let same = a.events.len() == b.events.len()
            && a.events.len() == base.events.len()
            && a.volatile.len() == b.volatile.len()
            && a.volatile.len() == base.volatile.len()
            && a.indirect.len() == b.indirect.len()
            && a.frames == b.frames
            && a.prev == b.prev
            && a.activations == b.activations
            && a.strs_ready == b.strs_ready
            && a.consts_ready == b.consts_ready
            && a.str_bases == b.str_bases
            && a.va_areas == b.va_areas
            && a.objs == b.objs
            && a.obj_types == b.obj_types
            && a.obj_aligns == b.obj_aligns
            && a.dyn_objs == b.dyn_objs
            && a.dyn_count == b.dyn_count
            && a.escaped == b.escaped
            && a.temps == b.temps
            && a.deref_roots == b.deref_roots
            && a.pending_masks == b.pending_masks
            && a.pending_borrow == b.pending_borrow
            && a.borrowing == b.borrowing
            && a.restricts == b.restricts
            && a.cut_snaps.len() == b.cut_snaps.len();
        if !same {
            return None;
        }
        let end = match (x, y) {
            (ArmEnd::Val(x), ArmEnd::Val(y)) if ctx.tm.width(x) == ctx.tm.width(y) => {
                ArmEnd::Val(ctx.join_value(cond, x, y)?)
            }
            (ArmEnd::Join, ArmEnd::Join) => ArmEnd::Join,
            (ArmEnd::Ret(None), ArmEnd::Ret(None)) => ArmEnd::Ret(None),
            (ArmEnd::Ret(Some(x)), ArmEnd::Ret(Some(y))) if ctx.tm.width(x) == ctx.tm.width(y) => {
                ArmEnd::Ret(Some(ctx.join_value(cond, x, y)?))
            }
            _ => return None,
        };
        let env = self.env;
        let epoch = base.mem.epoch;
        let mut read = |ctx: &mut Ctx, m: &Mem, addr: T, size: u8| {
            let mut init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
            ctx.mem_read(m, addr, size, &mut init)
        };
        self.mem = ctx.join_mem(cond, &base.mem, &a.mem, &self.mem, true, &mut read)?;
        // What each arm accessed was accessed where that arm was taken.
        let n = ctx.tm.not(cond);
        let old = base.access_seq;
        let shift = a.access_seq - old;
        let mut accesses: Vec<Access> = self.accesses.iter().filter(|y| y.seq <= old).cloned().collect();
        for (list, g, shift) in [(&a.accesses, cond, 0), (&self.accesses, n, shift)] {
            for y in list.iter().filter(|y| y.seq > old) {
                let mut y = y.clone();
                y.seq += shift;
                y.guard = Some(match y.guard {
                    Some(inner) => ctx.tm.and(g, inner),
                    None => g,
                });
                accesses.push(y);
            }
        }
        if accesses.len() > MAX_ACCESSES {
            let excess = accesses.len() - MAX_ACCESSES;
            // (Dropping a store could hide that it gave the memory another type.)
            if accesses[..excess].iter().any(|y| y.store) {
                return None;
            }
            accesses.drain(..excess);
        }
        self.accesses = accesses;
        self.access_seq += shift;
        self.seq_points = self.seq_points.max(a.seq_points) + 1;
        // Facts that hold on one side only are dropped; they are found again when needed.
        self.claims.retain(|c| a.claims.contains(c));
        self.touched.retain(|g| a.touched.contains(g));
        for x in &a.plain {
            if !self.plain.contains(x) {
                self.plain.push(*x);
            }
        }
        self.last_br = None;
        let mut cov = a.cov;
        Some((end, cov.split_off(base.cov.len())))
    }

    fn run_body(
        &mut self,
        ctx: &mut Ctx,
        body: &Body,
        ret_ty: TypeId,
        start: usize,
        mut skip_cut: bool,
        until: Option<usize>,
    ) -> R<BodyEnd> {
        let p = self.prog();
        let mut b = start;
        loop {
            ctx.step()?;
            if until == Some(b) {
                return Ok(BodyEnd::Join);
            }
            if endless(body, b) {
                // `for (;;) {}`: the function stays here for ever and does nothing more.
                // That is an end of the path, which the binary must reach in the same way
                // (a branch to itself).
                self.event(ctx, "<hang>", Vec::new(), None, true);
                return Err(Stop::Halt);
            }
            if self.frames.len() == 1 && !self.cut_blocks.is_empty() {
                if !skip_cut && self.cut_blocks.contains(&b) {
                    if ctx.no_fork > 0 {
                        // A loop head inside an arm: the region is not merged.
                        return Err(Stop::Truncated(crate::sym::NO_FORK.into()));
                    }
                    if !self.dyn_objs.is_empty() {
                        return Err(Stop::Unsupported(
                            "loop proof: an object of dynamic size (variable-length array, alloca) is live".into(),
                        ));
                    }
                    self.cut_snaps.push(CutSnap {
                        block: b,
                        mem: self.mem.clone(),
                        last_br: self.last_br,
                        nev: self.events.len() as u32,
                    });
                    let arrivals = match self.cut_only {
                        Some(only) => self.cut_snaps.iter().filter(|s| s.block == only).count(),
                        None => self.cut_snaps.len(),
                    };
                    if arrivals >= self.cut_stop && self.cut_only.is_none_or(|only| only == b) {
                        return Ok(BodyEnd::Cut(b));
                    }
                }
                self.last_br = None;
            }
            skip_cut = false;
            let blk = &body.blocks[b];
            for op in &blk.ops {
                self.cov.push(op.cov);
                crate::explain::report::at_src(ctx.pc.len(), op.cov);
                match &op.kind {
                    OpKind::Eval(e) => {
                        self.eval(ctx, e)?;
                    }
                    OpKind::Init { var, zero, items } => {
                        let base = self.frames.last().unwrap().locals[*var as usize];
                        let lty = p.funcs[self.frames.last().unwrap().func as usize].locals[*var as usize].ty;
                        self.init_object(ctx, base, lty, *zero, items)?;
                    }
                }
            }
            if blk.term_cov != super::lower::NO_COV {
                self.cov.push(blk.term_cov);
                crate::explain::report::at_src(ctx.pc.len(), blk.term_cov);
            }
            match &blk.term {
                Term::Jump(t) => b = *t,
                Term::Br(c, t, f) => {
                    let v = self.eval(ctx, c)?;
                    let nz = self.truth(ctx, v, c.ty);
                    if ctx.merge {
                        let key = (body as *const Body as usize, b);
                        let join = match ctx.src_joins.get(&key) {
                            Some(j) => *j,
                            None => {
                                let j = region_join(body, b);
                                ctx.src_joins.insert(key, j);
                                j
                            }
                        };
                        if let Some(j) = join {
                            let until = (j != usize::MAX).then_some(j);
                            let (t, f) = (*t, *f);
                            let mut arm = |s: &mut Self, ctx: &mut Ctx, taken: bool| -> R<ArmEnd> {
                                match s.run_body(ctx, body, ret_ty, if taken { t } else { f }, false, until)? {
                                    BodyEnd::Join => Ok(ArmEnd::Join),
                                    BodyEnd::Ret(v) => Ok(ArmEnd::Ret(v)),
                                    BodyEnd::Cut(_) => Err(Stop::Truncated(crate::sym::NO_FORK.into())),
                                }
                            };
                            match self.merge_arms(ctx, nz, &mut arm)? {
                                Some(ArmEnd::Join) => {
                                    b = j;
                                    continue;
                                }
                                Some(ArmEnd::Ret(v)) => return Ok(BodyEnd::Ret(v)),
                                _ => {}
                            }
                        }
                    }
                    ctx.fork_kind = if self.frames.len() > 1 { 6 } else { 3 };
                    if !ctx.merge {
                        // (For `verify::verify_function`: is this a region merging could join?)
                        let key = (body as *const Body as usize, b);
                        let join = match ctx.src_joins.get(&key) {
                            Some(j) => *j,
                            None => {
                                let j = region_join(body, b);
                                ctx.src_joins.insert(key, j);
                                j
                            }
                        };
                        if join.is_some() {
                            ctx.fork_why = Some(MERGEABLE);
                        } else if ctx.profile {
                            ctx.fork_why = Some(region_obstacle(body, b));
                        }
                    } else if ctx.profile {
                        ctx.fork_why = Some("tried");
                    }
                    let taken = ctx.branch(nz)?;
                    if self.frames.len() == 1 {
                        self.last_br = Some((b, taken));
                    }
                    b = if taken { *t } else { *f };
                }
                Term::Switch(e, cases, default) => {
                    let v = self.eval(ctx, e)?;
                    let w = ctx.tm.width(v);
                    let mut target = *default;
                    // The cases by value, when none of them wraps round as an unsigned range:
                    // a large `switch` is then decided by halving (a dozen decisions for a
                    // hundred cases) and not case by case, which would make every path through
                    // an interpreter's dispatch as deep as the number of its opcodes.
                    let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
                    let mut sorted: Vec<(u64, u64, usize)> =
                        cases.iter().map(|&(lo, hi, blk)| (lo & mask, hi & mask, blk)).collect();
                    sorted.sort_unstable();
                    let ordered = sorted.len() > 4
                        && sorted.iter().all(|c| c.0 <= c.1)
                        && sorted.windows(2).all(|p| p[0].1 < p[1].0);
                    let mut rest: &[(u64, u64, usize)] = if ordered { &sorted } else { cases };
                    while ordered && rest.len() > 2 {
                        let mid = rest.len() / 2;
                        let k = ctx.tm.konst(w, rest[mid].0);
                        let below = ctx.tm.ult(v, k);
                        ctx.fork_kind = if self.frames.len() > 1 { 6 } else { 4 };
                        rest = if ctx.branch(below)? { &rest[..mid] } else { &rest[mid..] };
                    }
                    for (lo, hi, blk) in rest {
                        let k = ctx.tm.konst(w, *lo);
                        let c = if lo == hi {
                            ctx.tm.eq(v, k)
                        } else {
                            // lo <= v <= hi in the type of the controlling expression.
                            let d = ctx.tm.sub(v, k);
                            let span = ctx.tm.konst(w, hi.wrapping_sub(*lo));
                            ctx.tm.ule(d, span)
                        };
                        ctx.fork_kind = if self.frames.len() > 1 { 6 } else { 4 };
                        if ctx.branch(c)? {
                            target = *blk;
                            break;
                        }
                    }
                    b = target;
                }
                Term::Ret(None) => return Ok(BodyEnd::Ret(None)),
                Term::Ret(Some(e)) if matches!(p.ty(ret_ty), Type::Record(_)) => {
                    // The result outlives the locals: copy it to a temporary.
                    let v = self.eval(ctx, e)?;
                    let t = self.temp(ctx, "ret");
                    self.copy(ctx, t, v, p.size_of(ret_ty).unwrap_or(0));
                    return Ok(BodyEnd::Ret(Some(t)));
                }
                Term::Ret(Some(e)) => {
                    if !p.is_scalar(ret_ty) {
                        return self.unsupported("returning a non-integer value", e);
                    }
                    return Ok(BodyEnd::Ret(Some(self.eval(ctx, e)?)));
                }
                Term::Unreachable => return Err(Stop::Undefined),
            }
        }
    }
}

/// The scalar and array members of structure type `ty`, nested structures flattened:
/// (offset, size).  None if it has a union, a bit-field or an incomplete member.
fn leaves(prog: &Program, ty: TypeId, base: u32, out: &mut Vec<(u32, u32)>) -> Option<()> {
    match prog.ty(ty) {
        Type::Record(r) => {
            let r = &prog.records[*r as usize];
            if r.is_union || !r.complete {
                return None;
            }
            for f in &r.fields {
                if f.bits.is_some() {
                    return None;
                }
                leaves(prog, f.ty, base + f.offset, out)?;
            }
        }
        _ => out.push((base, prog.size_of(ty)?)),
    }
    Some(())
}

/// Structures with static storage that have no symbol of their own but whose members do:
/// LLVM replaces a structure whose address is never used as a whole by one object per member
/// that the program uses, named `name.N` in the order of the members.  A part is bound to a
/// member only if the sizes leave a single way to do it, and if its initial contents in the
/// image are the member's in the source.
fn split_globals(prog: &Program, image: &Image, global_addr: &[Option<u32>]) -> HashMap<u32, Vec<(u32, u32, u32)>> {
    let mut out = HashMap::new();
    let mut parts: HashMap<&str, Vec<(u32, &crate::image::Symbol)>> = HashMap::new();
    for s in image.symbols.iter().filter(|s| s.kind != crate::image::SymKind::Func) {
        if let Some((base, n)) = s.name.rsplit_once('.')
            && let Ok(n) = n.parse::<u32>()
        {
            parts.entry(base).or_default().push((n, s));
        }
    }
    if parts.is_empty() {
        return out;
    }
    for (i, g) in prog.globals.iter().enumerate() {
        if global_addr[i].is_some() || !g.defined || g.is_volatile || image.object(&g.name).is_some() {
            continue;
        }
        // (Two objects of the name, in two files: which parts are whose is not known.)
        if prog.globals.iter().filter(|o| o.defined && o.name == g.name).count() != 1 {
            continue;
        }
        let Some(syms) = parts.get(&*g.name) else { continue };
        let mut syms = syms.clone();
        syms.sort_by_key(|s| s.0);
        if syms.windows(2).any(|w| w[0].0 == w[1].0) {
            continue;
        }
        let mut fields = Vec::new();
        if !matches!(prog.ty(g.ty), Type::Record(_)) || leaves(prog, g.ty, 0, &mut fields).is_none() {
            continue;
        }
        // Order-preserving assignments of the parts to members of the same size: ways[k][j] =
        // number of ways to place parts k.. on members j.. (capped at 2).
        let (np, nf) = (syms.len(), fields.len());
        if np > nf {
            continue;
        }
        let mut ways = vec![vec![0u8; nf + 2]; np + 1];
        ways[np] = vec![1; nf + 2];
        for k in (0..np).rev() {
            for j in (0..nf).rev() {
                let here = if syms[k].1.size == fields[j].1 {
                    ways[k + 1][j + 1]
                } else {
                    0
                };
                ways[k][j] = (here + ways[k][j + 1]).min(2);
            }
        }
        if ways[0][0] != 1 {
            continue;
        }
        let mut bound = Vec::new();
        let mut j = 0;
        for (k, (_, sym)) in syms.iter().enumerate() {
            while !(sym.size == fields[j].1 && ways[k + 1][j + 1] == 1) {
                j += 1;
            }
            bound.push((fields[j].0, fields[j].1, sym.addr));
            j += 1;
        }
        // Initial contents.  (An address in the initialiser is not compared here: refuse.)
        let init = g.init.as_ref();
        if init.is_some_and(|x| !x.relocs.is_empty()) {
            continue;
        }
        let same = bound.iter().all(|&(off, size, addr)| {
            let want: Vec<u8> = (off..off + size)
                .map(|o| init.and_then(|x| x.bytes.get(o as usize).copied()).unwrap_or(0))
                .collect();
            match image.read(addr, size) {
                Some(have) => have == &want[..],
                None => want.iter().all(|&b| b == 0),
            }
        });
        if same {
            out.insert(i as u32, bound);
        }
    }
    out
}