cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
//! Loops whose trip count depends on the input, proved by induction.
//!
//! Path-by-path exploration can only cover a loop up to some number of iterations.  This module
//! instead pairs a loop of the source with a loop of the machine code at a *cut point* (a block
//! of the source, an address of the binary) and proves a simulation relation there:
//!
//! * **base** — on every path from the function entry, when both sides first arrive at the cut
//!   point the relation holds;
//! * **step** — started at the cut point in *any* state satisfying the relation, both sides
//!   either leave the function with equal results or arrive at the cut point again with the
//!   relation holding, having performed the same observable events in between.
//!
//! Together these cover every execution with any number of iterations.  The relation is a
//! conjunction of simple facts guessed from one concrete path through the loop — a location
//! keeps the value it had on arrival, a machine location equals a source variable, or is a
//! linear function of one — and weakened until it is inductive: a fact that fails in the base
//! or the step is dropped and everything is checked again.  Whatever no fact constrains is
//! replaced by a fresh unknown at the start of the step, so the step really covers every state
//! the relation admits.  Any difficulty makes the attempt fail, leaving the function to the
//! bounded exploration; nothing found here is ever reported as a difference.
//!
//! # Dispatch loops
//!
//! A loop whose body is a `switch` or an if-chain of independent arms, each going back to the
//! head (an interpreter, a lexer, a scanner over a format string) is the same proof: the step
//! from the head is one segment per arm, and the arms are the paths of the step.  Nothing is
//! assumed about an arm that is not proved: the function is PROVED only when every path of
//! the step from every cut arrives or leaves correctly, and no credit is given for a part of
//! the arms (a relation that only some arms preserve is not a relation, so "the arms proved"
//! would be proved from states the others may never produce).  Three things make it work:
//!
//! * **All the candidates of a location at once.**  The one path the relation is guessed from
//!   goes through one or two arms, and what those arms leave alone looks constant, or equal
//!   to something it is unrelated to.  Every candidate still standing is part of the relation:
//!   the step starts from states that satisfy them all and each arrival is asked for each of
//!   them, so a round removes exactly the candidates some path breaks.  (Tried one after the
//!   other instead, a wrong candidate lets the step start in states no execution reaches, and
//!   right candidates of other locations are refuted there.)  A path of the step that fails
//!   outright (a mismatch, a solver that gives up) while candidates are still being refuted
//!   proves nothing either way, since it may start from such a state: the failure is reported
//!   only if it is still there in the round that refutes nothing.
//! * **Cuts from a path prefix.**  Guessing wants a path that reaches the loop and goes round
//!   it twice.  In a large function no *whole* path of that kind is found within the budget
//!   (it would also have to leave the loop and reach a return), so when that search fails the
//!   source is run until it has arrived twice at a loop head and the machine code until its
//!   first backward jump after the same events (`SegCtl::prefix`).  Such a run proves nothing
//!   and nothing is concluded from it but where to cut and what to guess.
//! * **Ranges of state variables.**  A variable only ever given constants stays within them
//!   (`constant_ranges`); compilers thread the jumps between the arms of a state machine and
//!   keep in a register only the values the arms store.  As every fact, proved or dropped.
//!
//! The source side decides a `switch` of more than four ordered cases by halving, so an arm is
//! a path of depth log2(cases), not of depth cases.
//!
//! Not done: a loop that calls a function that may return twice (a bytecode interpreter inside
//! its exception region), several addresses of the binary for one loop head of the source
//! (jump threading at `-O2`), and loops inside a callee the binary inlined.
//!
//! # What is assumed rather than guessed
//!
//! Every fact of the relation is a guess that the base case and the step must prove, so a
//! wrong or lucky guess costs a proof, never soundness.  Three things are not of that kind:
//!
//! * **Locals visible to external code.**  A cut point carries the set of locals whose address
//!   external code has seen at some arrival, each with its place in the binary's frame, and
//!   the step starts with all of them exposed and bound (source object and frame cells are the
//!   same memory).  At an arrival where one of them is not exposed yet this is an
//!   over-approximation on both sides at once: more pointers may alias the object than can,
//!   so the step covers more states than occur.  Binding early is the choice of the address
//!   of a source object, which the source's behaviour does not depend on beyond what it
//!   assumed about that address (`can_bind` checks that the choice contradicts none of it);
//!   the step then has to show that the binary passes exactly that address at every call, as
//!   the first call of an ordinary path does, and that the place is aligned.  An arrival with
//!   the object bound elsewhere, or with an object of dynamic size exposed, fails the attempt.
//!   Unknown values of the start state are marked as possibly pointing into exposed objects.
//! * **Bytes the source never wrote.**  A frame cell of an exposed local "holds the object's
//!   bytes" also where the source's bytes are indeterminate: the step then starts with the
//!   source's byte equal to whatever the cell holds.  An indeterminate byte may be any value,
//!   this one included, and the binary only has to behave as the source may.
//! * **Stale stack addresses.**  A register that holds a stack address at some arrival and
//!   that no fact describes starts the step as an unknown that is *not* treated as a pointer
//!   into the frame.  That is harmless only if the value is never used, so every path of the
//!   step is checked: the code must write the register before reading it, and before any call
//!   that could read it as an argument.  (Returned in r0, or left in a callee-saved register
//!   at the return, the unknown fails the ordinary comparisons.)

use super::*;
use crate::c::ast::{BinOp, Body, EK, Expr, Term, Type};
use crate::c::exec::CutSnap;
use crate::term::Node;
use crate::thumb::exec::MachSnap;
use std::collections::BTreeMap;

/// Coverage established by a successful proof.
#[derive(Default)]
pub(super) struct Proof {
    pub cov: Vec<u32>,
    pub bytes: Vec<(u32, u8)>,
    pub paths: usize,
    /// The proof rests on the size limit of objects (see `size_assumption`).
    pub object_size: bool,
}

/// Why no proof by induction was found: a short stable code for the kind of obstacle and the
/// detail of the attempt that got furthest.
#[derive(Clone, Debug)]
pub(super) struct Failure {
    pub code: &'static str,
    pub detail: String,
    /// How far the attempt got; of several attempts the furthest is reported.
    rank: u8,
}

impl Failure {
    fn new(code: &'static str, detail: impl Into<String>, rank: u8) -> Failure {
        Failure {
            code,
            detail: detail.into(),
            rank,
        }
    }

    /// The failure of one attempt with given cut points, in the base case or in the step.
    fn of(stop: &Stop, step: bool, cuts: &[Cut]) -> Failure {
        let at: Vec<String> = cuts.iter().map(|c| format!("{:#x}", c.m_pc)).collect();
        let phase = if step { "step" } else { "base case" };
        let place = format!("{phase}, cut at {}", at.join(" "));
        let rank = 4 + u8::from(step);
        match stop {
            Stop::Truncated(w) if w.contains("did not stabilise") => {
                Failure::new("no-relation", format!("{w} ({place})"), rank)
            }
            Stop::Truncated(w) if w.contains("branch depth") || w.contains("too many paths") => {
                Failure::new("body-too-large", format!("{w} ({place})"), rank)
            }
            Stop::Truncated(w) => Failure::new("budget", format!("{w} ({place})"), rank),
            Stop::Unsupported(w) => {
                let w = w.strip_prefix("loop proof: ").unwrap_or(w);
                let code = if w.contains("visible to external code") {
                    "exposed-local"
                } else if w.contains("dynamic size") {
                    "dynamic-object"
                } else if w.contains("loop head") || w.contains("different loops") {
                    "events"
                } else {
                    "unsupported-shape"
                };
                Failure::new(code, format!("{w} ({place})"), rank)
            }
            Stop::Mismatch(w, _) | Stop::Inconclusive(w) => Failure::new(
                if step { "step-failed" } else { "base-failed" },
                format!("{w} ({place})"),
                rank,
            ),
            _ => Failure::new("unsupported-shape", format!("{stop:?} ({place})"), rank),
        }
    }
}

/// How a source value is seen in a machine location of another width.
#[derive(Clone, Copy, Debug, PartialEq)]
enum View {
    Same,
    Zext,
    Sext,
    /// The bits starting at this position.
    Part(u8),
}

