cverif 0.0.3

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
//! 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, 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>>,
    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>)>,
    /// 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>,
    /// A hosted program: the compiler may rely on what the C library promises.
    pub hosted: bool,
    /// Memory keeps the type it is first accessed with (see `verify::Options`).
    pub typed_memory: bool,
}

/// 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 {
                let peers = same_name(false);
                // Positional matching is only safe when the file is known to be this unit's.
                let sure = gcc.iter().all(|(_, s)| unit_of(s) == Some(unit)) || prog.units.len() == 1;
                (sure && !gcc.is_empty() && gcc.len() == peers.len())
                    .then(|| peers.iter().position(|&j| j == i).map(|k| gcc[k].1.addr))
                    .flatten()
            }
        } 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> {
        let binding = bind_symbols(prog, image);
        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();
        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")
                    ));
                }
            }
        }
        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)
        };
        for (i, lit) in prog.strings.iter().enumerate() {
            if str_addr[i].is_some() || lit.is_empty() {
                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
            });
        }
        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;
        for &i in &frozen_ids {
            if global_addr[i].is_none() && image.object(&prog.globals[i].name).is_none() {
                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,
            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,
            data_notes,
            callable: Vec::new(),
            hosted: crate::c::target::Target::for_image(image).hosted != Some(false),
            typed_memory: false,
        };
        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();
        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();
        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)
}

/// 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;
    }
}

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,
    store: bool,
}

#[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 {
    let (rx, ry) = (class(p, x.refty), class(p, y.refty));
    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 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,
    }
}

/// 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)>;

pub struct CExec<'a> {
    pub env: &'a CEnv<'a>,
    pub mem: Mem,
    pub events: Vec<Event>,
    /// 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>,
    /// Live local objects: base -> (size, name).
    objs: HashMap<T, (u32, String)>,
    /// Declared types of the local variables among them.
    obj_types: HashMap<T, TypeId>,
    /// 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)>,
    plain: Vec<(T, u32)>,
    access_seq: 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,
    /// 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)>,
}

/// 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),
}

/// 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"];

/// 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",
];

impl<'a> CExec<'a> {
    pub fn new(env: &'a CEnv<'a>) -> CExec<'a> {
        CExec {
            env,
            mem: Mem::default(),
            events: Vec::new(),
            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(),
            obj_types: 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(),
            plain: Vec::new(),
            access_seq: 0,
            restricts: Vec::new(),
            cut_blocks: Vec::new(),
            cut_stop: usize::MAX,
            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();
        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 {
        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<()> {
        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))
                && !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(())
    }