#[derive(Clone, Debug)]
enum Cand {
    /// The location holds this value on every arrival.
    Inv(T),
    /// A machine location holds the value of source location `.0`.
    Rel(usize, View),
    /// A machine location holds `a * view(source location) + b`.
    Lin(usize, View, u64, T),
    /// A machine location holds the value an expression of the source has in the source's
    /// state (the index is into `Cut::exprs`): what the compiler computed once and kept, such
    /// as the address of the element a loop is at, or a value loaded before the loop.
    Val(usize, View),
    /// A machine location holds `a * view(source location .0) + base + d`, where the base is
    /// the value of another source location or of an expression of the source: a pointer
    /// that walks an array whose address is not the same on every path into the loop.
    Lin2(usize, View, u64, Base, u64),
    /// A location holds `a * (source location .0) + sign * (source location .2) + d`: two
    /// variables of the source that both move, or a difference of them (an index kept as
    /// the distance between two pointers), plus a third that does not move when `.4` names
    /// one (the end of an array as pointer - index + length).
    Two(usize, u64, usize, bool, Option<usize>, u64),
    /// A cell of the binary's frame holds the bytes of the source's object `.0` at offset
    /// `.1`: the object is visible to external code and the two are the same memory.  Bytes
    /// the source never wrote are indeterminate there, and the cell may hold anything.
    Obj(T, i64),
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Base {
    /// A source location (index into `Cut::c_locs`).
    Loc(usize),
    /// An expression of the source (index into `Cut::exprs`).
    Expr(usize),
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Place {
    Reg(u8),
    Mem { base: T, off: i64, size: u8 },
}

#[derive(Clone, Debug)]
struct Loc {
    place: Place,
    /// Facts to try, strongest first; `active == cands.len()` means nothing is known.
    cands: Vec<Cand>,
    active: usize,
    /// Facts were already added after the explored path's own were refuted.
    refined: bool,
}

impl Loc {
    fn width(&self) -> u8 {
        match self.place {
            Place::Reg(_) => 32,
            Place::Mem { size, .. } => size * 8,
        }
    }
}

#[derive(Clone)]
struct Cut {
    id: usize,
    c_block: usize,
    m_pc: u32,
    /// Arrivals of the source at its cut block when the machine code first reaches its own
    /// (more than one when the compiler peeled iterations off the front of the loop).
    lead: usize,
    /// Source iterations per machine iteration (more than one for an unrolled loop).
    ratio: usize,
    c_locs: Vec<Loc>,
    m_locs: Vec<Loc>,
    /// Private objects of the source whose every byte is a location.
    c_full: HashSet<T>,
    /// Locals of the source external code can reach at some arrival, and where the binary
    /// keeps them.  At an arrival where one is not exposed yet, nothing is lost by treating it
    /// as exposed already: the step then covers more states than occur.
    exposed: Vec<ExposedLocal>,
    /// Registers that hold a stack address at some arrival and about which the relation says
    /// nothing: neither the code nor a callee may read them before the code writes them.
    stale: u16,
    /// The branch that leads into the cut block, known to have been taken on arrival.
    pred: Option<(usize, bool)>,
    pred_exprs: Vec<(Expr, bool)>,
    /// Expressions of the source whose value a machine location may hold (`Cand::Val`).
    exprs: std::rc::Rc<Vec<Expr>>,
    /// Comparisons between variables of the source believed to hold on every arrival.
    facts: Vec<(Expr, bool)>,
    fail_facts: BTreeSet<usize>,
    /// Conditions on the source's state that hold at this point in every execution without
    /// undefined behaviour (`size_assumption`): assumed at the start of the step, not proved.
    assumed: Vec<(Expr, bool)>,
    /// World memory is not modified by the loop: both sides keep the write log of the first arrival.
    world_same: bool,
    c_world: Vec<Write>,
    c_epoch: u32,
    m_world: Vec<Write>,
    m_epoch: u32,
    // Facts refuted in the current round.
    // (location, which of its candidates)
    fail_c: BTreeSet<(usize, usize)>,
    fail_m: BTreeSet<(usize, usize)>,
    fail_pred: bool,
    fail_world: bool,
    grew: bool,
}

impl Cut {
    fn refuted(&self) -> bool {
        !self.fail_c.is_empty()
            || !self.fail_m.is_empty()
            || !self.fail_facts.is_empty()
            || self.fail_pred
            || self.fail_world
            || self.grew
    }
}

fn fail(what: &str) -> Stop {
    cut_error(what)
}

fn successors(t: &Term) -> Vec<usize> {
    match t {
        Term::Jump(t) => vec![*t],
        Term::Br(_, t, f) => vec![*t, *f],
        Term::Switch(_, cases, d) => cases.iter().map(|c| c.2).chain([*d]).collect(),
        Term::Ret(_) | Term::Unreachable => Vec::new(),
    }
}

struct CLoop {
    /// Candidate cut blocks: the blocks entered from the head inside the loop, then the head.
    cands: Vec<usize>,
    head: usize,
    inside: Vec<usize>,
}

/// Natural loops of the control-flow graph, by head.
fn c_loops(body: &Body) -> Vec<CLoop> {
    let n = body.blocks.len();
    let succ: Vec<Vec<usize>> = body.blocks.iter().map(|b| successors(&b.term)).collect();
    // Iterative depth-first search; an edge to a block on the current path is a back edge.
    let mut state = vec![0u8; n];
    let mut back: Vec<(usize, usize)> = Vec::new();
    let mut stack: Vec<(usize, usize)> = vec![(0, 0)];
    state[0] = 1;
    while let Some(&mut (b, ref mut i)) = stack.last_mut() {
        if *i < succ[b].len() {
            let s = succ[b][*i];
            *i += 1;
            match state[s] {
                0 => {
                    state[s] = 1;
                    stack.push((s, 0));
                }
                1 => back.push((b, s)),
                _ => {}
            }
        } else {
            state[b] = 2;
            stack.pop();
        }
    }
    let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (b, ss) in succ.iter().enumerate() {
        if state[b] != 0 {
            for &s in ss {
                preds[s].push(b);
            }
        }
    }
    let mut heads: Vec<usize> = back.iter().map(|e| e.1).collect();
    heads.sort_unstable();
    heads.dedup();
    let loops = heads
        .into_iter()
        .map(|head| {
            let mut inside: HashSet<usize> = HashSet::from([head]);
            let mut work: Vec<usize> = back.iter().filter(|e| e.1 == head).map(|e| e.0).collect();
            while let Some(b) = work.pop() {
                if inside.insert(b) {
                    work.extend(preds[b].iter().copied());
                }
            }
            let mut cands: Vec<usize> = Vec::new();
            if matches!(body.blocks[head].term, Term::Br(..)) {
                for &s in &succ[head] {
                    if s != head && inside.contains(&s) && !cands.contains(&s) {
                        cands.push(s);
                    }
                }
            }
            cands.push(head);
            (cands, inside)
        })
        .collect::<Vec<_>>();
    // Where the compiler rotated the loop or moved its test, the machine code's loop passes
    // its own block boundaries at other points of the source's loop: the blocks that end an
    // iteration, and those a branch inside the loop leads to.  Blocks of an inner loop are
    // left to that loop.
    let sets: Vec<HashSet<usize>> = loops.iter().map(|l| l.1.clone()).collect();
    loops
        .into_iter()
        .map(|(mut cands, inside)| {
            let head = *cands.last().expect("the head");
            let inner = |b: usize| {
                sets.iter()
                    .any(|o| o.len() < inside.len() && o.contains(&b) && o.is_subset(&inside))
            };
            let mut more: Vec<usize> = Vec::new();
            for &b in &inside {
                if cands.contains(&b) || inner(b) {
                    continue;
                }
                let latch = succ[b].contains(&head);
                let joined = preds[b].iter().filter(|q| inside.contains(q)).count() >= 2;
                let after_br = preds[b]
                    .iter()
                    .any(|&q| inside.contains(&q) && matches!(body.blocks[q].term, Term::Br(..)));
                if latch || joined || after_br {
                    more.push(b);
                }
            }
            more.sort_unstable();
            more.truncate(6);
            cands.extend(more);
            let mut inside: Vec<usize> = inside.into_iter().collect();
            inside.sort_unstable();
            CLoop { cands, head, inside }
        })
        .collect()
}

/// The conditions that hold when `e` evaluated to `want`, if evaluating them again has no effect.
fn pure_conditions(p: &Program, e: &Expr, want: bool, out: &mut Vec<(Expr, bool)>) -> bool {
    fn pure(p: &Program, e: &Expr) -> bool {
        match &e.kind {
            EK::Const(_) | EK::Local(_) | EK::Global(_) | EK::Func(_) | EK::Str(_) => true,
            EK::Load(x) => !p.is_volatile(x.ty) && pure(p, x),
            EK::Deref(x)
            | EK::Member(x, _)
            | EK::BitField(x, ..)
            | EK::Addr(x)
            | EK::Cast(x)
            | EK::Neg(x)
            | EK::BitNot(x)
            | EK::LogNot(x) => pure(p, x),
            EK::Bin(_, a, b) | EK::PtrAdd(a, b, _) | EK::PtrDiff(a, b, _) => pure(p, a) && pure(p, b),
            _ => false,
        }
    }
    match &e.kind {
        EK::LogNot(x) => pure_conditions(p, x, !want, out),
        EK::LogAnd(a, b) if want => pure_conditions(p, a, true, out) && pure_conditions(p, b, true, out),
        EK::LogOr(a, b) if !want => pure_conditions(p, a, false, out) && pure_conditions(p, b, false, out),
        _ => {
            if p.is_float(e.ty) || !pure(p, e) {
                return false;
            }
            out.push((e.clone(), want));
            true
        }
    }
}

/// Both polarities of every comparison between local variables and constants that the
/// function branches on.  Evaluating one reads only local variables and cannot be undefined.
fn simple_facts(p: &Program, fid: u32, body: &Body) -> Vec<(Expr, bool)> {
    fn leaf(p: &Program, e: &Expr) -> bool {
        match &e.kind {
            EK::Const(_) => true,
            EK::Load(x) => matches!(x.kind, EK::Local(_)) && !p.is_volatile(x.ty) && !p.is_float(e.ty),
            EK::Cast(x) => !p.is_float(e.ty) && leaf(p, x),
            _ => false,
        }
    }
    fn atoms<'e>(p: &Program, e: &'e Expr, out: &mut Vec<&'e Expr>) {
        use crate::c::ast::BinOp::*;
        match &e.kind {
            EK::LogNot(x) => atoms(p, x, out),
            EK::LogAnd(a, b) | EK::LogOr(a, b) => {
                atoms(p, a, out);
                atoms(p, b, out);
            }
            EK::Cast(x) if !leaf(p, e) => atoms(p, x, out),
            EK::Bin(Eq | Ne | Lt | Le, a, b) if leaf(p, a) && leaf(p, b) => out.push(e),
            _ if leaf(p, e) && !matches!(e.kind, EK::Const(_)) => out.push(e),
            _ => {}
        }
    }
    let mut found = Vec::new();
    for b in &body.blocks {
        if let Term::Br(e, ..) = &b.term {
            atoms(p, e, &mut found);
        }
    }
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    // A variable a `switch` selects on, as a state machine's state: it may stay within the
    // values the cases name (the compiler is free to treat the rest alike, and its code then
    // stores one of them where the source keeps whatever the variable held).
    for b in &body.blocks {
        if let Term::Switch(e, cases, _) = &b.term
            && leaf(p, e)
            && !matches!(e.kind, EK::Const(_))
            && !cases.is_empty()
            && out.len() < 8
        {
            let signed = p.is_signed(e.ty);
            let key = |v: u64| if signed { (v as i64) as i128 } else { v as i128 };
            let (Some(lo), Some(hi)) = (
                cases.iter().map(|c| c.0).min_by_key(|&v| key(v)),
                cases.iter().map(|c| c.1).max_by_key(|&v| key(v)),
            ) else {
                continue;
            };
            let konst = |v: u64| Expr {
                kind: EK::Const(v),
                ty: e.ty,
                loc: e.loc,
            };
            let cmp = |op: BinOp, a: Expr, b: Expr| Expr {
                kind: EK::Bin(op, Box::new(a), Box::new(b)),
                ty: crate::c::ast::INT,
                loc: e.loc,
            };
            out.push((cmp(BinOp::Le, e.clone(), konst(hi)), true));
            out.push((cmp(BinOp::Lt, e.clone(), konst(lo)), false));
        }
    }
    out.extend(constant_ranges(p, fid, body));
    for e in found {
        if seen.insert(format!("{:?}", e.kind)) && out.len() < 56 {
            out.push((e.clone(), true));
            out.push((e.clone(), false));
            // A loop counting up to a bound keeps `i <= n`, though it tests `i < n`.
            if let EK::Bin(op @ (BinOp::Lt | BinOp::Le), a, b) = &e.kind {
                let other = if *op == BinOp::Lt { BinOp::Le } else { BinOp::Lt };
                let mut weak = e.clone();
                weak.kind = EK::Bin(other, a.clone(), b.clone());
                out.push((weak.clone(), true));
                out.push((weak, false));
            }
        }
    }
    out
}

/// Locals that are only ever given constant values (the state of a state machine): each
/// stays between the least and the greatest of them, once it has been given one.  As every
/// fact these are guesses, proved or dropped with the rest of the relation.
fn constant_ranges(p: &Program, fid: u32, body: &Body) -> Vec<(Expr, bool)> {
    fn op_loc(items: &[(u32, Expr)]) -> crate::c::lex::Loc {
        items.first().map(|i| i.1.loc).unwrap_or_default()
    }
    // variable -> (its type and where, the constants assigned), None once anything else is done to it
    let mut vars: BTreeMap<u32, Option<(Expr, Vec<u64>)>> = BTreeMap::new();
    fn constant(e: &Expr) -> Option<u64> {
        match &e.kind {
            EK::Const(k) => Some(*k),
            EK::Cast(x) => constant(x),
            _ => None,
        }
    }
    fn walk(e: &Expr, vars: &mut BTreeMap<u32, Option<(Expr, Vec<u64>)>>) {
        match &e.kind {
            EK::Assign(l, r) if matches!(l.kind, EK::Local(_)) => {
                let EK::Local(v) = l.kind else { unreachable!() };
                match (
                    constant(r),
                    vars.entry(v).or_insert_with(|| Some(((**l).clone(), Vec::new()))),
                ) {
                    (Some(k), Some((_, ks))) => ks.push(k),
                    (_, slot) => *slot = None,
                }
                walk(r, vars);
            }
            // (read)
            EK::Load(x) if matches!(x.kind, EK::Local(_)) => {}
            // (anything else done with the variable: its address taken, modified in place)
            EK::Local(v) => {
                vars.insert(*v, None);
            }
            _ => e.children().into_iter().for_each(|c| walk(c, vars)),
        }
    }
    for b in &body.blocks {
        for op in &b.ops {
            match &op.kind {
                crate::c::ast::OpKind::Eval(e) => walk(e, &mut vars),
                crate::c::ast::OpKind::Init { var, items, zero } => {
                    let local = &p.funcs[fid as usize].locals[*var as usize];
                    let lv = Expr {
                        kind: EK::Local(*var),
                        ty: local.ty,
                        loc: op_loc(items),
                    };
                    let k = match &items[..] {
                        [] if *zero => Some(0),
                        [(0, e)] => constant(e),
                        _ => None,
                    };
                    match (k, vars.entry(*var).or_insert_with(|| Some((lv, Vec::new())))) {
                        (Some(k), Some((_, ks))) => ks.push(k),
                        (_, slot) => *slot = None,
                    }
                    items.iter().for_each(|i| walk(&i.1, &mut vars));
                }
            }
        }
        match &b.term {
            Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => walk(e, &mut vars),
            _ => {}
        }
    }
    let mut out = Vec::new();
    for (lv, ks) in vars.into_values().flatten() {
        let w = p.size_of(lv.ty).unwrap_or(0) * 8;
        if ks.len() < 2 || !(8..=32).contains(&w) || p.is_volatile(lv.ty) || p.is_float(lv.ty) || out.len() >= 8 {
            continue;
        }
        let signed = p.is_signed(lv.ty);
        let key = |v: u64| {
            let v = v & crate::term::mask(w as u8);
            if signed {
                crate::term::sext64(v, w as u8) as i128
            } else {
                v as i128
            }
        };
        let (lo, hi) = (
            ks.iter().copied().min_by_key(|&v| key(v)).expect("two constants"),
            ks.iter().copied().max_by_key(|&v| key(v)).expect("two constants"),
        );
        let ty = lv.ty;
        let loc = lv.loc;
        let load = Expr {
            kind: EK::Load(Box::new(lv)),
            ty,
            loc,
        };
        let cmp = |op: BinOp, k: u64| Expr {
            kind: EK::Bin(
                op,
                Box::new(load.clone()),
                Box::new(Expr {
                    kind: EK::Const(k),
                    ty,
                    loc,
                }),
            ),
            ty: crate::c::ast::INT,
            loc,
        };
        out.push((cmp(BinOp::Le, hi), true));
        out.push((cmp(BinOp::Lt, lo), false));
    }
    out
}

/// The value of a side-effect-free expression of the source in a given state of its memory.
/// This is a function of the state and nothing more: it assumes nothing about the pointers it
/// goes through, and need not be what the C semantics would give where that is undefined.  It
/// only serves to state candidate facts, which are proved before they are relied upon.
fn value_of(ctx: &mut Ctx, job: &Job, mem: &Mem, e: &Expr) -> Option<T> {
    let p = job.prog;
    let f = &p.funcs[job.fid as usize];
    fn addr(ctx: &mut Ctx, job: &Job, mem: &Mem, e: &Expr) -> Option<T> {
        let p = job.prog;
        let f = &p.funcs[job.fid as usize];
        match &e.kind {
            EK::Local(i) => {
                let l = f.locals.get(*i as usize)?;
                Some(ctx.private_base(&format!("&{}.{}#{i}@1", f.name, l.name)))
            }
            EK::Global(g) => job.env.global_addr[*g as usize].map(|a| ctx.tm.konst(32, a as u64)),
            EK::Deref(x) => value_of(ctx, job, mem, x),
            EK::Member(x, off) => {
                let a = addr(ctx, job, mem, x)?;
                Some(ctx.tm.add_const(a, *off as u64))
            }
            _ => None,
        }
    }
    let _ = f;
    if p.is_float(e.ty) {
        return None;
    }
    match &e.kind {
        EK::Const(c) => Some(ctx.tm.konst(p.bits(e.ty), *c)),
        EK::Addr(x) => addr(ctx, job, mem, x),
        EK::Load(x) => {
            if p.is_volatile(x.ty) || !p.is_scalar(e.ty) {
                return None;
            }
            let size = p.size_of(e.ty).filter(|s| matches!(s, 1 | 2 | 4))?;
            let a = addr(ctx, job, mem, x)?;
            let env = job.env;
            let epoch = mem.epoch;
            let mut init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
            Some(ctx.mem_read(mem, a, size as u8, &mut init))
        }
        EK::Cast(x) => {
            if p.is_float(x.ty) || !p.is_scalar(e.ty) || !p.is_scalar(x.ty) || matches!(p.ty(e.ty), Type::Bool) {
                return None;
            }
            let v = value_of(ctx, job, mem, x)?;
            Some(ctx.tm.resize(v, p.bits(e.ty), p.is_signed(x.ty)))
        }
        EK::Bin(op, a, b) => {
            let (x, y) = (value_of(ctx, job, mem, a)?, value_of(ctx, job, mem, b)?);
            if ctx.tm.width(x) != ctx.tm.width(y) {
                return None;
            }
            Some(match op {
                BinOp::Add => ctx.tm.add(x, y),
                BinOp::Sub => ctx.tm.sub(x, y),
                BinOp::Mul => ctx.tm.mul(x, y),
                BinOp::And => ctx.tm.and(x, y),
                BinOp::Or => ctx.tm.or(x, y),
                BinOp::Xor => ctx.tm.xor(x, y),
                _ => return None,
            })
        }
        EK::PtrAdd(a, i, size) => {
            let (x, y) = (value_of(ctx, job, mem, a)?, value_of(ctx, job, mem, i)?);
            if ctx.tm.width(x) != 32 {
                return None;
            }
            let y = ctx.tm.resize(y, 32, p.is_signed(i.ty));
            let scaled = ctx.tm.scale(y, *size as u64);
            Some(ctx.tm.add(x, scaled))
        }
        _ => None,
    }
}

/// Expressions of the function whose value the machine code may keep in a register or a stack
/// slot across the iterations of a loop: every side-effect-free subexpression that is more than
/// a variable or a constant, and the address of whatever is read through a pointer.
fn value_exprs(p: &Program, body: &Body) -> Vec<Expr> {
    fn simple(p: &Program, e: &Expr) -> bool {
        match &e.kind {
            EK::Const(_) | EK::Local(_) | EK::Global(_) => true,
            EK::Load(x) => !p.is_volatile(x.ty) && simple(p, x),
            EK::Deref(x) | EK::Member(x, _) | EK::Addr(x) | EK::Cast(x) => simple(p, x),
            EK::Bin(BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor, a, b) => {
                simple(p, a) && simple(p, b)
            }
            EK::PtrAdd(a, b, _) => simple(p, a) && simple(p, b),
            _ => false,
        }
    }
    fn walk(p: &Program, e: &Expr, out: &mut Vec<Expr>) {
        let children: Vec<&Expr> = match &e.kind {
            EK::Deref(x)
            | EK::Member(x, _)
            | EK::BitField(x, ..)
            | EK::Addr(x)
            | EK::Load(x)
            | EK::Cast(x)
            | EK::Neg(x)
            | EK::BitNot(x)
            | EK::LogNot(x) => vec![x],
            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, _) => vec![a, b],
            EK::Cond(a, b, c) => vec![a, b, c],
            EK::Call(f, args) => std::iter::once(&**f).chain(args.iter()).collect(),
            _ => Vec::new(),
        };
        for c in children {
            walk(p, c, out);
        }
        if !simple(p, e) || p.is_float(e.ty) {
            return;
        }
        match &e.kind {
            // The address of what is accessed, and what is read through a pointer.
            EK::Deref(_) | EK::Member(..) => {
                let mut a = e.clone();
                a.kind = EK::Addr(Box::new(e.clone()));
                out.push(a);
            }
            EK::Load(x) if !matches!(x.kind, EK::Local(_)) => out.push(e.clone()),
            EK::Bin(..) | EK::PtrAdd(..) => out.push(e.clone()),
            EK::Cast(x) if !matches!(x.kind, EK::Const(_)) && p.is_scalar(e.ty) && p.bits(e.ty) != p.bits(x.ty) => {
                out.push(e.clone())
            }
            _ => {}
        }
    }
    let mut found = Vec::new();
    for b in &body.blocks {
        for op in &b.ops {
            match &op.kind {
                crate::c::ast::OpKind::Eval(e) => walk(p, e, &mut found),
                crate::c::ast::OpKind::Init { items, .. } => {
                    for (_, e) in items {
                        walk(p, e, &mut found);
                    }
                }
            }
        }
        match &b.term {
            Term::Br(e, ..) | Term::Switch(e, ..) => walk(p, e, &mut found),
            Term::Ret(Some(e)) => walk(p, e, &mut found),
            _ => {}
        }
    }
    let mut seen = HashSet::new();
    found.retain(|e| seen.insert(format!("{:?}", e.kind)));
    found.truncate(96);
    found
}

/// Could `t` be the address of (part of) a private object?  Indeterminate contents of private
/// memory are values, not addresses.
fn may_point_private(ctx: &Ctx, t: T) -> bool {
    let mut seen = HashSet::new();
    let mut stack = vec![t];
    while let Some(x) = stack.pop() {
        if !seen.insert(x) {
            continue;
        }
        if ctx.private_bases.contains(&x) {
            return true;
        }
        if let Node::Load(m, _) = ctx.tm.node(x)
            && *m >= crate::sym::UNINIT_EPOCH
        {
            continue;
        }
        stack.extend(crate::bv::Prover::children_of(ctx.tm.node(x)));
    }
    false
}

fn apply_view(ctx: &mut Ctx, v: T, view: View, w: u8) -> Option<T> {
    let vw = ctx.tm.width(v);
    match view {
        View::Same => (vw == w).then_some(v),
        View::Zext => (vw < w).then(|| ctx.tm.resize(v, w, false)),
        View::Sext => (vw < w).then(|| ctx.tm.resize(v, w, true)),
        View::Part(lo) => (lo as u32 + w as u32 <= vw as u32 && vw > w).then(|| ctx.tm.extract(v, lo, w)),
    }
}

fn views(vw: u8, w: u8) -> Vec<View> {
    if vw == w {
        vec![View::Same]
    } else if vw < w {
        vec![View::Zext, View::Sext]
    } else if vw.is_multiple_of(w) {
        (0..vw / w).map(|i| View::Part(i * w)).collect()
    } else {
        Vec::new()
    }
}

fn c_read(ctx: &mut Ctx, job: &Job, mem: &Mem, place: Place) -> T {
    let Place::Mem { base, off, size } = place else {
        unreachable!("source locations are memory")
    };
    let addr = ctx.tm.add_const(base, off as u64);
    let env = job.env;
    let epoch = mem.epoch;
    let mut init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
    ctx.mem_read(mem, addr, size, &mut init)
}

fn m_read(ctx: &mut Ctx, job: &Job, regs: &[T; 16], mem: &Mem, place: Place) -> T {
    match place {
        Place::Reg(r) => regs[r as usize],
        Place::Mem { base, off, size } => {
            let addr = ctx.tm.add_const(base, off as u64);
            let mut init = image_init(job.image, mem.epoch, None);
            ctx.mem_read(mem, addr, size, &mut init)
        }
    }
}

/// Bytes of private objects covered by locations, per side.
#[derive(Clone, Default)]
struct Cover(HashMap<T, BTreeSet<i64>>);

impl Cover {
    /// Add locations for the uncovered bytes of `[off, off + size)`.  Returns whether any were added.
    fn add(&mut self, locs: &mut Vec<Loc>, base: T, off: i64, size: u32) -> bool {
        let set = self.0.entry(base).or_default();
        let whole = (0..size as i64).all(|i| !set.contains(&(off + i)));
        let mut push = |off: i64, size: u8| {
            locs.push(Loc {
                place: Place::Mem { base, off, size },
                cands: Vec::new(),
                active: 0,
                refined: false,
            })
        };
        if whole && matches!(size, 1 | 2 | 4 | 8) {
            push(off, size as u8);
            set.extend(off..off + size as i64);
            return true;
        }
        let mut any = false;
        let mut i = 0i64;
        while i < size as i64 {
            let o = off + i;
            if set.contains(&o) {
                i += 1;
                continue;
            }
            // Whole aligned words where possible, single bytes otherwise.
            let word = o & 3 == 0 && i + 4 <= size as i64 && (0..4).all(|k| !set.contains(&(o + k)));
            let n = if word { 4 } else { 1 };
            push(o, n as u8);
            set.extend(o..o + n);
            any = true;
            i += n;
        }
        any
    }
}

/// Written extents of the private objects of `mem`: (base, offset, size).  None if some write is
/// at a non-constant offset of an object not listed in `full`.
fn extents(ctx: &mut Ctx, mem: &Mem, full: &HashSet<T>) -> Option<Vec<(T, i64, u32)>> {
    let mut out = Vec::new();
    let mut bases: Vec<&T> = mem.private.keys().collect();
    bases.sort_unstable();
    for &base in bases {
        if full.contains(&base) {
            continue;
        }
        for e in &mem.private[&base] {
            let d = ctx.tm.const_diff(e.addr, base)?;
            out.push((base, d as u32 as i32 as i64, e.size as u32));
        }
    }
    Some(out)
}

fn same_log(a: &[Write], b: &[Write]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|(x, y)| {
            x.addr == y.addr && x.size == y.size && x.val == y.val && x.guard == y.guard && x.havoc == y.havoc
        })
}

/// A candidate pairing of a source cut block with a machine address.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Pair {
    block: usize,
    pc: u32,
    lead: usize,
    ratio: usize,
}

struct Explored {
    c: Vec<CutSnap>,
    m: Vec<MachSnap>,
    /// Targets of the machine code's backward jumps.
    back: Vec<u32>,
    /// What held on the explored path (path condition and assumptions), to compare the values
    /// seen along it.
    known: Vec<T>,
    /// Where the binary kept the locals external code could reach on that path.
    bound: Vec<(T, i64, u32)>,
    /// Equalities between values of that path already put to the prover.
    asked: std::cell::RefCell<HashMap<(T, T), bool>>,
}