    fn assume_disjoint(&mut self, ctx: &mut Ctx, a: T, an: u32, b: T, bn: u32) -> R<()> {
        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);
        let ok = ctx.tm.and(c1, c2);
        ctx.assume(ok)
    }

    /// 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: T, size: u32, base: TypeId, 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,
            store,
        };
        let earlier = std::mem::take(&mut self.accesses);
        let mut result = Ok(());
        '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 !x.store && y.store && !types_may_alias(p, &x, y) {
                let superseded = earlier[i + 1..]
                    .iter()
                    .any(|z| z.store && z.addr == x.addr && z.size >= x.size && types_may_alias(p, &x, z));
                if !superseded {
                    result = self.assume_disjoint(ctx, x.addr, x.size, y.addr, y.size);
                    if result.is_err() {
                        break 'outer;
                    }
                    continue;
                }
            }
            // On request: no two accesses of incompatible types touch the same memory.
            if self.env.typed_memory && (x.store || y.store) && !types_may_alias(p, &x, y) {
                result = self.assume_disjoint(ctx, x.addr, x.size, y.addr, y.size);
                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 x.store
                && !y.store
                && !types_may_alias(p, &x, y)
                && earlier[..i]
                    .iter()
                    .rev()
                    .take_while(|z| !z.store)
                    .any(|z| z.addr == x.addr && z.size == x.size && z.refty == x.refty && z.base == x.base)
            {
                result = self.assume_disjoint(ctx, x.addr, x.size, y.addr, y.size);
                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_disjoint(ctx, x.addr, x.size, y.addr, y.size);
                    if result.is_err() {
                        break 'outer;
                    }
                    break;
                }
            }
        }
        self.accesses = earlier;
        result?;
        if !self.accesses.iter().any(|y| {
            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), 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()
    }

    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 {
            self.zero(ctx, base, p.size_of(ty).unwrap_or(0));
        }
        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, 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)?;
                // 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 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.
                            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);
                            if ctx.tm.as_const(ok).is_none() && !ctx.ub.contains(&ok) {
                                ctx.ub.push(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) => {
                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);
                    }
                }
                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)
    }

    pub fn eval(&mut self, ctx: &mut Ctx, e: &Expr) -> R<T> {
        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);
                }
                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);
                }
                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 va = self.eval(ctx, a)?;
                let vb = self.eval(ctx, b)?;
                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)?;
                let nz = self.truth(ctx, va, a.ty);
                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)?;
                let nz = self.truth(ctx, vc, c.ty);
                if ctx.branch(nz)? {
                    self.eval(ctx, a)
                } else {
                    self.eval(ctx, b)
                }
            }
            EK::Comma(a, b) => {
                self.eval(ctx, a)?;
                self.eval(ctx, b)
            }
            EK::Assign(lv, rv) => {
                let v = self.eval(ctx, rv)?;
                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_write(ctx, addr, bounds, *bit, *bw, e.ty, v);
                }
                let (addr, bounds) = self.lvalue(ctx, lv)?;
                if self.observable(ctx, lv, addr) {
                    self.volatile_write(ctx, lv, addr, v)?;
                    return Ok(v);
                }
                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.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 (addr, bounds) = self.lvalue(ctx, lv)?;
                let vol = self.observable(ctx, lv, addr);
                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)?
                };
                self.prev.push(old);
                let nv = self.eval(ctx, newv);
                self.prev.pop();
                let nv = nv?;
                if vol {
                    self.volatile_write(ctx, lv, addr, nv)?;
                } else {
                    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) => self.call(ctx, e, callee, args),
            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)?;
                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();
                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, false)
                } 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);
                }
                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 ----------------------------------------------------------------

    fn call(&mut self, ctx: &mut Ctx, e: &Expr, callee: &Expr, args: &[Expr]) -> R<T> {
        let p = self.prog();
        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,
                };
                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);
                        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 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));
        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);
                }
                vals.push(self.eval(ctx, a)?);
            }
            let r = self.run_function(ctx, fid, &vals)?;
            return Ok(r.unwrap_or(void));
        }
        let vals = self.event_args(ctx, args)?;
        // Built-ins with known semantics (a function the source defines is what its body says).
        match if opaque { "" } 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" if vals.len() == 1 => {
                let c = ctx.tm.popcount(vals[0].0);
                let b = ctx.tm.extract(c, 0, 1);
                return Ok(ctx.tm.zext(b, 32));
            }
            "__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).
                if let Some(n) = ctx.unique_value(vals[2].0)
                    && n <= MAX_MEM_INLINE
                {
                    let dst = vals[0].0;
                    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));
                }
            }
            "__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));
            }
            "__builtin_parity" | "__builtin_parityl" if vals.len() == 1 => {
                let v = vals[0].0;
                let mut acc = ctx.tm.extract(v, 0, 1);
                for i in 1..ctx.tm.width(v) {
                    let b = ctx.tm.extract(v, i, 1);
                    acc = ctx.tm.xor(acc, b);
                }
                return Ok(ctx.tm.zext(acc, 32));
            }
            "__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)));
            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)
            .then(|| match (&*f.name, vals.len()) {
                ("memcpy" | "memmove" | "memset" | "strncpy" | "strncat", 3) | ("strcpy" | "strcat", 2) => {
                    Some(vals[0].0)
                }
                _ => None,
            })
            .flatten();
        let twice = RETURNS_TWICE.contains(&&*f.name) || p.returns_twice.contains(&f.name);
        if twice && self.frames.len() > 1 {
            // The frame that would be re-entered is the binary's, and which function of the
            // binary that is depends on what the compiler inlined.
            return Err(Stop::Unsupported(format!(
                "call to {}, which may return twice, from a function inlined into the one under verification",
                f.name
            )));
        }
        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.event_result(ctx, ret_ty, 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 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);
        self.event_result(ctx, ft.ret, r)
    }

    fn event(
        &mut self,
        ctx: &mut Ctx,
        name: &str,
        args: Vec<(T, bool)>,
        ret: Option<(u8, bool)>,
        noreturn: bool,
    ) -> Option<T> {
        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.
    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)
            && !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> {
        for &(v, _) in args {
            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,
                    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,
                dynamic: None,
                name,
                pre,
                post: Vec::new(),
            });
        }
        // From the callee's return on, pointers of unknown origin may point into these objects.
        for e in &out {
            if !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(_) => 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);
            self.objs.insert(base, (p.size_of(l.ty).unwrap_or(0), name));
            self.obj_types.insert(base, l.ty);
            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());
        if let Ok(BodyEnd::Cut(_)) = r {
            // Stopped at a cut point: the frame stays live for the state to be examined.
            return r;
        }
        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 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
    }

    /// 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()
    }

    fn run_body(&mut self, ctx: &mut Ctx, body: &Body, ret_ty: TypeId, start: usize, mut skip_cut: bool) -> R<BodyEnd> {
        let p = self.prog();
        let mut b = start;
        loop {
            ctx.step()?;
            if self.frames.len() == 1 && !self.cut_blocks.is_empty() {
                if !skip_cut && self.cut_blocks.contains(&b) {
                    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,
                    });
                    if self.cut_snaps.len() >= self.cut_stop {
                        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);
                    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;
                    for (lo, hi, blk) in cases {
                        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)
                        };
                        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),
            }
        }
    }
}