/// One complete path of the function on which the loops iterate, with the state of both sides
/// at every arrival at a candidate cut point.
fn explore(
    ctx: &mut Ctx,
    job: &Job,
    pre: &[T],
    loops: &[CLoop],
    range: (u32, u32),
    depths: &[usize],
) -> Result<Explored, Failure> {
    let watch: Vec<usize> = loops.iter().flat_map(|l| l.cands.iter().copied()).collect();
    // (score, branch decisions, targets of backward jumps, block boundaries passed)
    #[allow(clippy::type_complexity)]
    let mut best: Option<(usize, Vec<bool>, Vec<u32>, Vec<u32>)> = None;
    'search: for &depth in depths {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        // Some path was cut short by the depth: a deeper search can find more.
        let mut deeper = false;
        for _ in 0..48 {
            ctx.restart(pre);
            let ctl = SegCtl {
                c_cuts: &watch,
                ..Default::default()
            };
            match run_seg(ctx, job, &ctl) {
                Ok(end) => {
                    let twice = loops
                        .iter()
                        .filter(|l| {
                            // (a loop whose head branches two ways inside the loop, as one
                            // made with `goto` does, need not pass the first of them)
                            let at = |b: usize| end.cx.cut_snaps.iter().filter(|s| s.block == b).count();
                            at(l.cands[0]) >= 2 || at(l.head) >= 3
                        })
                        .count();
                    let within = |a: &u32| *a >= range.0 && *a < range.1;
                    let targets: Vec<u32> = end.m.back_targets.iter().copied().filter(within).collect();
                    let leaders: Vec<u32> = end.m.leaders.iter().copied().filter(within).collect();
                    // Prefer a path on which the machine code looped too.
                    let score = twice * 2 + usize::from(!targets.is_empty());
                    if twice > 0 && best.as_ref().is_none_or(|b| score > b.0) {
                        let done = twice == loops.len() && !targets.is_empty();
                        best = Some((score, ctx.decisions[..ctx.pos].to_vec(), targets, leaders));
                        if done {
                            break 'search;
                        }
                    }
                }
                Err(Stop::Truncated(why)) if why != "branch depth limit" => {
                    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
                        eprintln!("explore: {why}");
                    }
                    return Err(Failure::new(
                        "budget",
                        format!("{why} while looking for a path through the loop"),
                        1,
                    ));
                }
                Err(e) => {
                    deeper |= matches!(&e, Stop::Truncated(_));
                    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
                        eprintln!("explore path: {e:?}");
                    }
                }
            }
            if !ctx.next_path() {
                if deeper {
                    break;
                }
                break 'search;
            }
        }
    }
    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
        eprintln!("explore: best {best:x?}");
    }
    let Some((_, decisions, back, mut targets)) = best else {
        return Err(Failure::new(
            "no-looping-path",
            "no explored path goes round a loop of the source twice",
            0,
        ));
    };
    if back.is_empty() {
        return Err(Failure::new(
            "no-looping-path",
            "the binary takes no backward jump where the source loops",
            0,
        ));
    }
    for &a in &back {
        if !targets.contains(&a) {
            targets.push(a);
        }
    }
    // Replay the same path, now watching the block boundaries the machine code passed.
    ctx.limits.max_depth = decisions.len();
    ctx.decisions = decisions;
    ctx.restart(pre);
    let ctl = SegCtl {
        c_cuts: &watch,
        m_cuts: &targets,
        ..Default::default()
    };
    let end = run_seg(ctx, job, &ctl).map_err(|e| {
        Failure::new(
            "unsupported-shape",
            format!("the looping path cannot be replayed: {e:?}"),
            1,
        )
    })?;
    let mut known = ctx.pc.clone();
    known.extend_from_slice(&ctx.ub);
    Ok(Explored {
        c: end.cx.cut_snaps,
        m: end.m.cut_snaps,
        back,
        known,
        bound: end.bound,
        asked: Default::default(),
    })
}

/// The start of a path on which the source arrives twice at the first block of loop `li`,
/// with the machine code followed until the first backward jump it takes after the source's
/// calls of that stretch.  Unlike `explore` this needs no path through the whole function,
/// which a function with a large loop body (an interpreter's dispatch loop) does not yield
/// within any budget: the path stops as soon as the loop has gone round once.  Like `explore`
/// it proves nothing; what it shows are places to cut and facts to try there.
fn explore_prefix(
    ctx: &mut Ctx,
    job: &Job,
    pre: &[T],
    loops: &[CLoop],
    li: usize,
    range: (u32, u32),
) -> Option<Explored> {
    let watch: Vec<usize> = loops.iter().flat_map(|l| l.cands.iter().copied()).collect();
    let target = loops[li].cands[0];
    let within = |a: &u32| *a >= range.0 && *a < range.1;
    let mut found: Option<(Vec<bool>, Vec<u32>, Vec<u32>)> = None;
    'search: for depth in [4usize, 8, 14, 24] {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        let mut deeper = false;
        for _ in 0..40 {
            ctx.restart(pre);
            let ctl = SegCtl {
                c_cuts: &watch,
                stop: 2,
                prefix: Some(target),
                ..Default::default()
            };
            match run_seg(ctx, job, &ctl) {
                Ok(end) if end.cut.is_some() => {
                    let back: Vec<u32> = end.m.back_targets.iter().copied().filter(within).collect();
                    let leaders: Vec<u32> = end.m.leaders.iter().copied().filter(within).collect();
                    if !back.is_empty() {
                        found = Some((ctx.decisions[..ctx.pos].to_vec(), back, leaders));
                        break 'search;
                    }
                }
                Ok(_) => {}
                Err(Stop::Truncated(why)) if why != "branch depth limit" => return None,
                Err(e) => deeper |= matches!(&e, Stop::Truncated(_)),
            }
            if !ctx.next_path() {
                if deeper {
                    break;
                }
                break 'search;
            }
        }
    }
    let (decisions, back, mut targets) = found?;
    for &a in &back {
        if !targets.contains(&a) {
            targets.push(a);
        }
    }
    ctx.limits.max_depth = decisions.len();
    ctx.decisions = decisions;
    ctx.restart(pre);
    let ctl = SegCtl {
        c_cuts: &watch,
        m_cuts: &targets,
        stop: 2,
        prefix: Some(target),
        ..Default::default()
    };
    let end = run_seg(ctx, job, &ctl).ok()?;
    let mut known = ctx.pc.clone();
    known.extend_from_slice(&ctx.ub);
    Some(Explored {
        c: end.cx.cut_snaps,
        m: end.m.cut_snaps,
        back,
        known,
        bound: end.bound,
        asked: Default::default(),
    })
}

/// One cut point per loop of the source, each from its own path prefix (`explore_prefix`):
/// the first block of the loop with the address the machine code jumped back to.  A loop no
/// prefix reaches twice gets none and has to be unrolled by the paths of the proof.
fn prefix_plan(
    ctx: &mut Ctx,
    job: &Job,
    pre: &[T],
    loops: &[CLoop],
    range: (u32, u32),
    debug: bool,
) -> Option<Vec<Cut>> {
    let mut cuts: Vec<Cut> = Vec::new();
    for li in 0..loops.len() {
        ctx.check_deadline().ok()?;
        let Some(ex) = explore_prefix(ctx, job, pre, loops, li, range) else {
            if debug {
                eprintln!("no path prefix goes round loop {li}");
            }
            continue;
        };
        let block = loops[li].cands[0];
        let c_ev: Vec<u32> = ex.c.iter().filter(|s| s.block == block).map(|s| s.nev).collect();
        // The address the path ended at, reached with the same calls made as the source.
        let Some(last) = ex.m.last() else { continue };
        let pc = last.pc;
        if cuts.iter().any(|c| c.m_pc == pc || c.c_block == block) {
            continue;
        }
        let m_ev: Vec<u32> = ex.m.iter().filter(|s| s.pc == pc).map(|s| s.nev).collect();
        let Some(lead) =
            (1..=2usize).find(|&lead| c_ev.len() >= lead && c_ev[lead - 1..].iter().zip(&m_ev).all(|(a, b)| a == b))
        else {
            continue;
        };
        let pair = Pair {
            block,
            pc,
            lead,
            ratio: 1,
        };
        if debug {
            eprintln!("path prefix: loop {li} cut at block {block}, {pc:#x}, lead {lead}");
        }
        if let Some(cut) = build_cut(ctx, job, &ex, cuts.len(), pair) {
            cuts.push(cut);
        }
    }
    (!cuts.is_empty()).then_some(cuts)
}

/// Candidates `t = a * c_j + s * c_k + d` for a 32-bit value `t` that changed by `dt` between
/// the two arrivals seen, over the first `n` source locations (values at the first arrival
/// and their change; None where the change is not a constant).
fn two_term(ctx: &mut Ctx, t: T, dt: i64, cv: &[T], dc: &[Option<i64>], n: usize) -> Vec<Cand> {
    let mut out = Vec::new();
    let mut tried = 0;
    for j in 0..n {
        let Some(dj) = dc[j].filter(|&d| d != 0) else { continue };
        for k in 0..n {
            let Some(dk) = dc[k] else { continue };
            if k == j || ctx.tm.as_const(cv[k]).is_some() {
                continue;
            }
            for neg in [false, true] {
                // (a fixed base added is the one-variable form with a base)
                if dk == 0 && !neg {
                    continue;
                }
                let rest = dt - if neg { -dk } else { dk };
                if rest == 0 || rest % dj != 0 || !(-16..=16).contains(&(rest / dj)) || tried >= 48 {
                    continue;
                }
                tried += 1;
                let a = (rest / dj) as u64 & 0xffff_ffff;
                let scaled = ctx.tm.scale(cv[j], a);
                let part = if neg {
                    ctx.tm.sub(scaled, cv[k])
                } else {
                    ctx.tm.add(scaled, cv[k])
                };
                let rest = ctx.tm.sub(t, part);
                if let Some(d) = ctx.tm.as_const(rest) {
                    out.push(Cand::Two(j, a, k, neg, None, d));
                } else if let Some((x, d)) = (0..n).find_map(|x| {
                    let fixed = x != j && x != k && dc[x] == Some(0) && ctx.tm.as_const(cv[x]).is_none();
                    let d = if fixed { ctx.tm.const_diff(rest, cv[x]) } else { None };
                    d.map(|d| (x, d))
                }) {
                    out.push(Cand::Two(j, a, k, neg, Some(x), d));
                }
            }
        }
    }
    out.truncate(3);
    out
}

/// Cover the binary's cells of an exposed local with locations that hold the object's bytes.
fn expose(m_locs: &mut Vec<Loc>, m_cover: &mut Cover, sp0: T, e: &ExposedLocal) {
    m_cover.add(m_locs, sp0, e.at, e.size);
    for l in m_locs.iter_mut() {
        if let Place::Mem { base, off, size } = l.place
            && base == sp0
            && off >= e.at
            && off + size as i64 <= e.at + e.size as i64
        {
            l.cands = vec![Cand::Obj(e.base, off - e.at)];
            l.active = 0;
        }
    }
}

/// Build the cut point (block, address) with the facts suggested by the explored path.
fn build_cut(ctx: &mut Ctx, job: &Job, ex: &Explored, id: usize, plan: Pair) -> Option<Cut> {
    let p = job.prog;
    let f = &p.funcs[job.fid as usize];
    let (c_block, m_pc) = (plan.block, plan.pc);
    let all: Vec<&CutSnap> = ex.c.iter().filter(|s| s.block == c_block).collect();
    let cs: Vec<&CutSnap> = [plan.lead - 1, plan.lead - 1 + plan.ratio]
        .into_iter()
        .filter_map(|i| all.get(i).copied())
        .collect();
    let ms: Vec<&MachSnap> = ex.m.iter().filter(|s| s.pc == m_pc).take(2).collect();
    let (c1, m1) = (*cs.first()?, *ms.first()?);
    let second = match (cs.get(1), ms.get(1)) {
        (Some(c), Some(m)) => Some((*c, *m)),
        _ => None,
    };
    // Source locations: every local of the function, the objects of structure arguments, and
    // whatever else is private and written.
    let mut c_locs = Vec::new();
    let mut c_cover = Cover::default();
    let mut c_full = HashSet::new();
    for (i, l) in f.locals.iter().enumerate() {
        let base = ctx.private_base(&format!("&{}.{}#{i}@1", f.name, l.name));
        let size = p.size_of(l.ty).unwrap_or(0);
        if size == 0 {
            continue;
        }
        if size > 256 {
            return None; // too large to track byte by byte
        }
        c_cover.add(&mut c_locs, base, 0, size);
        c_full.insert(base);
    }
    for (base, words) in &job.struct_args {
        c_cover.add(&mut c_locs, *base, 0, 4 * words.len() as u32);
        c_full.insert(*base);
    }
    let mut m_locs: Vec<Loc> = (0..15)
        .map(|r| Loc {
            place: Place::Reg(r),
            cands: Vec::new(),
            active: 0,
            refined: false,
        })
        .collect();
    let mut m_cover = Cover::default();
    let none = HashSet::new();
    for (c, m) in [Some((c1, m1)), second].into_iter().flatten() {
        for (base, off, size) in extents(ctx, &c.mem, &c_full)? {
            c_cover.add(&mut c_locs, base, off, size);
        }
        for (base, off, size) in extents(ctx, &m.mem, &none)? {
            m_cover.add(&mut m_locs, base, off, size);
        }
    }
    // Locals external code can reach at an arrival seen, with the binary's cells for them.
    let mut exposed: Vec<ExposedLocal> = Vec::new();
    for c in &all {
        for e in &c.mem.exposed {
            if exposed.iter().any(|x| x.base == e.base) {
                continue;
            }
            let (_, at, size) = *ex.bound.iter().find(|b| b.0 == e.base)?;
            let i = (0..f.locals.len())
                .find(|&i| ctx.private_base(&format!("&{}.{}#{i}@1", f.name, f.locals[i].name)) == e.base)?;
            if e.dyn_size.is_some() || !c_full.contains(&e.base) {
                return None;
            }
            exposed.push(ExposedLocal {
                base: e.base,
                at,
                size,
                align: p.align_of(f.locals[i].ty).clamp(1, 8),
                name: format!("&{}.{}#{i}@1", f.name, f.locals[i].name),
            });
        }
    }
    for e in &exposed {
        expose(&mut m_locs, &mut m_cover, job.regs[13], e);
    }
    // Values at the first and second arrival.
    let cv1: Vec<T> = c_locs.iter().map(|l| c_read(ctx, job, &c1.mem, l.place)).collect();
    let mv1: Vec<T> = m_locs
        .iter()
        .map(|l| m_read(ctx, job, &m1.regs, &m1.mem, l.place))
        .collect();
    let (cv2, mv2) = match second {
        Some((c2, m2)) => (
            Some(
                c_locs
                    .iter()
                    .map(|l| c_read(ctx, job, &c2.mem, l.place))
                    .collect::<Vec<T>>(),
            ),
            Some(
                m_locs
                    .iter()
                    .map(|l| m_read(ctx, job, &m2.regs, &m2.mem, l.place))
                    .collect::<Vec<T>>(),
            ),
        ),
        None => (None, None),
    };
    let exprs = std::rc::Rc::new(value_exprs(p, f.body.as_ref()?));
    let ev1: Vec<Option<T>> = exprs.iter().map(|e| value_of(ctx, job, &c1.mem, e)).collect();
    let ev2: Option<Vec<Option<T>>> =
        second.map(|(c2, _)| exprs.iter().map(|e| value_of(ctx, job, &c2.mem, e)).collect());
    // How much each 32-bit source location changed between the two arrivals, where that is a constant.
    let dc: Vec<Option<i64>> = (0..c_locs.len())
        .map(|i| {
            let c2 = cv2.as_ref()?;
            if ctx.tm.width(cv1[i]) != 32 {
                return None;
            }
            ctx.tm.const_diff(c2[i], cv1[i]).map(|d| crate::term::sext64(d, 32))
        })
        .collect();
    for i in 0..c_locs.len() {
        if cv2.as_ref().is_none_or(|v| v[i] == cv1[i]) {
            c_locs[i].cands.push(Cand::Inv(cv1[i]));
            continue;
        }
        // Moving in step with an earlier source variable: c_i = a * c_j + b.
        let Some(c2) = &cv2 else { continue };
        let w = c_locs[i].width();
        let Some(di) = ctx.tm.const_diff(c2[i], cv1[i]) else {
            continue;
        };
        for j in 0..i {
            if ctx.tm.width(cv1[j]) != w || c_locs[j].cands.iter().any(|c| matches!(c, Cand::Inv(_))) {
                continue;
            }
            let Some(dj) = ctx.tm.const_diff(c2[j], cv1[j]) else {
                continue;
            };
            let (di, dj) = (crate::term::sext64(di, w), crate::term::sext64(dj, w));
            if dj == 0 || di % dj != 0 {
                continue;
            }
            let a = (di / dj) as u64 & crate::term::mask(w);
            let scaled = ctx.tm.scale(cv1[j], a);
            let b = ctx.tm.sub(cv1[i], scaled);
            c_locs[i].cands.push(Cand::Lin(j, View::Same, a, b));
        }
        if w == 32 {
            let more = two_term(ctx, cv1[i], crate::term::sext64(di, 32), &cv1, &dc, i);
            c_locs[i].cands.extend(more);
        }
    }
    let mut asks = 0;
    for (i, l) in m_locs.iter_mut().enumerate() {
        let w = l.width();
        let steady = mv2.as_ref().is_none_or(|v| v[i] == mv1[i]);
        if matches!(l.cands.first(), Some(Cand::Obj(..))) {
            continue;
        }
        if steady {
            l.cands.push(Cand::Inv(mv1[i]));
        }
        // Equal to a source variable at every arrival seen.
        for (j, &c) in cv1.iter().enumerate() {
            for view in views(ctx.tm.width(c), w) {
                let Some(t1) = apply_view(ctx, c, view, w) else {
                    continue;
                };
                if t1 != mv1[i] {
                    continue;
                }
                let also = match (&cv2, &mv2) {
                    (Some(c2), Some(m2)) => match apply_view(ctx, c2[j], view, w) {
                        Some(t2) => same_on_path(ctx, ex, t2, m2[i]),
                        None => false,
                    },
                    _ => true,
                };
                if also {
                    l.cands.push(Cand::Rel(j, view));
                }
            }
        }
        // Equal to a source variable without being the same term: the two sides computed the
        // value in different ways (a minimum as a conditional move, say), or the path
        // explored makes two variables equal that are not on other paths.
        let kept = matches!(l.place, Place::Reg(4..=11) | Place::Mem { .. });
        if kept && ctx.tm.as_const(mv1[i]).is_none() && asks < 64 {
            for (j, &c) in cv1.iter().enumerate() {
                // (a constant in the source at the first arrival may be an input in the
                // binary that the path condition pins)
                if ctx.tm.width(c) != w
                    || ctx.mentions_uninit(c)
                    || l.cands.iter().any(|x| matches!(x, Cand::Rel(k, _) if *k == j))
                    || (ctx.tm.as_const(c).is_some()
                        && !matches!((&cv2, &mv2), (Some(c2), Some(m2)) if c2[j] == m2[i] && c2[j] != c))
                {
                    continue;
                }
                asks += 1;
                if !same_on_path(ctx, ex, c, mv1[i]) {
                    continue;
                }
                let also = match (&cv2, &mv2) {
                    (Some(c2), Some(m2)) => same_on_path(ctx, ex, c2[j], m2[i]),
                    _ => true,
                };
                if also {
                    l.cands.push(Cand::Rel(j, View::Same));
                }
            }
        }
        // Equal to the value of an expression of the source at every arrival seen.
        if matches!(l.place, Place::Reg(_)) || w == 32 {
            for (k, v1) in ev1.iter().enumerate() {
                let Some(v1) = *v1 else { continue };
                for view in views(ctx.tm.width(v1), w) {
                    if !matches!(view, View::Same | View::Zext | View::Sext) {
                        continue;
                    }
                    if apply_view(ctx, v1, view, w) != Some(mv1[i]) || ctx.tm.as_const(mv1[i]).is_some() {
                        continue;
                    }
                    let also = match (&ev2, &mv2) {
                        (Some(e2), Some(m2)) => match e2[k].and_then(|v| apply_view(ctx, v, view, w)) {
                            Some(t2) => same_on_path(ctx, ex, t2, m2[i]),
                            None => false,
                        },
                        _ => true,
                    };
                    if also && l.cands.iter().filter(|c| matches!(c, Cand::Val(..))).count() < 3 {
                        l.cands.push(Cand::Val(k, view));
                    }
                }
            }
        }
        // A combination of two source variables that move.
        if w == 32
            && let Some(m2) = &mv2
            && ctx.tm.as_const(mv1[i]).is_none()
            && let Some(dm) = ctx.tm.const_diff(m2[i], mv1[i])
        {
            let more = two_term(ctx, mv1[i], crate::term::sext64(dm, 32), &cv1, &dc, cv1.len());
            l.cands.extend(more);
        }
        // Moving in step with a source variable: m = a * c + b.
        if let (Some(c2), Some(m2), 32) = (&cv2, &mv2, w)
            && let Some(dm) = ctx.tm.const_diff(m2[i], mv1[i])
            && dm != 0
        {
            for (j, &c) in cv1.iter().enumerate() {
                let cw = ctx.tm.width(c);
                let Some(dc) = ctx.tm.const_diff(c2[j], c) else {
                    continue;
                };
                let view = match cw {
                    32 => View::Same,
                    8 | 16 => View::Zext,
                    _ => continue,
                };
                let (dm, dc) = (dm as u32 as i32 as i64, crate::term::sext64(dc, cw));
                if dc == 0 || dm % dc != 0 {
                    continue;
                }
                let a = (dm / dc) as u64 & 0xffff_ffff;
                let Some(v1) = apply_view(ctx, c, view, 32) else {
                    continue;
                };
                let scaled = ctx.tm.scale(v1, a);
                let b = ctx.tm.sub(mv1[i], scaled);
                if a == 1 && ctx.tm.as_const(b) == Some(0) {
                    continue; // already a plain equality
                }
                l.cands.push(Cand::Lin(j, view, a, b));
                // The same with the constant part read from the source's state, when it is
                // the value of a variable or of an expression there.
                if ctx.tm.as_const(b).is_some() {
                    continue;
                }
                let mut more = Vec::new();
                for (k, &ck) in cv1.iter().enumerate() {
                    if k != j
                        && ctx.tm.width(ck) == 32
                        && ctx.tm.as_const(ck).is_none()
                        && let Some(d) = ctx.tm.const_diff(b, ck)
                        && c2[k] == ck
                    {
                        more.push(Cand::Lin2(j, view, a, Base::Loc(k), d));
                    }
                }
                for (k, &ek) in ev1.iter().enumerate() {
                    if let Some(ek) = ek
                        && ctx.tm.width(ek) == 32
                        && ctx.tm.as_const(ek).is_none()
                        && let Some(d) = ctx.tm.const_diff(b, ek)
                        && ev2.as_ref().is_some_and(|e| e[k] == Some(ek))
                    {
                        more.push(Cand::Lin2(j, view, a, Base::Expr(k), d));
                    }
                }
                if asks < 64 {
                    // (or not as terms: a bound computed another way than the source did,
                    // or equal to another variable on the path explored)
                    for (k, &ck) in cv1.iter().enumerate() {
                        if k == j
                            || more
                                .iter()
                                .any(|c| matches!(c, Cand::Lin2(_, _, _, Base::Loc(x), _) if *x == k))
                            || ctx.tm.width(ck) != 32
                            || ctx.tm.as_const(ck).is_some()
                            || c2[k] != ck
                            || ctx.mentions_uninit(ck)
                        {
                            continue;
                        }
                        asks += 1;
                        if same_on_path(ctx, ex, b, ck) {
                            more.push(Cand::Lin2(j, view, a, Base::Loc(k), 0));
                        }
                    }
                }
                more.truncate(4);
                l.cands.extend(more);
            }
        }
    }
    // The branch condition under which the cut block is entered.
    let mut pred = None;
    let mut pred_exprs = Vec::new();
    if let Some((b, taken)) = c1.last_br
        && cs.iter().all(|s| s.last_br == c1.last_br)
        && let Some(body) = &f.body
        && let Term::Br(e, ..) = &body.blocks[b].term
        && pure_conditions(p, e, taken, &mut pred_exprs)
    {
        pred = Some((b, taken));
    } else {
        pred_exprs.clear();
    }
    let world_same = second.is_none_or(|(c2, m2)| {
        same_log(&c1.mem.world, &c2.mem.world)
            && same_log(&m1.mem.world, &m2.mem.world)
            && c1.mem.epoch == c2.mem.epoch
            && m1.mem.epoch == m2.mem.epoch
    });
    Some(Cut {
        id,
        c_block,
        m_pc,
        lead: plan.lead,
        ratio: plan.ratio,
        c_locs,
        m_locs,
        c_full,
        exposed,
        stale: 0,
        pred,
        pred_exprs,
        exprs,
        facts: simple_facts(p, job.fid, f.body.as_ref()?),
        fail_facts: BTreeSet::new(),
        assumed: Vec::new(),
        world_same,
        c_world: c1.mem.world.clone(),
        c_epoch: c1.mem.epoch,
        m_world: m1.mem.world.clone(),
        m_epoch: m1.mem.epoch,
        fail_c: BTreeSet::new(),
        fail_m: BTreeSet::new(),
        fail_pred: false,
        fail_world: false,
        grew: false,
    })
}

/// Are the two values equal on the explored path?  Only a hint for choosing candidates.
fn same_on_path(ctx: &mut Ctx, ex: &Explored, a: T, b: T) -> bool {
    if a == b {
        return true;
    }
    if ctx.tm.width(a) != ctx.tm.width(b) || ctx.check_deadline().is_err() {
        return false;
    }
    if let Some(&r) = ex.asked.borrow().get(&(a, b)) {
        return r;
    }
    let e = ctx.tm.eq(a, b);
    let r = matches!(ctx.prover.prove(&mut ctx.tm, &ex.known, e), crate::bv::Verdict::Proved);
    ex.asked.borrow_mut().insert((a, b), r);
    r
}

/// The values, in the state `mem` of the source, of the expressions the facts in force refer to.
fn expr_values(ctx: &mut Ctx, job: &Job, cut: &Cut, mem: &Mem) -> Vec<Option<T>> {
    let mut used = vec![false; cut.exprs.len()];
    for l in &cut.m_locs {
        for cand in &l.cands {
            if let Cand::Val(k, _) | Cand::Lin2(_, _, _, Base::Expr(k), _) = cand {
                used[*k] = true;
            }
        }
    }
    (0..cut.exprs.len())
        .map(|k| {
            if used[k] {
                value_of(ctx, job, mem, &cut.exprs[k])
            } else {
                None
            }
        })
        .collect()
}

fn expected(ctx: &mut Ctx, cand: &Cand, cvals: &[T], evals: &[Option<T>], w: u8) -> Option<T> {
    match cand {
        Cand::Inv(v) => Some(*v),
        Cand::Obj(..) => None,
        Cand::Val(k, view) => apply_view(ctx, (*evals.get(*k)?)?, *view, w),
        Cand::Rel(j, view) => apply_view(ctx, cvals[*j], *view, w),
        Cand::Lin(j, view, a, b) => {
            let v = apply_view(ctx, cvals[*j], *view, w)?;
            let s = ctx.tm.scale(v, *a);
            Some(ctx.tm.add(s, *b))
        }
        Cand::Two(j, a, k, neg, x, d) => {
            if w != 32 || ctx.tm.width(cvals[*j]) != 32 || ctx.tm.width(cvals[*k]) != 32 {
                return None;
            }
            let s = ctx.tm.scale(cvals[*j], *a);
            let mut t = if *neg {
                ctx.tm.sub(s, cvals[*k])
            } else {
                ctx.tm.add(s, cvals[*k])
            };
            if let Some(x) = x {
                if ctx.tm.width(cvals[*x]) != 32 {
                    return None;
                }
                t = ctx.tm.add(t, cvals[*x]);
            }
            Some(ctx.tm.add_const(t, *d))
        }
        Cand::Lin2(j, view, a, base, d) => {
            let v = apply_view(ctx, cvals[*j], *view, w)?;
            let s = ctx.tm.scale(v, *a);
            let b = match base {
                Base::Loc(k) => cvals[*k],
                Base::Expr(k) => (*evals.get(*k)?)?,
            };
            if ctx.tm.width(b) != w {
                return None;
            }
            let t = ctx.tm.add(s, b);
            Some(ctx.tm.add_const(t, *d))
        }
    }
}

fn holds(ctx: &mut Ctx, a: T, b: T) -> bool {
    if a == b {
        return true;
    }
    let e = ctx.tm.eq(a, b);
    ctx.implied(e)
}

/// Both sides arrived at the cut point: check every fact of the relation in the state reached.
fn arrive(ctx: &mut Ctx, job: &Job, cut: &mut Cut, end: &mut SegEnd) -> R<()> {
    if end.bound_dynamic {
        return Err(fail(
            "an object of dynamic size is visible to external code at the loop head",
        ));
    }
    for (base, dynamic) in end.cx.escaped_objects() {
        let place = end.bound.iter().find(|b| b.0 == base);
        if let Some(e) = cut.exposed.iter().find(|e| e.base == base) {
            // The step assumes the object where the relation says it is.
            if place.is_some_and(|b| b.1 != e.at) {
                return Err(fail(
                    "a local object visible to external code is at another place in the frame",
                ));
            }
            continue;
        }
        // One more object to carry across the cut point, if it is the function's own local
        // at a fixed place of the frame.
        let (Some(&(_, at, size)), None, true) = (place, dynamic, cut.c_full.contains(&base)) else {
            return Err(fail("a local object is visible to external code at the loop head"));
        };
        let Some((_, align, name)) = end.cx.object(base) else {
            return Err(fail("a local object is visible to external code at the loop head"));
        };
        let e = ExposedLocal {
            base,
            at,
            size,
            align,
            name,
        };
        let mut m_cover = Cover::default();
        for l in &cut.m_locs {
            if let Place::Mem { base, off, size } = l.place {
                m_cover.0.entry(base).or_default().extend(off..off + size as i64);
            }
        }
        expose(&mut cut.m_locs, &mut m_cover, job.regs[13], &e);
        cut.exposed.push(e);
        cut.grew = true;
    }
    // Private memory written anywhere must be a location, so that the step starts from a
    // state in which it is unknown.
    let Some(c_ext) = extents(ctx, &end.cx.mem, &cut.c_full) else {
        return Err(fail("the source writes a local object at a computed offset"));
    };
    let Some(m_ext) = extents(ctx, &end.m.mem, &HashSet::new()) else {
        return Err(fail("the binary writes its stack frame at a computed offset"));
    };
    let mut c_cover = Cover::default();
    let mut m_cover = Cover::default();
    for l in &cut.c_locs {
        if let Place::Mem { base, off, size } = l.place {
            c_cover.0.entry(base).or_default().extend(off..off + size as i64);
        }
    }
    for l in &cut.m_locs {
        if let Place::Mem { base, off, size } = l.place {
            m_cover.0.entry(base).or_default().extend(off..off + size as i64);
        }
    }
    for (base, off, size) in c_ext {
        cut.grew |= c_cover.add(&mut cut.c_locs, base, off, size);
    }
    for (base, off, size) in m_ext {
        cut.grew |= m_cover.add(&mut cut.m_locs, base, off, size);
    }
    if cut.grew {
        return Ok(());
    }
    let cvals: Vec<T> = cut
        .c_locs
        .iter()
        .map(|l| c_read(ctx, job, &end.cx.mem, l.place))
        .collect();
    let evals = expr_values(ctx, job, cut, &end.cx.mem);
    // Locations thought constant that moved by a constant instead: (location, old value, change).
    let mut c_moved: Vec<(usize, T, i64)> = Vec::new();
    let mut m_moved: Vec<(usize, T, i64)> = Vec::new();
    for (i, l) in cut.c_locs.iter().enumerate() {
        // Every candidate still standing is part of the relation (see `start_state`).
        for (n, cand) in l.cands.iter().enumerate() {
            let ok = match expected(ctx, cand, &cvals, &evals, l.width()) {
                Some(want) => holds(ctx, cvals[i], want),
                None => false,
            };
            if !ok {
                cut.fail_c.insert((i, n));
                if let Cand::Inv(v) = cand
                    && let Some(d) = ctx.tm.const_diff(cvals[i], *v)
                    && d != 0
                {
                    c_moved.push((i, *v, crate::term::sext64(d, l.width())));
                }
            }
        }
        match l.cands.first() {
            Some(_) => {}
            None => {
                if may_point_private(ctx, cvals[i]) {
                    return Err(fail(
                        "a pointer to a local object changes in the loop in a way that is not understood",
                    ));
                }
            }
        }
    }
    for i in 0..cut.m_locs.len() {
        let l = &cut.m_locs[i];
        let got = m_read(ctx, job, &end.m.regs, &end.m.mem, l.place);
        for (n, cand) in l.cands.iter().enumerate() {
            if let &Cand::Obj(base, off) = cand {
                let Place::Mem { size, .. } = l.place else {
                    unreachable!("a cell of the frame")
                };
                let want = c_read(ctx, job, &end.cx.mem, Place::Mem { base, off, size });
                if !ctx.mentions_uninit(want) && !holds(ctx, got, want) {
                    cut.fail_m.insert((i, n));
                }
                continue;
            }
            let ok = match expected(ctx, cand, &cvals, &evals, l.width()) {
                Some(want) => holds(ctx, got, want),
                None => false,
            };
            if !ok {
                if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() && !cut.fail_m.contains(&(i, n)) {
                    let want = expected(ctx, cand, &cvals, &evals, l.width());
                    eprintln!(
                        "    machine {i}.{n} refuted: holds {} wanted {:?}",
                        ctx.tm.show(got),
                        want.map(|w| ctx.tm.show(w))
                    );
                }
                cut.fail_m.insert((i, n));
                if let Cand::Inv(v) = cand
                    && l.width() == 32
                    && let Some(d) = ctx.tm.const_diff(got, *v)
                    && d != 0
                {
                    m_moved.push((i, *v, d as u32 as i32 as i64));
                }
            }
        }
        match l.cands.first() {
            Some(_) => {}
            None => {
                if may_point_private(ctx, got) {
                    // A stack address left in a register is harmless as long as the code
                    // overwrites the register before it or a callee reads it: the step is
                    // checked for that.
                    match l.place {
                        Place::Reg(r @ (0..=12 | 14)) => {
                            if cut.stale >> r & 1 == 0 {
                                cut.stale |= 1 << r;
                                cut.grew = true;
                            }
                        }
                        _ => {
                            return Err(fail(
                                "a stack address changes in the loop in a way that is not understood",
                            ));
                        }
                    }
                }
            }
        }
    }
    // A location that moves in step with a source variable is a linear function of it.
    for &(i, v, d) in &m_moved {
        if cut.m_locs[i].refined {
            continue;
        }
        cut.m_locs[i].refined = true;
        for &(j, cv, dc) in &c_moved {
            let view = match cut.c_locs[j].width() {
                32 => View::Same,
                8 | 16 => View::Zext,
                _ => continue,
            };
            if d % dc != 0 {
                continue;
            }
            let a = (d / dc) as u64 & 0xffff_ffff;
            let Some(c32) = apply_view(ctx, cv, view, 32) else {
                continue;
            };
            let scaled = ctx.tm.scale(c32, a);
            let b = ctx.tm.sub(v, scaled);
            cut.m_locs[i].cands.push(Cand::Lin(j, view, a, b));
        }
    }
    for &(i, v, d) in &c_moved {
        if cut.c_locs[i].refined {
            continue;
        }
        cut.c_locs[i].refined = true;
        let w = cut.c_locs[i].width();
        for &(j, cv, dc) in &c_moved {
            if j >= i || cut.c_locs[j].width() != w || d % dc != 0 {
                continue;
            }
            let a = (d / dc) as u64 & crate::term::mask(w);
            let scaled = ctx.tm.scale(cv, a);
            let b = ctx.tm.sub(v, scaled);
            cut.c_locs[i].cands.push(Cand::Lin(j, View::Same, a, b));
        }
    }
    for (k, (e, want)) in cut.facts.iter().enumerate() {
        let (npc, nub) = (ctx.pc.len(), ctx.ub.len());
        let v = end.cx.eval(ctx, e);
        let clean = ctx.pc.len() == npc && ctx.ub.len() == nub;
        ctx.pc.truncate(npc);
        ctx.ub.truncate(nub);
        let ok = match v {
            Ok(v) if clean => {
                let nz = ctx.tm.nonzero(v);
                let c = if *want { nz } else { ctx.tm.not(nz) };
                ctx.tm.is_true(c) || ctx.implied(c)
            }
            _ => false,
        };
        if !ok {
            if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() && !cut.fail_facts.contains(&k) && k < 2 {
                eprintln!(
                    "    fact {k} refuted: {:?} clean {clean}",
                    v.as_ref().map(|v| ctx.tm.show(*v))
                );
            }
            cut.fail_facts.insert(k);
        }
    }
    if cut.pred.is_some() && end.cx.last_br != cut.pred {
        cut.fail_pred = true;
    }
    if cut.world_same {
        let same = same_log(&end.cx.mem.world, &cut.c_world)
            && same_log(&end.m.mem.world, &cut.m_world)
            && end.cx.mem.epoch == cut.c_epoch
            && end.m.mem.epoch == cut.m_epoch;
        if !same {
            cut.fail_world = true;
        }
    } else {
        compare_world(
            ctx,
            job,
            &end.cx.mem.world,
            end.cx.mem.epoch,
            &end.cx.mem.exposed,
            &end.m,
            "memory at a loop head",
            &mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
        )?;
    }
    Ok(())
}

/// An arbitrary state satisfying the relation of `cut`.
fn start_state(ctx: &mut Ctx, job: &Job, cut: &Cut) -> Option<SegInit> {
    let tag = format!("hv{}", cut.id);
    let fresh_epoch = 0x4000_0000 + ((cut.id as u32) << 16);
    let mut c_mem = Mem::default();
    let mut m_mem = Mem::default();
    if cut.world_same {
        c_mem.world = cut.c_world.clone();
        c_mem.epoch = cut.c_epoch;
        m_mem.world = cut.m_world.clone();
        m_mem.epoch = cut.m_epoch;
    } else {
        c_mem.epoch = fresh_epoch;
        m_mem.epoch = fresh_epoch;
    }
    // With locals visible to external code, an unknown value may be the address of one.
    let open = !cut.exposed.is_empty();
    for e in &cut.exposed {
        c_mem.exposed.push(Exposed {
            base: e.base,
            size: e.size,
            dyn_size: None,
            since: 0,
        });
    }
    // A location with several candidates standing starts with the value the first gives it
    // and the others are assumed of that value: the start state satisfies them all, as the
    // arrivals are required to.  (Trying them one after the other instead would start the
    // step from states an untested guess allows, and a wrong guess there refutes right ones
    // elsewhere.  With all of them in force together, every state the step starts from
    // satisfies whatever subset is truly inductive, so what a round refutes is rightly gone.)
    let mut also: Vec<T> = Vec::new();
    let mut cvals = Vec::with_capacity(cut.c_locs.len());
    for (i, l) in cut.c_locs.iter().enumerate() {
        let Place::Mem { base, off, size } = l.place else {
            unreachable!()
        };
        let v = match l.cands.first() {
            Some(cand) => {
                let v = expected(ctx, cand, &cvals, &[], size * 8)?;
                for other in &l.cands[1..] {
                    if let Some(w) = expected(ctx, other, &cvals, &[], size * 8) {
                        also.push(ctx.tm.eq(v, w));
                    }
                }
                v
            }
            None => {
                let v = ctx.named_sym(&format!("{tag}.c{i}.{}", size * 8), size * 8);
                if open {
                    ctx.mark_young(v);
                }
                v
            }
        };
        let a = ctx.tm.add_const(base, off as u64);
        ctx.mem_write(&mut c_mem, a, size, v);
        cvals.push(v);
    }
    let evals = expr_values(ctx, job, cut, &c_mem);
    let mut regs = [ctx.tm.konst(32, 0); 16];
    for (i, l) in cut.m_locs.iter().enumerate() {
        let w = l.width();
        let v = match l.cands.first() {
            Some(&Cand::Obj(base, off)) => {
                let Place::Mem { size, .. } = l.place else {
                    unreachable!("a cell of the frame")
                };
                c_read(ctx, job, &c_mem, Place::Mem { base, off, size })
            }
            Some(cand) => {
                let v = expected(ctx, cand, &cvals, &evals, w)?;
                for other in &l.cands[1..] {
                    if let Some(x) = expected(ctx, other, &cvals, &evals, w) {
                        also.push(ctx.tm.eq(v, x));
                    }
                }
                v
            }
            None => {
                let v = ctx.named_sym(&format!("{tag}.m{i}.{w}"), w);
                if open {
                    ctx.mark_young(v);
                }
                v
            }
        };
        match l.place {
            Place::Reg(r) => regs[r as usize] = v,
            Place::Mem { base, off, size } => {
                let a = ctx.tm.add_const(base, off as u64);
                ctx.mem_write(&mut m_mem, a, size, v);
            }
        }
    }
    Some(SegInit {
        c_block: cut.c_block,
        c_mem,
        m_pc: cut.m_pc,
        m_regs: regs,
        m_mem,
        also,
        tag,
        exposed: cut.exposed.clone(),
    })
}

/// Try to prove the function with the given cut points.  Err: the attempt failed.
fn attempt(ctx: &mut Ctx, job: &Job, pre: &[T], cuts: &mut [Cut], depth: usize) -> Result<Proof, Failure> {
    let mut step = false;
    let r = attempt_in(ctx, job, pre, cuts, depth, &mut step);
    r.map_err(|e| Failure::of(&e, step, cuts))
}

fn attempt_in(ctx: &mut Ctx, job: &Job, pre: &[T], cuts: &mut [Cut], depth: usize, step: &mut bool) -> R<Proof> {
    let blocks: Vec<usize> = cuts.iter().map(|c| c.c_block).collect();
    let pcs: Vec<u32> = cuts.iter().map(|c| c.m_pc).collect();
    ctx.limits.max_depth = depth;
    for _round in 0..60 {
        let mut proof = Proof {
            object_size: cuts.iter().any(|c| !c.assumed.is_empty()),
            ..Proof::default()
        };
        // A path of the step that fails outright while the relation is still being weakened:
        // it started from a state some wrong guess allowed (a register taken for a variable
        // that the one path explored did not change, as most arms of a dispatch loop leave
        // most variables alone).  The failure counts only if the round refutes nothing.
        let mut pending: Option<Stop> = None;
        for start in std::iter::once(None).chain((0..cuts.len()).map(Some)) {
            ctx.seg = start.map_or(0, |j| j as u32 + 1);
            *step = start.is_some();
            let init = match start {
                Some(j) => Some(start_state(ctx, job, &cuts[j]).ok_or_else(|| fail("no start state"))?),
                None => None,
            };
            let mut exprs: Vec<(Expr, bool)> = Vec::new();
            if let Some(j) = start {
                // Once the base case has refuted something, the step would start from a
                // relation already known to be wrong.
                if cuts.iter().any(|c| c.refuted()) {
                    break;
                }
                if cuts[j].pred.is_some() {
                    exprs.extend(cuts[j].pred_exprs.iter().cloned());
                }
                exprs.extend(cuts[j].facts.iter().cloned());
                exprs.extend(cuts[j].assumed.iter().cloned());
            }
            ctx.decisions.clear();
            let mut n = 0;
            loop {
                ctx.restart(pre);
                let ctl = SegCtl {
                    init: init.as_ref(),
                    assume: exprs.iter().map(|(e, w)| (e, *w)).collect(),
                    c_cuts: &blocks,
                    m_cuts: &pcs,
                    stop: match start {
                        None => cuts[0].lead,
                        Some(j) => cuts[j].ratio,
                    },
                    m_stop: 1,
                    prefix: None,
                };
                match run_seg(ctx, job, &ctl) {
                    Ok(mut end) => {
                        if let Some(j) = start
                            && end.m.first_reads.get() & cuts[j].stale != 0
                        {
                            return Err(fail(
                                "a stack address changes in the loop in a way that is not understood",
                            ));
                        }
                        if let Some((b, pc)) = end.cut {
                            let j = blocks.iter().position(|&x| x == b).expect("a cut block");
                            if cuts[j].m_pc != pc {
                                return Err(fail("the two sides arrive at different loops"));
                            }
                            match arrive(ctx, job, &mut cuts[j], &mut end) {
                                Err(e @ (Stop::Mismatch(..) | Stop::Inconclusive(_))) if start.is_some() => {
                                    pending.get_or_insert(e);
                                }
                                r => r?,
                            }
                        }
                        proof.paths += 1;
                        proof.cov.extend(end.res.cov);
                        proof.bytes.extend(end.res.insns);
                        proof.bytes.extend(end.res.data);
                    }
                    Err(Stop::Undefined) => {}
                    Err(e @ (Stop::Mismatch(..) | Stop::Inconclusive(_) | Stop::Unsupported(_))) if start.is_some() => {
                        pending.get_or_insert(e);
                    }
                    Err(e) => return Err(e),
                }
                n += 1;
                if n > 400 {
                    return Err(Stop::Truncated("too many paths through a loop body".into()));
                }
                if !ctx.next_path() {
                    break;
                }
            }
        }
        // Drop what was refuted; done when nothing was.
        let mut changed = false;
        if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
            for cut in cuts.iter() {
                eprintln!(
                    "  round {_round} cut ({}, {:#x}): refuted source {:?} machine {:?} facts {:?} pred {} world {} grew {}",
                    cut.c_block,
                    cut.m_pc,
                    cut.fail_c,
                    cut.fail_m,
                    cut.fail_facts,
                    cut.fail_pred,
                    cut.fail_world,
                    cut.grew
                );
            }
        }
        for cut in cuts.iter_mut() {
            // (highest index first, so that the others keep their places)
            for (i, n) in std::mem::take(&mut cut.fail_c).into_iter().rev() {
                cut.c_locs[i].cands.remove(n);
                changed = true;
            }
            for (i, n) in std::mem::take(&mut cut.fail_m).into_iter().rev() {
                cut.m_locs[i].cands.remove(n);
                changed = true;
            }
            let dead = std::mem::take(&mut cut.fail_facts);
            if !dead.is_empty() {
                let mut k = 0;
                cut.facts.retain(|_| {
                    k += 1;
                    !dead.contains(&(k - 1))
                });
                changed = true;
            }
            if std::mem::take(&mut cut.fail_pred) {
                cut.pred = None;
                changed = true;
            }
            if std::mem::take(&mut cut.fail_world) {
                cut.world_same = false;
                changed = true;
            }
            changed |= std::mem::take(&mut cut.grew);
        }
        if !changed {
            return match pending {
                Some(e) => Err(e),
                None => Ok(proof),
            };
        }
    }
    Err(Stop::Truncated("the loop relation did not stabilise".into()))
}

/// What the size limit of objects says about a counted loop, as a condition on the source's
/// state that holds at every point of the loop in an execution without undefined behaviour.
///
/// The loop must be `while (i < n) { ... }` with `i` and `n` unsigned 32-bit locals, not volatile, whose
/// address is never taken, a body that is a straight line of blocks without calls, in which
/// `n` is not assigned, `i` is incremented by one exactly once, and some `p + i` with elements
/// of `size` bytes is computed on every iteration.  Then, from any point of the loop where
/// `i < n`, nothing can stop the loop before the iteration with `i == n - 1` has run (or it
/// is running), and that iteration computes a pointer `(n - 1) * size` bytes or more into an
/// object.  No object is larger than `PTRDIFF_MAX` bytes, so `(n - 1) * size < 2^31` or the
/// behaviour is undefined: `i >= n || n <= (2^31 - 1) / size + 1`.  Compilers rely on this
/// when they replace the test `i < n` by a comparison of a walking pointer with an end
/// pointer, which is the same test only if `n * size` does not wrap.
fn size_assumption(p: &Program, body: &Body, l: &CLoop) -> Option<(Expr, bool)> {
    use crate::c::ast::OpKind;
    let Term::Br(cond, t, e) = &body.blocks[l.head].term else {
        return None;
    };
    if !l.inside.contains(t) || l.inside.contains(e) {
        return None;
    }
    let EK::Bin(BinOp::Lt, a, b) = &cond.kind else {
        return None;
    };
    let local = |x: &Expr| match &x.kind {
        EK::Load(v) => match v.kind {
            EK::Local(i) if p.bits(x.ty) == 32 && !p.is_signed(x.ty) && !p.is_volatile(x.ty) => Some(i),
            _ => None,
        },
        _ => None,
    };
    let (i, n) = (local(a)?, local(b)?);
    // Everything evaluated in the loop, and what the rest of the function does with `i` and `n`.
    struct Seen {
        i: u32,
        n: u32,
        bad: bool,
        steps: usize,
        size: Option<u32>,
    }
    fn walk(p: &Program, e: &Expr, always: bool, in_loop: bool, s: &mut Seen) {
        let is = |x: &Expr, v: u32| matches!(x.kind, EK::Local(w) if w == v);
        match &e.kind {
            EK::Addr(x) if is(x, s.i) || is(x, s.n) => s.bad = true,
            _ if !in_loop => {}
            EK::Call(..) | EK::Asm(..) | EK::VaArg(..) | EK::VaStart(..) | EK::Alloca(..) | EK::Compound { .. } => {
                s.bad = true
            }
            EK::Assign(x, _) if is(x, s.i) || is(x, s.n) => s.bad = true,
            EK::AssignOp(x, v, _) if is(x, s.n) || (is(x, s.i) && !always) => {
                let _ = v;
                s.bad = true
            }
            EK::AssignOp(x, v, _) if is(x, s.i) => match &v.kind {
                EK::Bin(BinOp::Add, a, b) if matches!(a.kind, EK::Prev) => {
                    let mut one: &Expr = b;
                    while let EK::Cast(y) = &one.kind {
                        one = y;
                    }
                    if matches!(one.kind, EK::Const(1)) {
                        s.steps += 1
                    } else {
                        s.bad = true
                    }
                }
                _ => s.bad = true,
            },
            EK::PtrAdd(_, idx, size) if always => {
                // (the index itself, not a narrower view of it)
                let mut x: &Expr = idx;
                let mut whole = true;
                while let EK::Cast(y) = &x.kind {
                    whole &= p.bits(x.ty) == 32;
                    x = y;
                }
                if let EK::Load(v) = &x.kind
                    && is(v, s.i)
                    && whole
                {
                    s.size = Some(s.size.map_or(*size, |z| z.max(*size)));
                }
            }
            _ => {}
        }
        match &e.kind {
            // Only the first operand is evaluated every time.
            EK::LogAnd(a, b) | EK::LogOr(a, b) => {
                walk(p, a, always, in_loop, s);
                walk(p, b, false, in_loop, s);
            }
            EK::Cond(a, b, c) => {
                walk(p, a, always, in_loop, s);
                walk(p, b, false, in_loop, s);
                walk(p, c, false, in_loop, s);
            }
            _ => e.children().into_iter().for_each(|c| walk(p, c, always, in_loop, s)),
        }
    }
    let mut s = Seen {
        i,
        n,
        bad: false,
        steps: 0,
        size: None,
    };
    for (k, b) in body.blocks.iter().enumerate() {
        let in_loop = l.inside.contains(&k);
        if in_loop && k != l.head && !matches!(b.term, Term::Jump(_)) {
            return None;
        }
        for op in &b.ops {
            match &op.kind {
                OpKind::Eval(e) => walk(p, e, true, in_loop, &mut s),
                OpKind::Init { var, items, .. } => {
                    s.bad |= in_loop && (*var == i || *var == n);
                    items.iter().for_each(|x| walk(p, &x.1, true, in_loop, &mut s));
                }
            }
        }
        match &b.term {
            Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => walk(p, e, true, in_loop, &mut s),
            _ => {}
        }
    }
    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
        eprintln!(
            "counted loop at block {}: size {:?} bad {} steps {}",
            l.head, s.size, s.bad, s.steps
        );
    }
    let size = s.size.filter(|&z| z >= 2 && !s.bad && s.steps == 1)?;
    let with = |kind: EK| Expr {
        kind,
        ty: cond.ty,
        loc: cond.loc,
    };
    let limit = Expr {
        kind: EK::Const(((1u64 << 31) - 1) / size as u64 + 1),
        ty: b.ty,
        loc: b.loc,
    };
    let done = with(EK::Bin(BinOp::Le, b.clone(), a.clone()));
    let small = with(EK::Bin(BinOp::Le, b.clone(), Box::new(limit)));
    Some((with(EK::Bin(BinOp::Or, Box::new(done), Box::new(small))), true))
}

/// A function with a loop among those `fid` mentions (calls, most of the time), directly or
/// through other functions: where the loop of a function without one may be.
fn callee_with_loop(p: &Program, fid: u32) -> Option<&str> {
    use crate::c::ast::OpKind;
    fn mentions(e: &Expr, out: &mut Vec<u32>) {
        if let EK::Func(id) = e.kind {
            out.push(id);
        }
        for c in e.children() {
            mentions(c, out);
        }
    }
    let mut seen = HashSet::from([fid]);
    let mut work = vec![(fid, 0)];
    while let Some((f, depth)) = work.pop() {
        let Some(body) = &p.funcs[f as usize].body else {
            continue;
        };
        if body.blocks.is_empty() {
            continue;
        }
        if f != fid && !c_loops(body).is_empty() {
            return Some(&p.funcs[f as usize].name);
        }
        if depth >= 4 {
            continue;
        }
        let mut found = Vec::new();
        for b in &body.blocks {
            for op in &b.ops {
                match &op.kind {
                    OpKind::Eval(e) => mentions(e, &mut found),
                    OpKind::Init { items, .. } => items.iter().for_each(|i| mentions(&i.1, &mut found)),
                }
            }
            match &b.term {
                Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => mentions(e, &mut found),
                _ => {}
            }
        }
        for g in found {
            if seen.insert(g) {
                work.push((g, depth + 1));
            }
        }
    }
    None
}

/// Prove the whole function by induction over its loops.  None if no proof was found.
pub(super) fn prove(ctx: &mut Ctx, job: &Job, pre: &[T], range: (u32, u32)) -> Result<Proof, Failure> {
    let debug = std::env::var_os("CVERIF_DEBUG").is_some();
    // (a loop in a function called from here is not a loop of this function: where the
    // binary calls that function too it is a call on both sides, and where the binary has
    // it inline the source is followed into it and there is no cut point to stop at)
    let no_loop = || match callee_with_loop(job.prog, job.fid) {
        Some(g) => Failure::new(
            "callee-loop",
            format!("the function's own body has no loop; {g}, which it calls, has one"),
            0,
        ),
        None => Failure::new("no-source-loop", "neither the function nor what it calls has a loop", 0),
    };
    let body = job.prog.funcs[job.fid as usize].body.as_ref().ok_or_else(no_loop)?;
    let loops = c_loops(body);
    if loops.is_empty() {
        return Err(no_loop());
    }
    let sizes: Vec<(usize, (Expr, bool))> = (0..loops.len())
        .filter_map(|l| Some((l, size_assumption(job.prog, body, &loops[l])?)))
        .collect();
    let mut worst: Option<Failure> = None;
    let note = |f: Failure, worst: &mut Option<Failure>| {
        if worst.as_ref().is_none_or(|w| f.rank > w.rank) {
            *worst = Some(f);
        }
    };
    let saved = (ctx.limits, ctx.seg);
    let work0 = ctx.work();
    let result = (|| {
        // A short path through the loops first; a long one if that is not enough (unrolled
        // loops only show their period after several iterations).
        let mut short = false;
        for (stage, depths) in [&[3usize, 5, 8][..], &[12, 20][..]].into_iter().enumerate() {
            let ex = match explore(ctx, job, pre, &loops, range, depths) {
                Ok(ex) => ex,
                Err(f) => {
                    note(f, &mut worst);
                    continue;
                }
            };
            let plain = !short;
            short = true;
            // Candidate pairings per loop: a cut block of the source with a machine address that
            // was reached about as often on the explored path.
            let mut per_loop: Vec<Vec<Pair>> = Vec::new();
            for l in &loops {
                let mut pairs: Vec<(usize, Pair)> = Vec::new();
                for (order, &block) in l.cands.iter().enumerate() {
                    let nc = ex.c.iter().filter(|s| s.block == block).count();
                    if nc == 0 {
                        continue;
                    }
                    let mut counts: BTreeMap<u32, usize> = BTreeMap::new();
                    for s in &ex.m {
                        *counts.entry(s.pc).or_default() += 1;
                    }
                    let c_ev: Vec<u32> = ex.c.iter().filter(|s| s.block == block).map(|s| s.nev).collect();
                    for (pc, nm) in counts {
                        let is_back = ex.back.contains(&pc);
                        if plain && (nm >= 2 || is_back) {
                            // The two sides have performed the same events whenever they are
                            // at corresponding points; `lead` is 2 where the machine code only
                            // gets there after the source has been there once.
                            let m_ev: Vec<u32> = ex.m.iter().filter(|s| s.pc == pc).map(|s| s.nev).collect();
                            for lead in 1..=2usize {
                                if nc < lead || !c_ev[lead - 1..].iter().zip(&m_ev).all(|(a, b)| a == b) {
                                    continue;
                                }
                                let pair = Pair {
                                    block,
                                    pc,
                                    lead,
                                    ratio: 1,
                                };
                                let score = (nc + 1 - lead).abs_diff(nm) * 4 + order + 3 * usize::from(!is_back);
                                pairs.push((score + 2 * (lead - 1), pair));
                                break;
                            }
                        }
                        if stage == 1 && is_back && nm >= 2 && nc > nm {
                            // `ratio` source iterations per machine iteration, after `lead` of them.
                            let (low, high) = (nc.div_ceil(nm + 1).max(2), (nc - 1) / (nm - 1));
                            for ratio in (low..=high).rev().take(4) {
                                let span = (nm - 1) * ratio;
                                for lead in 1..=ratio {
                                    if lead + span <= nc {
                                        let pair = Pair { block, pc, lead, ratio };
                                        pairs.push((100 + order + 2 * lead, pair));
                                    }
                                }
                            }
                        }
                    }
                }
                pairs.sort_by_key(|p| (p.0, p.1.pc, p.1.ratio, p.1.lead));
                pairs.truncate(if stage == 0 { 8 } else { 30 });
                if !pairs.is_empty() {
                    per_loop.push(pairs.into_iter().map(|p| p.1).collect());
                }
            }
            // One loop at a time first, then all loops together.
            let mut plans: Vec<Vec<Pair>> = per_loop.iter().flatten().map(|&p| vec![p]).collect();
            if per_loop.len() >= 2 && plain {
                // With several loops, the likeliest cut of each together comes first: a loop
                // without a cut point can only be unrolled.
                let first: Vec<Pair> = per_loop.iter().map(|p| p[0]).collect();
                if (0..first.len())
                    .all(|i| (0..i).all(|j| first[i].pc != first[j].pc && first[i].block != first[j].block))
                {
                    plans.insert(0, first);
                }
                let mut combos: Vec<Vec<Pair>> = vec![Vec::new()];
                for pairs in &per_loop {
                    let mut next = Vec::new();
                    for c in &combos {
                        for &p in pairs.iter().take(4) {
                            if c.iter().any(|q: &Pair| q.pc == p.pc) {
                                continue;
                            }
                            let mut c = c.clone();
                            c.push(p);
                            next.push(c);
                        }
                    }
                    combos = next;
                    combos.truncate(24);
                }
                plans.extend(combos);
            }
            if plans.is_empty() {
                let f = Failure::new(
                    "no-cut-pair",
                    "no address of the binary is reached as often as a loop head of the source, with the same calls made",
                    2,
                );
                note(f, &mut worst);
            }
            for plan in plans.into_iter().take(64) {
                if let Err(e) = ctx.check_deadline() {
                    let w = match e {
                        Stop::Truncated(w) => w,
                        e => format!("{e:?}"),
                    };
                    // The attempts made so far say more than the limit that ended them.
                    note(Failure::new("budget", format!("{w} before any attempt"), 3), &mut worst);
                    return None;
                }
                let mut cuts = Vec::new();
                for (id, &pair) in plan.iter().enumerate() {
                    let Some(cut) = build_cut(ctx, job, &ex, id, pair) else {
                        break;
                    };
                    cuts.push(cut);
                }
                if cuts.len() != plan.len() {
                    let f = Failure::new(
                        "no-cut-pair",
                        "no relation can be set up at the candidate cut points",
                        3,
                    );
                    note(f, &mut worst);
                    continue;
                }
                if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
                    for cut in &cuts {
                        eprintln!(
                            "cut ({}, {:#x}) lead {} ratio {} pred {:?} world_same {}",
                            cut.c_block, cut.m_pc, cut.lead, cut.ratio, cut.pred, cut.world_same
                        );
                        for (side, locs) in [("source", &cut.c_locs), ("machine", &cut.m_locs)] {
                            for (i, l) in locs.iter().enumerate() {
                                let cands: Vec<String> = l
                                    .cands
                                    .iter()
                                    .map(|c| match c {
                                        Cand::Inv(v) => format!("= {}", ctx.tm.show(*v)),
                                        Cand::Rel(j, view) => format!("= {view:?}(source {j})"),
                                        Cand::Val(k, view) => format!("= {view:?}(expr {k})"),
                                        Cand::Two(j, a, k, neg, x, d) => format!(
                                            "= {}*source {j} {} source {k} + {x:?} + {}",
                                            *a as u32 as i32,
                                            if *neg { "-" } else { "+" },
                                            *d as u32 as i32
                                        ),
                                        Cand::Lin2(j, _, a, base, d) => {
                                            format!(
                                                "= {}*source {j} + {base:?} + {}",
                                                *a as u32 as i32, *d as u32 as i32
                                            )
                                        }
                                        Cand::Obj(b, off) => format!("= object {} + {off}", ctx.tm.show(*b)),
                                        Cand::Lin(j, _, a, b) => {
                                            format!("= {}*source {j} + {}", *a as u32 as i32, ctx.tm.show(*b))
                                        }
                                    })
                                    .collect();
                                eprintln!("  {side} {i} {:?}: {}", l.place, cands.join(" | "));
                            }
                        }
                    }
                }
                let fresh = cuts.clone();
                let mut r = attempt(ctx, job, pre, &mut cuts, 16);
                if r.is_err() && !sizes.is_empty() {
                    // Once more with what the size limit of objects says about the loops
                    // the cut points are in.
                    cuts = fresh;
                    let mut any = false;
                    for cut in cuts.iter_mut() {
                        for (l, a) in &sizes {
                            if loops[*l].inside.contains(&cut.c_block) {
                                cut.assumed.push(a.clone());
                                any = true;
                            }
                        }
                    }
                    if any {
                        r = attempt(ctx, job, pre, &mut cuts, 16);
                    }
                }
                match r {
                    Ok(proof) => return Some(proof),
                    Err(e) => {
                        if debug {
                            eprintln!("loop proof with cuts {plan:x?} failed: {e:?}");
                        }
                        note(e, &mut worst);
                    }
                }
            }
        }
        // No whole path through the loops was found, or none gave a proof: cut every loop
        // where a path *prefix* shows it going round once.
        // (A function too large for a whole path has used the budget looking for one: this
        // stage has half as much again, a fixed amount of work like the rest.)
        let whole = (ctx.work_limit, ctx.max_terms, ctx.deadline);
        if whole.0 != u64::MAX {
            let more = ctx.work() + whole.0.saturating_sub(work0) / 2;
            ctx.set_budget(whole.0.max(more), whole.1, whole.2);
            ctx.prover.forget_unknown();
        }
        let r = prefix_plan(ctx, job, pre, &loops, range, debug).map(|mut cuts| attempt(ctx, job, pre, &mut cuts, 16));
        ctx.set_budget(whole.0, whole.1, whole.2);
        match r? {
            Ok(proof) => return Some(proof),
            Err(e) => {
                if debug {
                    eprintln!("loop proof with cuts from path prefixes failed: {e:?}");
                }
                note(e, &mut worst);
            }
        }
        None
    })();
    ctx.limits = saved.0;
    ctx.seg = saved.1;
    ctx.decisions.clear();
    result.ok_or_else(|| worst.unwrap_or_else(|| Failure::new("unsupported-shape", "no attempt was made", 0)))
}