cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
//! Binary-to-binary comparison: are two machine-code images observably equivalent?
//!
//! Both sides are executed symbolically from the same machine state.  For every function the
//! two images define under the same name, the paths of the old code are explored and the new
//! code is run under the same path condition; at every external call, at a trap and at the
//! return the observable state must be the same: the result, the memory the caller can reach,
//! the calls made and their arguments, the accesses to peripheral registers, the callee-saved
//! registers and the stack pointer.
//!
//! Two things a source would supply are missing and are replaced by explicit rules:
//!
//! * **Addresses.**  The two images lay their data out differently.  The new image runs in the
//!   address space of the old one: the address of every data access it makes is translated by
//!   symbol (`g + 4` of the new image is `g + 4` of the old one), and data only the new image
//!   has lives in a window of its own.  Pointer *values* (results, arguments, stored words)
//!   are equal when they designate the same symbol and offset, the same function, or constant
//!   strings with the same contents.
//! * **Signatures.**  r0-r3 and the stack are all potential arguments; r0 and r1 are both
//!   potential results.  A difference confined to a register that may be dead (a `void`
//!   function leaves garbage in r0) is a class of its own or a stated condition, never
//!   silently dropped.  See [`Assumptions`].

/// The reference interpreter of the tests, used to run counterexamples (see `replay`).
#[allow(dead_code, clippy::all)]
#[path = "../tests/support/armsim.rs"]
mod armsim;
pub mod replay;

use crate::c::ast::{Program, VOID};
use crate::image::{Image, Segment, SymKind};
use crate::sym::{Ctx, R, Stop};
use crate::term::{Env, Node, T};
use crate::thumb::exec::{Callee, Exit, Machine, Remap, image_init};
use crate::verify::{Options as VerifyOptions, Status, model_runtime_call, run_jobs, verify};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::Arc;
use std::time::Instant;

// ----- options ----------------------------------------------------------------------

/// What the comparison takes for granted where machine code alone does not say.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Assumptions {
    /// The stack pointer is 8-byte aligned at function entry (AAPCS public interface).
    pub sp_aligned: bool,
    /// A register or stack word that the two images pass with different values to a function
    /// neither of them defines is not an argument of that function.  Off by default: such a
    /// function is then reported as MAY-DIFFER.
    pub ext_arity: bool,
    /// A function whose r1 differs at return does not return a 64-bit value, unless a caller
    /// in one of the images reads r1 after calling it.
    pub ret32: bool,
    /// A function whose effects are the same and whose r0 differs at return returns nothing,
    /// unless a caller in one of the images reads r0 after calling it.
    pub void_r0: bool,
    /// The stack at and above the entry stack pointer is the caller's.  Machine code does not
    /// say how many stack arguments a function has (those it owns and may overwrite), so every
    /// word there counts as visible to the caller: the two versions must leave the same values.
    pub caller_stack: bool,
}

impl Default for Assumptions {
    fn default() -> Self {
        Assumptions {
            sp_aligned: true,
            ext_arity: false,
            ret32: true,
            void_r0: false,
            caller_stack: true,
        }
    }
}

impl Assumptions {
    /// Name, whether it is in force, and what it means.
    pub fn list(&self) -> Vec<(&'static str, bool, &'static str)> {
        vec![
            (
                "sp-aligned",
                self.sp_aligned,
                "the stack pointer is 8-byte aligned at function entry",
            ),
            (
                "ext-arity",
                self.ext_arity,
                "an argument register or stack word passed with different values to a function neither image defines is not one of its arguments (each use is listed)",
            ),
            (
                "ret32",
                self.ret32,
                "a function whose r1 differs at return does not return a 64-bit value, unless a caller in the images reads r1",
            ),
            (
                "void-r0",
                self.void_r0,
                "a function with the same effects whose r0 differs at return returns nothing, unless a caller in the images reads r0",
            ),
            (
                "caller-stack",
                self.caller_stack,
                "the stack at and above the entry stack pointer belongs to the caller (the number of stack arguments is unknown): a store there is a difference unless both versions leave the same value",
            ),
        ]
    }

    pub fn set(&mut self, name: &str, on: bool) -> Result<(), String> {
        match name {
            "sp-aligned" => self.sp_aligned = on,
            "ext-arity" => self.ext_arity = on,
            "ret32" => self.ret32 = on,
            "void-r0" => self.void_r0 = on,
            "caller-stack" => self.caller_stack = on,
            _ => {
                return Err(format!(
                    "unknown assumption `{name}` (known: sp-aligned, ext-arity, ret32, void-r0, caller-stack)"
                ));
            }
        }
        Ok(())
    }
}

/// Assumptions of the model itself: they cannot be switched off.
pub const MODEL_ASSUMPTIONS: [&str; 7] = [
    "a callee does not read an argument register that some caller leaves holding what an earlier call clobbered, nor a stack word some caller never wrote",
    "a call that is the last instruction of a function does not return, nor does a function all of whose paths end in such a call or in an endless loop",
    "results are returned in r0 (r0:r1); r4-r11 and sp are compared as outputs, r2, r3, r12 and the flags are not",
    "pointers received from the caller do not point into the function's own stack frame or its stack arguments",
    "behaviour does not depend on the numeric value of addresses: a value that designates the same symbol and offset in both images is the same pointer",
    "an access whose address has a constant part inside an object is an access to that object",
    "only constant addresses inside the peripheral ranges (--mmio) are volatile; other memory is compared by its contents at each call and at return",
];

#[derive(Clone, Debug, Default)]
pub struct Options {
    pub verify: VerifyOptions,
    pub assume: Assumptions,
    /// Explain every reported difference: the two values as expressions, where they differ,
    /// and the code of both versions.
    pub explain: bool,
}

// ----- results ----------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
    /// Proved observably equivalent for every machine state (under the listed conditions).
    Equivalent,
    /// The same except in a place that may be dead: r0 at return (dead if the function returns
    /// nothing), an argument word at a call (dead if the callee takes fewer arguments), a frame
    /// slot a callee can reach (dead if it lies outside the object the callee was given).
    MayDiffer(String),
    /// Provably different, with an input that shows it.
    Different(String),
    /// No difference found, but exploration hit a limit.
    Bounded(String),
    /// The prover gave up.
    Inconclusive(String),
    /// Something the comparison does not model.
    Unsupported(String),
    /// Only the new image has the function.
    Added,
    /// Only the old image has the function.
    Removed,
}

/// How a pair of functions was decided.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Route {
    /// Both images match the source, and the two sources say the same about the function
    /// and everything its proofs followed.
    Source,
    /// The same instructions, calling the same functions and holding the same addresses:
    /// nothing was explored.
    SameInstructions,
    /// The machine code of the two was compared path by path.
    Machine,
    /// Not compared (only one image has the function).
    None,
}

#[derive(Clone, Debug)]
pub struct FuncDiff {
    pub name: String,
    /// (address, size) in the old and in the new image.
    pub old: Option<(u32, u32)>,
    pub new: Option<(u32, u32)>,
    pub verdict: Verdict,
    /// The code bytes are identical.
    pub same_code: bool,
    /// Conditions the verdict depends on.
    pub conditions: Vec<String>,
    /// Functions it calls that are assumed equivalent and are not proved so: (name, status).
    pub modulo: Vec<(String, String)>,
    /// The verdict was obtained with the functions it calls inlined on both sides.
    pub inlined: bool,
    /// How the source was used (three-way mode).
    pub via_source: Option<String>,
    /// What settled the verdict.
    pub route: Route,
    /// What became of the counterexample of a DIFFERENT verdict when both functions were run
    /// on it (see `replay`).  One that does not reproduce makes the verdict INCONCLUSIVE and
    /// is kept here; the others are kept with `CVERIF_REPLAY` set or from `compare_replayed`.
    pub replay: Option<replay::Replay>,
    pub paths: usize,
    pub millis: u128,
    /// With `Options::explain`: the difference in detail and both listings.
    pub explanation: Option<String>,
}

impl FuncDiff {
    pub fn label(&self) -> &'static str {
        match &self.verdict {
            Verdict::Equivalent if self.same_code && self.old.map(|o| o.0) != self.new.map(|n| n.0) => "MOVED",
            Verdict::Equivalent if self.same_code => "IDENTICAL",
            Verdict::Equivalent => "EQUIVALENT",
            Verdict::MayDiffer(_) => "MAY-DIFFER",
            Verdict::Different(_) => "DIFFERENT",
            Verdict::Bounded(_) => "BOUNDED",
            Verdict::Inconclusive(_) => "INCONCLUSIVE",
            Verdict::Unsupported(_) => "UNSUPPORTED",
            Verdict::Added => "ADDED",
            Verdict::Removed => "REMOVED",
        }
    }

    /// Equivalent, whatever the code looks like.
    pub fn is_equivalent(&self) -> bool {
        self.verdict == Verdict::Equivalent
    }

    pub fn detail(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        match &self.verdict {
            Verdict::MayDiffer(s)
            | Verdict::Different(s)
            | Verdict::Bounded(s)
            | Verdict::Inconclusive(s)
            | Verdict::Unsupported(s) => parts.push(s.clone()),
            _ => {}
        }
        if !self.modulo.is_empty() {
            let l: Vec<String> = self.modulo.iter().map(|(n, s)| format!("{n} ({s})")).collect();
            parts.push(format!("modulo {}", l.join(", ")));
        }
        if !self.conditions.is_empty() {
            parts.push(format!("if {}", self.conditions.join("; ")));
        }
        if let Some(s) = &self.via_source {
            parts.push(format!("[{s}]"));
        }
        parts.join("  ")
    }
}

#[derive(Clone, Debug, Default)]
pub struct Comparison {
    pub funcs: Vec<FuncDiff>,
    /// Data objects both images define, and those whose initial contents differ.
    pub data_checked: usize,
    pub data: Vec<(String, String)>,
    pub data_added: Vec<String>,
    pub data_removed: Vec<String>,
    pub assume: Assumptions,
    pub with_source: bool,
    /// With one source per image: the functions whose definition differs between the two,
    /// and the unchanged ones that depend on a change otherwise than through a call that
    /// their proofs compared as a call (see `SrcDelta::through_source`).
    pub source_changed: Vec<String>,
    pub source_affected: Vec<String>,
    /// With sources: pairs that consist of the same instructions and were for that reason
    /// not checked against the source.
    pub source_unchecked: usize,
}

impl Comparison {
    /// Something provably differs.
    pub fn differs(&self) -> bool {
        !self.data.is_empty() || self.funcs.iter().any(|f| matches!(f.verdict, Verdict::Different(_)))
    }

    /// Some function differs unless a register or stack slot is dead, which nothing shows.
    pub fn may_differ(&self) -> bool {
        self.funcs.iter().any(|f| matches!(f.verdict, Verdict::MayDiffer(_)))
    }

    pub fn func(&self, name: &str) -> Option<&FuncDiff> {
        self.funcs.iter().find(|f| f.name == name)
    }

    pub fn count(&self, label: &str) -> usize {
        self.funcs.iter().filter(|f| f.label() == label).count()
    }

    pub fn render(&self) -> String {
        let mut o = String::new();
        let width = self.funcs.iter().map(|f| f.name.len()).max().unwrap_or(8);
        for f in &self.funcs {
            let size = |x: Option<(u32, u32)>| x.map_or("-".to_string(), |x| x.1.to_string());
            let mut line = format!(
                "{:<12} {:<width$}  {:>5} -> {:<5} bytes  {:>4} paths  {:>6} ms",
                f.label(),
                f.name,
                size(f.old),
                size(f.new),
                f.paths,
                f.millis
            );
            let d = f.detail();
            if !d.is_empty() {
                line.push_str("  ");
                line.push_str(&d);
            }
            match &f.replay {
                Some(replay::Replay::Reproduced(how)) => {
                    let _ = write!(line, "  {{run on that input: {how}}}");
                }
                Some(replay::Replay::NotReproduced(_)) => {}
                Some(replay::Replay::NotModelled(how)) => {
                    let _ = write!(line, "  {{not run on that input: {how}}}");
                }
                None => {}
            }
            let _ = writeln!(o, "{}", line.trim_end());
            if let Some(e) = &f.explanation {
                for l in e.lines() {
                    let _ = writeln!(o, "    {l}");
                }
            }
        }
        for (n, what) in &self.data {
            let _ = writeln!(o, "{:<12} {n}: {what}", "DATA");
        }
        for n in &self.data_added {
            let _ = writeln!(o, "{:<12} {n}: only in the new image", "DATA");
        }
        for n in &self.data_removed {
            let _ = writeln!(o, "{:<12} {n}: only in the old image", "DATA");
        }
        let _ = writeln!(o);
        let eq = self.funcs.iter().filter(|f| f.is_equivalent()).count();
        let names = |l: &str| -> String {
            let v: Vec<&str> = self
                .funcs
                .iter()
                .filter(|f| f.label() == l)
                .map(|f| f.name.as_str())
                .collect();
            if v.is_empty() {
                String::new()
            } else {
                format!(": {}", v.join(", "))
            }
        };
        let _ = writeln!(
            o,
            "functions:       {eq} equivalent ({} identical, {} moved), {} different{}",
            self.count("IDENTICAL"),
            self.count("MOVED"),
            self.count("DIFFERENT"),
            names("DIFFERENT")
        );
        let _ = writeln!(
            o,
            "                 {} may differ (in a register or stack slot that may be dead){}",
            self.count("MAY-DIFFER"),
            names("MAY-DIFFER")
        );
        let _ = writeln!(
            o,
            "                 {} bounded, {} inconclusive, {} unsupported, {} added{}, {} removed{}",
            self.count("BOUNDED"),
            self.count("INCONCLUSIVE"),
            self.count("UNSUPPORTED"),
            self.count("ADDED"),
            names("ADDED"),
            self.count("REMOVED"),
            names("REMOVED")
        );
        let _ = writeln!(
            o,
            "data objects:    {} compared, {} differ, {} added, {} removed",
            self.data_checked,
            self.data.len(),
            self.data_added.len(),
            self.data_removed.len()
        );
        let _ = writeln!(
            o,
            "mode:            {}",
            if self.with_source {
                "three-way (both images against the source, then against each other)"
            } else {
                "machine code against machine code, no source"
            }
        );
        if self.funcs.iter().any(|f| f.replay.is_some()) {
            let n =
                |p: fn(&replay::Replay) -> bool| self.funcs.iter().filter(|f| f.replay.as_ref().is_some_and(p)).count();
            let _ = writeln!(
                o,
                "counterexamples: {} reproduced by running both functions, {} not reproduced, {} not run",
                n(|r| matches!(r, replay::Replay::Reproduced(_))),
                n(|r| matches!(r, replay::Replay::NotReproduced(_))),
                n(|r| matches!(r, replay::Replay::NotModelled(_)))
            );
        }
        let by = |r: Route| self.funcs.iter().filter(|f| f.route == r).count();
        let _ = writeln!(
            o,
            "decided by:      {} through the source (both images match it, and it says the same in both versions), {} by having the same instructions, {} by comparing the machine code",
            by(Route::Source),
            by(Route::SameInstructions),
            by(Route::Machine)
        );
        if self.source_unchecked > 0 {
            let _ = writeln!(
                o,
                "                 {} pair(s) with the same instructions are equivalent whatever the source says, and were not checked against it (verify an image against its source for that)",
                self.source_unchecked
            );
        }
        if !self.source_changed.is_empty() {
            let list = |v: &[String]| {
                let mut s = v.iter().take(12).cloned().collect::<Vec<_>>().join(", ");
                if v.len() > 12 {
                    let _ = write!(s, ", ... ({} in all)", v.len());
                }
                s
            };
            let _ = writeln!(
                o,
                "source:          {} function(s) changed between the two sources: {}",
                self.source_changed.len(),
                list(&self.source_changed)
            );
            if !self.source_affected.is_empty() {
                let _ = writeln!(
                    o,
                    "                 {} more depend on a change otherwise than through a call (the code of a changed function in place, a changed object, a changed interface): {}",
                    self.source_affected.len(),
                    list(&self.source_affected)
                );
            }
            let _ = writeln!(
                o,
                "                 these are compared as machine code; a function that only calls a changed one depends on it through its interface, and is equivalent through the source if it matches its source in both images"
            );
        }
        let _ = writeln!(o, "assumptions:");
        for (name, on, what) in self.assume.list() {
            let _ = writeln!(o, "  {} {name:<10} {what}", if on { "[x]" } else { "[ ]" });
        }
        for what in MODEL_ASSUMPTIONS {
            let _ = writeln!(o, "  [x] {:<10} {what}", "(model)");
        }
        let _ = writeln!(
            o,
            "verdict:         {}",
            if self.differs() {
                "DIFFERENT - the two images do not behave the same"
            } else if self.may_differ() {
                "MAY DIFFER - the images differ in registers or stack slots that nothing shows to be dead"
            } else if self
                .funcs
                .iter()
                .all(|f| f.is_equivalent() || matches!(f.verdict, Verdict::Added | Verdict::Removed))
            {
                "EQUIVALENT - every function both images define is proved equivalent"
            } else {
                "no difference proved"
            }
        );
        o
    }

    pub fn json(&self, old: &str, new: &str) -> String {
        let mut o = String::new();
        let _ = writeln!(o, "{{");
        let _ = writeln!(o, "  \"type\": \"compare\",");
        let _ = writeln!(o, "  \"old\": {},", json_str(old));
        let _ = writeln!(o, "  \"new\": {},", json_str(new));
        let _ = writeln!(o, "  \"with_source\": {},", self.with_source);
        let _ = writeln!(o, "  \"different\": {},", self.differs());
        let _ = writeln!(o, "  \"may_differ\": {},", self.may_differ());
        let _ = writeln!(o, "  \"assumptions\": {{");
        let l = self.assume.list();
        for (i, (name, on, _)) in l.iter().enumerate() {
            let _ = writeln!(
                o,
                "    {}: {on}{}",
                json_str(name),
                if i + 1 < l.len() { "," } else { "" }
            );
        }
        let _ = writeln!(o, "  }},");
        let list = |v: Vec<String>| format!("[{}]", v.join(", "));
        let _ = writeln!(
            o,
            "  \"model_assumptions\": {},",
            list(MODEL_ASSUMPTIONS.iter().map(|s| json_str(s)).collect())
        );
        let _ = writeln!(o, "  \"functions\": [");
        for (i, f) in self.funcs.iter().enumerate() {
            let at = |x: Option<(u32, u32)>| match x {
                Some((a, s)) => format!("{{\"addr\": {a}, \"size\": {s}}}"),
                None => "null".into(),
            };
            let reason = match &f.verdict {
                Verdict::MayDiffer(s)
                | Verdict::Different(s)
                | Verdict::Bounded(s)
                | Verdict::Inconclusive(s)
                | Verdict::Unsupported(s) => json_str(s),
                _ => "null".into(),
            };
            let _ = writeln!(
                o,
                "    {{\"name\": {}, \"status\": {}, \"reason\": {reason}, \"old\": {}, \"new\": {}, \"same_code\": {}, \"inlined\": {}, \"conditions\": {}, \"modulo\": {}, \"source\": {}, \"route\": {}, \"explanation\": {}, \"paths\": {}, \"millis\": {}}}{}",
                json_str(&f.name),
                json_str(f.label()),
                at(f.old),
                at(f.new),
                f.same_code,
                f.inlined,
                list(f.conditions.iter().map(|s| json_str(s)).collect()),
                list(
                    f.modulo
                        .iter()
                        .map(|(n, s)| format!("{{\"name\": {}, \"status\": {}}}", json_str(n), json_str(s)))
                        .collect()
                ),
                f.via_source.as_ref().map_or("null".into(), |s| json_str(s)),
                match f.route {
                    Route::Source => "\"source\"",
                    Route::SameInstructions => "\"same-instructions\"",
                    Route::Machine => "\"machine\"",
                    Route::None => "null",
                },
                f.explanation.as_ref().map_or("null".into(), |s| json_str(s)),
                f.paths,
                f.millis,
                if i + 1 < self.funcs.len() { "," } else { "" }
            );
        }
        let _ = writeln!(o, "  ],");
        let _ = writeln!(
            o,
            "  \"data\": {{\"compared\": {}, \"different\": {}, \"added\": {}, \"removed\": {}}},",
            self.data_checked,
            list(
                self.data
                    .iter()
                    .map(|(n, w)| format!("{{\"name\": {}, \"what\": {}}}", json_str(n), json_str(w)))
                    .collect()
            ),
            list(self.data_added.iter().map(|s| json_str(s)).collect()),
            list(self.data_removed.iter().map(|s| json_str(s)).collect()),
        );
        let _ = writeln!(o, "  \"summary\": {{");
        let labels = [
            "IDENTICAL",
            "MOVED",
            "EQUIVALENT",
            "MAY-DIFFER",
            "DIFFERENT",
            "BOUNDED",
            "INCONCLUSIVE",
            "UNSUPPORTED",
            "ADDED",
            "REMOVED",
        ];
        for (i, l) in labels.iter().enumerate() {
            let _ = writeln!(
                o,
                "    {}: {}{}",
                json_str(l),
                self.count(l),
                if i + 1 < labels.len() { "," } else { "" }
            );
        }
        let _ = writeln!(o, "  }}");
        let _ = writeln!(o, "}}");
        o
    }
}

fn json_str(s: &str) -> String {
    let mut o = String::with_capacity(s.len() + 2);
    o.push('"');
    for c in s.chars() {
        match c {
            '"' => o.push_str("\\\""),
            '\\' => o.push_str("\\\\"),
            '\n' => o.push_str("\\n"),
            '\r' => o.push_str("\\r"),
            '\t' => o.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(o, "\\u{:04x}", c as u32);
            }
            c => o.push(c),
        }
    }
    o.push('"');
    o
}

// ----- address correspondence -----------------------------------------------------------

/// A data object of the new image.
#[derive(Clone, Debug)]
struct ObjMap {
    start: u32,
    size: u32,
    /// Address of the object of the same name in the old image.
    to: Option<u32>,
    /// Accesses are redirected to the old image's object (writable data, or read-only data
    /// with the same contents); otherwise the object lives in the new image's own window.
    direct: bool,
    /// A pointer into the object is the same value as a pointer into the old image's object:
    /// writable data, or read-only data with the same contents up to pointers.
    same: bool,
}

/// How addresses of the new image translate into the address space of the old one.
#[derive(Debug, Default)]
struct Layout {
    objs: Vec<ObjMap>,
    /// Fake addresses of undefined symbols: (new, old).
    ext: Vec<(u32, u32)>,
    /// Segments of the new image: (address, size, writable).
    segs: Vec<(u32, u32, bool)>,
    /// Offset of the window that holds what only the new image has.
    delta: u32,
    /// Read-only memory in the common address space: (address, size).
    rom: Vec<(u32, u32)>,
}

/// Most values a pointer read from a constant table may take for it to be followed.
const MAX_TABLE_VALUES: usize = 32;
/// Most pairs of corresponding pointers set aside one by one when two values are compared.
const MAX_POINTER_PAIRS: usize = 400;

/// Every value `t` can take on the current path, if there are few.
fn enumerate(ctx: &mut Ctx, t: T, max: usize) -> Option<Vec<u32>> {
    if let Some(k) = ctx.tm.as_const(t) {
        return Some(vec![k as u32]);
    }
    let mut values: Vec<u32> = Vec::new();
    let mut known = ctx.tm.fals();
    loop {
        match ctx.check(known) {
            Ok(()) => break,
            Err(Some(env)) => {
                let v = ctx.tm.eval(t, &env, &mut Default::default());
                if values.contains(&(v as u32)) || values.len() >= max {
                    return None;
                }
                values.push(v as u32);
                let k = ctx.tm.konst(32, v);
                let e = ctx.tm.eq(t, k);
                known = ctx.tm.or(known, e);
            }
            Err(None) => return None,
        }
    }
    // A model need not say anything about a term the question did not mention: keep the
    // values the path allows.
    values.retain(|&v| {
        let k = ctx.tm.konst(32, v as u64);
        let ne = ctx.tm.ne(t, k);
        !ctx.implied(ne)
    });
    values.sort_unstable();
    Some(values)
}

/// An address with a symbolic part and a constant part below this is a pointer plus a field
/// offset, not an indexed object, even if an image is loaded at address zero.
const SMALL_OFFSET: u32 = 0x1000;

impl Layout {
    /// Where an access of the new image at constant address `k` goes.
    fn access(&self, k: u32) -> Option<u32> {
        for &(b, a) in &self.ext {
            if k.wrapping_sub(b) < 16 {
                return Some(a.wrapping_add(k - b));
            }
        }
        if let Some(o) = self.objs.iter().find(|o| k.wrapping_sub(o.start) < o.size) {
            return Some(match o.to {
                Some(a) if o.direct => a.wrapping_add(k - o.start),
                _ => k.wrapping_add(self.delta),
            });
        }
        let seg = self.segs.iter().find(|s| k.wrapping_sub(s.0) < s.1)?;
        // Writable memory no symbol names (a heap, a stack area) is taken to be laid out alike.
        Some(if seg.2 { k } else { k.wrapping_add(self.delta) })
    }

    /// The old image's address for a pointer value of the new image into a named object.
    fn value(&self, k: u32) -> Option<u32> {
        for &(b, a) in &self.ext {
            if k.wrapping_sub(b) < 16 {
                return Some(a.wrapping_add(k - b));
            }
        }
        let o = self.objs.iter().find(|o| k.wrapping_sub(o.start) < o.size)?;
        o.to.filter(|_| o.same).map(|a| a.wrapping_add(k - o.start))
    }

    fn translate(&self, ctx: &mut Ctx, addr: T) -> T {
        if ctx.region(addr).is_some() {
            return addr;
        }
        if let Node::Ite(c, x, y) = *ctx.tm.node(addr) {
            let (x, y) = (self.translate(ctx, x), self.translate(ctx, y));
            return ctx.tm.ite(c, x, y);
        }
        let (ts, k) = ctx.tm.linear(addr);
        let k = k as u32;
        if ts.is_empty() || k >= SMALL_OFFSET {
            match self.access(k) {
                Some(n) if n != k => return ctx.tm.add_const(addr, n.wrapping_sub(k) as u64),
                Some(_) => return addr,
                None => {}
            }
        }
        // A pointer read from a constant table of the new image: one of a few addresses of
        // the new image, each translated on its own.
        if ts.is_empty() || !self.reads_rom(ctx, addr) {
            return addr;
        }
        let Some(values) = enumerate(ctx, addr, MAX_TABLE_VALUES) else {
            return addr;
        };
        let to = |k: u32| self.access(k).unwrap_or(k);
        let Some((&last, rest)) = values.split_last() else {
            return addr;
        };
        let mut out = ctx.tm.konst(32, to(last) as u64);
        for &k in rest.iter().rev() {
            let (kt, nt) = (ctx.tm.konst(32, k as u64), ctx.tm.konst(32, to(k) as u64));
            let c = ctx.tm.eq(addr, kt);
            out = ctx.tm.ite(c, nt, out);
        }
        out
    }

    /// Does the value come out of read-only memory (a load whose address has its constant
    /// part there)?
    fn reads_rom(&self, 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 seen.len() > 4000 {
                return false;
            }
            let n = ctx.tm.node(x);
            if let Node::Load(epoch, a) = n
                && *epoch < crate::sym::UNINIT_EPOCH
            {
                let k = ctx.tm.linear(*a).1 as u32;
                if self.rom.iter().any(|r| k.wrapping_sub(r.0) < r.1) {
                    return true;
                }
            }
            stack.extend(crate::bv::Prover::children_of(n));
        }
        false
    }
}

/// A named thing of an image: a data object or a function.
#[derive(Clone, Debug)]
struct Named {
    name: String,
    file: Option<String>,
    addr: u32,
    size: u32,
    writable: bool,
}

/// Named data objects of an image.
fn objects(img: &Image) -> Vec<Named> {
    let mut syms: Vec<&crate::image::Symbol> = img
        .symbols
        .iter()
        .filter(|s| s.kind != SymKind::Func && !s.name.is_empty() && !s.name.starts_with('$'))
        .collect();
    syms.sort_by_key(|s| s.addr);
    let mut out = Vec::new();
    for (i, s) in syms.iter().enumerate() {
        let Some(seg) = img.segment_at(s.addr) else { continue };
        let end = seg.addr + seg.data.len() as u32;
        let size = if s.size > 0 {
            s.size.min(end - s.addr)
        } else if s.kind == SymKind::Object {
            // No size recorded (a symbol table from `nm`): up to the next symbol.
            syms[i + 1..]
                .iter()
                .map(|n| n.addr)
                .find(|&a| a > s.addr)
                .unwrap_or(end)
                .min(end)
                - s.addr
        } else {
            continue;
        };
        if size > 0 {
            out.push(Named {
                name: s.name.clone(),
                file: s.file.clone(),
                addr: s.addr,
                size,
                writable: seg.writable,
            });
        }
    }
    out
}

/// Pair the named things of the two images: (name to show, index in `a`, index in `b`).
/// A name that occurs once on each side is a pair.  Several things of the same name (statics
/// of different files) are told apart by the file they come from when the image records it,
/// and otherwise paired in address order if there are as many on each side.
fn pair_up(a: &[Named], b: &[Named]) -> Vec<(String, usize, usize)> {
    let group = |l: &[Named]| {
        let mut m: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        for (i, x) in l.iter().enumerate() {
            m.entry(x.name.clone()).or_default().push(i);
        }
        for v in m.values_mut() {
            v.sort_by_key(|&i| l[i].addr);
        }
        m
    };
    let (ga, gb) = (group(a), group(b));
    let mut out = Vec::new();
    for (name, va) in &ga {
        let Some(vb) = gb.get(name) else { continue };
        if va.len() == 1 && vb.len() == 1 {
            out.push((name.clone(), va[0], vb[0]));
            continue;
        }
        let base = |f: &Option<String>| f.as_ref().map(|f| f.rsplit('/').next().unwrap_or(f).to_string());
        let once =
            |l: &[Named], v: &[usize], f: &Option<String>| v.iter().filter(|&&i| base(&l[i].file) == *f).count() == 1;
        let (mut ra, mut rb) = (va.clone(), vb.clone());
        for &i in va {
            let f = base(&a[i].file);
            if f.is_some()
                && once(a, va, &f)
                && once(b, vb, &f)
                && let Some(&j) = vb.iter().find(|&&j| base(&b[j].file) == f)
            {
                out.push((format!("{name} ({})", f.unwrap()), i, j));
                ra.retain(|&x| x != i);
                rb.retain(|&x| x != j);
            }
        }
        if ra.len() == rb.len() {
            for (n, (&i, &j)) in ra.iter().zip(&rb).enumerate() {
                out.push((format!("{name} (#{})", n + 1), i, j));
            }
        }
    }
    out
}

/// Do two functions of the same size consist of the same instructions, up to branches to the
/// same place of the same function and address words that designate the same thing?  (Every
/// aligned word that is an address must designate something known to be the same, also when
/// the two are equal: the things at one address may differ.)
fn same_instructions(sp: &Space, ea: u32, eb: u32, size: u32) -> bool {
    let (Some(x), Some(y)) = (sp.a.read(ea, size), sp.b.read(eb, size)) else {
        return false;
    };
    if size == 0 || (ea ^ eb) & 3 != 0 {
        return false;
    }
    let hw = |d: &[u8], i: usize| d.get(i..i + 2).map(|h| u16::from_le_bytes([h[0], h[1]]));
    // The target of a `bl` or `b.w` at offset `i`.
    let branch = |d: &[u8], at: u32, i: usize| -> Option<u32> {
        let (h1, h2) = (hw(d, i)? as u32, hw(d, i + 2)? as u32);
        if h1 & 0xf800 != 0xf000 || h2 & 0x9000 != 0x9000 {
            return None;
        }
        let s = h1 >> 10 & 1;
        let (i1, i2) = (!(h2 >> 13 ^ s) & 1, !(h2 >> 11 ^ s) & 1);
        let imm = s << 24 | i1 << 23 | i2 << 22 | (h1 & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
        let imm = ((imm << 7) as i32 >> 7) as u32;
        Some(at.wrapping_add(i as u32).wrapping_add(4).wrapping_add(imm))
    };
    let same_place = |ta: u32, tb: u32| match (sp.a.func_at(ta), sp.b.func_at(tb)) {
        (Some(fa), Some(fb)) => {
            fa.name == fb.name
                && ta - fa.addr == tb - fb.addr
                && sp.paired.get(&fa.name).is_some_and(|p| *p == [fa.addr, fb.addr])
        }
        _ => false,
    };
    // An address word: does it designate the same thing in both images, for certain?
    let same_thing = |wa: u32, wb: u32| -> bool {
        if sp.a.func_at(wa & !1).is_some() || sp.b.func_at(wb & !1).is_some() {
            return (wa ^ wb) & 1 == 0 && same_place(wa & !1, wb & !1);
        }
        if let Some(m) = sp.layout.value(wb) {
            return m == wa;
        }
        if sp.layout.objs.iter().any(|o| wb.wrapping_sub(o.start) < o.size) {
            return false;
        }
        match (sp.a.segment_at(wa), sp.b.segment_at(wb)) {
            // Writable memory no symbol names is taken to be laid out alike.
            (Some(p), Some(q)) if p.writable && q.writable => wa == wb,
            (Some(p), Some(q)) if !p.writable && !q.writable => {
                matches!((rom_str(sp.a, wa), rom_str(sp.b, wb)), (Some(s), Some(t)) if s == t && !s.is_empty())
            }
            _ => false,
        }
    };
    // What an instruction refers to relative to its own address: nothing outside the function
    // (`Ok(None)`), a branch to the given place outside it, or something this check does not
    // follow (`Err`).
    let refs = |d: &[u8], at: u32, i: usize| -> Result<Option<u32>, ()> {
        let h = hw(d, i).ok_or(())? as u32;
        let pc = at.wrapping_add(i as u32).wrapping_add(4);
        let inside = |t: u32, len: u32| t.wrapping_sub(at) < size && t.wrapping_sub(at) + len <= size;
        let jump = |t: u32| if inside(t, 2) { Ok(None) } else { Ok(Some(t)) };
        let sext = |v: u32, bits: u32| ((v << (32 - bits)) as i32 >> (32 - bits)) as u32;
        if h < 0xe800 {
            return match h {
                0xe000..=0xe7ff => jump(pc.wrapping_add(sext(h & 0x7ff, 11) << 1)),
                0xd000..=0xddff => jump(pc.wrapping_add(sext(h & 0xff, 8) << 1)),
                _ if h & 0xf500 == 0xb100 => jump(pc + ((h >> 9 & 1) << 6 | (h >> 3 & 0x1f) << 1)),
                0x4800..=0x4fff | 0xa000..=0xa7ff => {
                    if inside((pc & !3) + (h & 0xff) * 4, 4) {
                        Ok(None)
                    } else {
                        Err(())
                    }
                }
                // The program counter as an operand.
                _ if h & 0xff78 == 0x4478 || h & 0xff78 == 0x4678 || h & 0xff87 == 0x4487 => Err(()),
                _ => Ok(None),
            };
        }
        let h2 = hw(d, i + 2).ok_or(())? as u32;
        if h & 0xf800 == 0xf000 && h2 & 0x8000 != 0 {
            if h2 & 0x1000 != 0 {
                return jump(branch(d, at, i).ok_or(())?);
            }
            if h2 & 0x4000 != 0 {
                return Err(());
            }
            if h & 0x0380 != 0x0380 {
                let s = h >> 10 & 1;
                let imm = s << 20 | (h2 >> 11 & 1) << 19 | (h2 >> 13 & 1) << 18 | (h & 0x3f) << 12 | (h2 & 0x7ff) << 1;
                let t = pc.wrapping_add(sext(imm, 21));
                return if inside(t, 2) { Ok(None) } else { Err(()) };
            }
            return Ok(None);
        }
        if h & 0xff7f == 0xf85f {
            // ldr.w from the literal pool.
            let base = pc & !3;
            let t = if h & 0x80 != 0 {
                base.wrapping_add(h2 & 0xfff)
            } else {
                base.wrapping_sub(h2 & 0xfff)
            };
            return if inside(t, 4) { Ok(None) } else { Err(()) };
        }
        if h & 0xfff0 == 0xe8d0 && h & 0xf == 0xf && h2 & 0xffe0 == 0xf000 {
            // tbb, tbh: the table follows, its entries are offsets.
            return Ok(None);
        }
        // (In a data-processing instruction on a shifted register, 1111 as the first operand
        // of ORR or ORN is no operand: those are MOV and MVN.)
        let mov = h & 0xfe00 == 0xea00 && matches!(h >> 5 & 0xf, 2 | 3);
        let pc_operand = h & 0xf == 0xf
            && !mov
            && matches!(h & 0xfe00, 0xe800 | 0xe400 | 0xea00 | 0xec00 | 0xee00 | 0xf800 | 0xfa00);
        if pc_operand || h & 0xfbff == 0xf20f || h & 0xfbff == 0xf2af || (h & 0xfe00 == 0xea00 && h2 & 0xf == 0xf) {
            return Err(());
        }
        Ok(None)
    };
    // Without the record of what is data among the code there is no telling them apart.
    if sp.a.data_ranges.is_empty() || sp.b.data_ranges.is_empty() {
        return false;
    }
    let n = size as usize;
    let mut i = 0usize;
    while i + 2 <= n {
        let (da, db) = (sp.a.is_data_in_code(ea + i as u32), sp.b.is_data_in_code(eb + i as u32));
        if da != db {
            return false;
        }
        if da {
            if (ea as usize + i).is_multiple_of(4) && i + 4 <= n {
                let word = |d: &[u8]| u32::from_le_bytes([d[i], d[i + 1], d[i + 2], d[i + 3]]);
                let (wa, wb) = (word(x), word(y));
                let ok = if sp.is_address(wa & !1) || sp.is_address(wb & !1) {
                    same_thing(wa, wb)
                } else {
                    wa == wb
                };
                if !ok {
                    return false;
                }
                i += 4;
            } else {
                if x[i..i + 2] != y[i..i + 2] {
                    return false;
                }
                i += 2;
            }
            continue;
        }
        let len = if hw(x, i).is_some_and(|h| h >= 0xe800) { 4 } else { 2 };
        if i + len > n || hw(x, i).map(|h| h >= 0xe800) != hw(y, i).map(|h| h >= 0xe800) {
            return false;
        }
        match (refs(x, ea, i), refs(y, eb, i)) {
            (Ok(None), Ok(None)) => {
                if x[i..i + len] != y[i..i + len] {
                    return false;
                }
            }
            (Ok(Some(ta)), Ok(Some(tb))) => {
                // The same kind of branch, to the same place of the same function.
                let kind = |d: &[u8]| match len {
                    4 => (hw(d, i).map(|h| h & 0xf800), hw(d, i + 2).map(|h| h & 0xd000)),
                    _ => (
                        hw(d, i).map(|h| match h {
                            0xe000..=0xe7ff => h & 0xf800,
                            0xd000..=0xdfff => h & 0xff00,
                            _ => h & 0xfd07,
                        }),
                        None,
                    ),
                };
                if kind(x) != kind(y) || !same_place(ta, tb) {
                    return false;
                }
            }
            _ => return false,
        }
        i += len;
    }
    i == n
}

/// The addresses outside a function that its instructions call or jump to directly.  (Words
/// of a literal pool that happen to look like a branch give addresses nothing is at: more
/// than there is does no harm to the callers of this.)
fn direct_targets(img: &Image, entry: u32, size: u32) -> BTreeSet<u32> {
    let mut out = BTreeSet::new();
    let Some(d) = img.read(entry, size) else {
        return out;
    };
    let hw = |i: usize| d.get(i..i + 2).map(|h| u16::from_le_bytes([h[0], h[1]]) as u32);
    let mut i = 0usize;
    while let Some(h) = hw(i) {
        let pc = entry.wrapping_add(i as u32).wrapping_add(4);
        let mut target = None;
        let mut len = 2;
        if h >= 0xe800 {
            len = 4;
            if let Some(h2) = hw(i + 2)
                && h & 0xf800 == 0xf000
                && h2 & 0x9000 == 0x9000
            {
                let s = h >> 10 & 1;
                let (i1, i2) = (!(h2 >> 13 ^ s) & 1, !(h2 >> 11 ^ s) & 1);
                let imm = s << 24 | i1 << 23 | i2 << 22 | (h & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
                target = Some(pc.wrapping_add(((imm << 7) as i32 >> 7) as u32));
            }
        } else if h & 0xf800 == 0xe000 {
            target = Some(pc.wrapping_add((((h & 0x7ff) << 21) as i32 >> 20) as u32));
        }
        if let Some(t) = target
            && t.wrapping_sub(entry) >= size
        {
            out.insert(t & !1);
        }
        i += len;
    }
    out
}

/// Code the compiler made out of parts of functions: no public interface, always followed.
fn is_fragment(name: &str) -> bool {
    name.starts_with("OUTLINED_FUNCTION_")
        || [".constprop.", ".isra.", ".part.", ".cold", ".lto_priv.", ".localalias"]
            .iter()
            .any(|p| name.contains(p))
}

/// The NUL-terminated constant at a read-only address.
fn rom_str(img: &Image, k: u32) -> Option<&[u8]> {
    let s = img.segment_at(k).filter(|s| !s.writable)?;
    let rest = &s.data[(k - s.addr) as usize..];
    let n = rest.iter().position(|&c| c == 0)?;
    Some(&rest[..n])
}

/// Do constants `ka` (old image) and `kb` (new image) designate the same thing?
fn same_const(a: &Image, b: &Image, layout: &Layout, ka: u32, kb: u32) -> bool {
    if let Some(m) = layout.value(kb) {
        return m == ka;
    }
    if let Some(fb) = b.func_at(kb & !1) {
        return (ka ^ kb) & 1 == 0 && a.func_at(ka & !1).is_some_and(|fa| fa.name == fb.name);
    }
    // A pointer into an object of the new image that has no equal in the old one.
    if ka != kb
        && layout.objs.iter().any(|o| kb.wrapping_sub(o.start) < o.size)
        && b.segment_at(kb).is_some_and(|s| s.writable)
    {
        return false;
    }
    // Constants in read-only memory are the same if they hold the same string.
    match (rom_str(a, ka), rom_str(b, kb)) {
        (Some(x), Some(y)) => x == y,
        (None, None) => ka == kb,
        _ => false,
    }
}

/// First place where the contents of two objects differ, words that are pointers to the same
/// thing being equal: (offset, old, new).
fn first_difference(a: &Image, b: &Image, layout: &Layout, x: &[u8], y: &[u8]) -> Option<(usize, u32, u32)> {
    let mut off = 0usize;
    while off < x.len().min(y.len()) {
        let n = if off.is_multiple_of(4) && off + 4 <= x.len() {
            4
        } else {
            1
        };
        let (xs, ys) = (&x[off..off + n], &y[off..off + n]);
        if xs != ys {
            let word = |s: &[u8]| s.iter().rev().fold(0u32, |v, &b| (v << 8) | b as u32);
            let (wa, wb) = (word(xs), word(ys));
            let pointers = n == 4
                && (a.segment_at(wa & !1).is_some() || a.externals.contains_key(&(wa & !1)))
                && same_const(a, b, layout, wa, wb);
            if !pointers {
                return Some((off, wa, wb));
            }
        }
        off += n;
    }
    None
}

struct Space<'a> {
    a: &'a Image,
    b: &'a Image,
    /// Data as each machine reads it, in the common address space.
    da: Arc<Image>,
    db: Arc<Image>,
    layout: Arc<Layout>,
    values: Arc<Values>,
    /// Functions both images define: name -> entry in each.
    paired: BTreeMap<String, [u32; 2]>,
    /// Entry -> name of the paired functions of each image.
    fn_key: [HashMap<u32, String>; 2],
    /// Paired functions that share their code with another name in one image only.
    folded: HashMap<String, String>,
    /// Data objects both images define: (name, old, new).
    obj_pairs: Vec<(String, Named, Named)>,
    /// Names each image leaves undefined.
    ext_names: [HashSet<String>; 2],
    mmio: Vec<(u32, u32)>,
    /// Paired functions that cannot return: in one of the images no path through their code
    /// reaches a return (it ends in a call that is the last instruction, or in a loop), or
    /// a call to them is the last instruction of its function.
    noreturn: HashSet<String>,
    /// Lowest and highest address of the segments of both images.
    span: (u32, u32),
    /// With `Options::explain`: the reported differences (message, detail).
    explain: bool,
    notes: std::sync::Mutex<Vec<(String, String)>>,
}

fn funcs_of(img: &Image) -> Vec<Named> {
    let mut v: Vec<Named> = img
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Func && !s.name.is_empty() && !is_fragment(&s.name))
        .filter(|s| img.segment_at(s.addr).is_some_and(|g| g.exec))
        .map(|s| Named {
            name: s.name.clone(),
            file: s.file.clone(),
            addr: s.addr,
            size: s.size,
            writable: false,
        })
        .collect();
    v.sort_by(|x, y| (&x.name, x.addr).cmp(&(&y.name, y.addr)));
    v.dedup_by(|x, y| x.name == y.name && x.addr == y.addr);
    v
}

/// What a pointer value of the new image is in the old one.
struct Values {
    layout: Arc<Layout>,
    /// Entry of each paired function in the new image -> its entry in the old one.
    fns: HashMap<u32, u32>,
}

impl Values {
    /// `t`, a value of the new image, with the constants it chooses among replaced by the old
    /// image's address of the same object or function.
    fn revalue(&self, ctx: &mut Ctx, t: T, seen: &mut usize) -> T {
        let mut memo = HashMap::new();
        self.revalue_in(ctx, t, seen, &mut memo)
    }

    /// Only positions that hold (parts of) the value are entered: both arms of a choice, the
    /// pieces of a concatenation, what is shifted or cut.  Conditions and the addresses of
    /// loads are in the common address space already.
    fn revalue_in(&self, ctx: &mut Ctx, t: T, seen: &mut usize, memo: &mut HashMap<T, T>) -> T {
        if let Some(&r) = memo.get(&t) {
            return r;
        }
        *seen += 1;
        if *seen > 4096 {
            return t;
        }
        let w = ctx.tm.width(t);
        let r = match *ctx.tm.node(t) {
            Node::Const(k) if w == 32 => {
                let k = k as u32;
                let to = self.layout.value(k).or_else(|| {
                    let entry = self.fns.get(&(k & !1))?;
                    Some(entry | (k & 1))
                });
                match to {
                    Some(m) if m != k => ctx.tm.konst(32, m as u64),
                    _ => t,
                }
            }
            Node::Ite(c, x, y) => {
                let (x2, y2) = (self.revalue_in(ctx, x, seen, memo), self.revalue_in(ctx, y, seen, memo));
                if (x2, y2) == (x, y) { t } else { ctx.tm.ite(c, x2, y2) }
            }
            Node::Concat(x, y) => {
                let (x2, y2) = (self.revalue_in(ctx, x, seen, memo), self.revalue_in(ctx, y, seen, memo));
                if (x2, y2) == (x, y) { t } else { ctx.tm.concat(x2, y2) }
            }
            Node::Extract(x, lo) => {
                let x2 = self.revalue_in(ctx, x, seen, memo);
                if x2 == x { t } else { ctx.tm.extract(x2, lo, w) }
            }
            Node::ZExt(x) => {
                let x2 = self.revalue_in(ctx, x, seen, memo);
                if x2 == x { t } else { ctx.tm.zext(x2, w) }
            }
            Node::LShr(x, n) => {
                let x2 = self.revalue_in(ctx, x, seen, memo);
                if x2 == x { t } else { ctx.tm.lshr(x2, n) }
            }
            Node::Shl(x, n) => {
                let x2 = self.revalue_in(ctx, x, seen, memo);
                if x2 == x { t } else { ctx.tm.shl(x2, n) }
            }
            _ => t,
        };
        memo.insert(t, r);
        r
    }
}

impl<'a> Space<'a> {
    fn revalue(&self, ctx: &mut Ctx, t: T, seen: &mut usize) -> T {
        self.values.revalue(ctx, t, seen)
    }

    fn new(a: &'a Image, b: &'a Image, mmio: &[(u32, u32)]) -> Space<'a> {
        let (oa, ob) = (objects(a), objects(b));
        // Labels the compiler numbers are not names: such constants compare by contents.
        let obj_pairs: Vec<(String, Named, Named)> = pair_up(&oa, &ob)
            .into_iter()
            .filter(|p| !p.0.starts_with(".L"))
            .map(|(n, i, j)| (n, oa[i].clone(), ob[j].clone()))
            .collect();
        let mut layout = Layout::default();
        for o in &ob {
            let peer = obj_pairs
                .iter()
                .find(|p| p.2.addr == o.addr && p.2.name == o.name)
                .map(|p| &p.1);
            let same = peer.is_some_and(|p| p.size == o.size && a.read(p.addr, p.size) == b.read(o.addr, o.size));
            let direct = peer.is_some_and(|p| (o.writable && p.writable) || (!o.writable && !p.writable && same));
            layout.objs.push(ObjMap {
                start: o.addr,
                size: o.size,
                to: peer.map(|p| p.addr),
                direct,
                // Read-only objects of the same name and size: assumed the same, until the
                // contents say otherwise (below).
                same: direct || peer.is_some_and(|p| p.size == o.size && !o.writable && !p.writable),
            });
        }
        // Smaller objects first, so that a symbol covering a whole area does not hide them.
        layout.objs.sort_by_key(|o| (o.size, o.start));
        // Read-only objects that differ only in pointers to the same things are the same.
        // Objects point to each other in cycles (every type object to the type of types, and
        // that one to itself), so this is the largest relation that holds up: all candidates
        // are taken to be the same, and those whose contents then differ are struck off until
        // none is left to strike.
        loop {
            let differ: Vec<usize> = (0..layout.objs.len())
                .filter(|&i| {
                    let o = &layout.objs[i];
                    o.same
                        && !o.direct
                        && !o
                            .to
                            .is_some_and(|to| match (a.read(to, o.size), b.read(o.start, o.size)) {
                                (Some(x), Some(y)) => first_difference(a, b, &layout, x, y).is_none(),
                                _ => false,
                            })
                })
                .collect();
            if differ.is_empty() {
                break;
            }
            for i in differ {
                if std::env::var_os("CVERIF_COMPARE_DEBUG").is_some() {
                    let o = &layout.objs[i];
                    let d = o
                        .to
                        .and_then(|to| first_difference(a, b, &layout, a.read(to, o.size)?, b.read(o.start, o.size)?));
                    eprintln!("compare: object at {:#x} (old {:x?}) differs: {d:x?}", o.start, o.to);
                }
                layout.objs[i].same = false;
            }
        }
        let ext_a: HashMap<&str, u32> = a.externals.iter().map(|(a, n)| (n.as_str(), *a)).collect();
        for (addr, name) in &b.externals {
            if let Some(&to) = ext_a.get(name.as_str()) {
                layout.ext.push((*addr, to));
            }
        }
        layout.ext.sort();
        layout.segs = b
            .segments
            .iter()
            .map(|s| (s.addr, s.data.len() as u32, s.writable))
            .collect();
        // Initialised data as stored in the load image (startup code copies it to RAM).
        let stored = |img: &Image| -> Vec<Segment> {
            img.segments
                .iter()
                .filter_map(|s| {
                    let at = s.load_addr?;
                    let free = (0..s.data.len() as u32)
                        .step_by(4)
                        .all(|o| img.segment_at(at + o).is_none());
                    free.then(|| Segment {
                        name: format!("{} (load image)", s.name),
                        addr: at,
                        data: s.data.clone(),
                        writable: false,
                        exec: false,
                        load_addr: None,
                    })
                })
                .collect()
        };
        let (stored_a, stored_b) = (stored(a), stored(b));
        layout
            .segs
            .extend(stored_b.iter().map(|s| (s.addr, s.data.len() as u32, false)));
        // A window for what only the new image has: clear of everything either image uses.
        let mut used: Vec<(u32, u32)> = mmio.to_vec();
        for img in [a, b] {
            used.extend(
                img.segments
                    .iter()
                    .map(|s| (s.addr, s.addr + (s.data.len() as u32).saturating_sub(1))),
            );
            used.extend(img.externals.keys().map(|&e| (e, e + 15)));
        }
        used.extend(
            stored_a
                .iter()
                .chain(&stored_b)
                .map(|s| (s.addr, s.addr + (s.data.len() as u32).saturating_sub(1))),
        );
        layout.delta = (1..256u32)
            .map(|d| d << 24)
            .find(|&d| {
                b.segments.iter().all(|s| {
                    let lo = s.addr.wrapping_add(d);
                    let hi = lo.wrapping_add((s.data.len() as u32).saturating_sub(1));
                    hi >= lo && used.iter().all(|&(ulo, uhi)| hi < ulo || lo > uhi)
                })
            })
            .unwrap_or(0x7000_0000);
        let clone = |s: &Segment, shift: u32| Segment {
            name: s.name.clone(),
            addr: s.addr.wrapping_add(shift),
            data: s.data.clone(),
            writable: s.writable,
            exec: s.exec,
            load_addr: None,
        };
        let da = Image {
            segments: a.segments.iter().chain(&stored_a).map(|s| clone(s, 0)).collect(),
            ..Default::default()
        };
        let mut db = Image {
            segments: da.segments.iter().map(|s| clone(s, 0)).collect(),
            ..Default::default()
        };
        db.segments
            .extend(b.segments.iter().chain(&stored_b).map(|s| clone(s, layout.delta)));
        layout.rom = db
            .segments
            .iter()
            .filter(|s| !s.writable)
            .map(|s| (s.addr, s.data.len() as u32))
            .collect();
        // Functions.
        let (fa, fb) = (funcs_of(a), funcs_of(b));
        let mut paired = BTreeMap::new();
        let mut fn_key = [HashMap::new(), HashMap::new()];
        for (name, i, j) in pair_up(&fa, &fb) {
            paired.insert(name, [fa[i].addr, fb[j].addr]);
        }
        // Names that are one piece of code in one of the images (aliases, identical
        // functions folded by the linker, a run-time routine with two ABI names) are one
        // callee: a call is the event of the first name of its group, in both images.
        let mut group: HashMap<String, String> = paired.keys().map(|n| (n.clone(), n.clone())).collect();
        let mut folded: HashMap<String, String> = HashMap::new();
        loop {
            let mut changed = false;
            for side in 0..2 {
                let mut at: HashMap<u32, String> = HashMap::new();
                for (n, e) in &paired {
                    let g = group[n].clone();
                    match at.get(&e[side]) {
                        Some(first) if *first != g => {
                            let (lo, hi) = if *first < g {
                                (first.clone(), g)
                            } else {
                                (g, first.clone())
                            };
                            for v in group.values_mut().filter(|v| **v == hi) {
                                *v = lo.clone();
                            }
                            at.insert(e[side], lo);
                            changed = true;
                        }
                        Some(_) => {}
                        None => {
                            at.insert(e[side], g);
                        }
                    }
                }
            }
            if !changed {
                break;
            }
        }
        for (n, e) in &paired {
            fn_key[0].insert(e[0], group[n].clone());
            fn_key[1].insert(e[1], group[n].clone());
            let others: Vec<&str> = (paired.iter())
                .filter(|(m, x)| *m != n && (x[0] == e[0]) != (x[1] == e[1]))
                .map(|(m, x)| (m.as_str(), x))
                .filter(|(m, _)| group[*m] == group[n])
                .map(|(m, _)| m)
                .collect();
            if !others.is_empty() {
                folded.insert(
                    n.clone(),
                    format!(
                        "folded: one piece of code with {} in one of the images",
                        others.join(", ")
                    ),
                );
            }
        }
        let stuck = |img: &Image| -> HashSet<u32> {
            let d = crate::discover::discover(
                img,
                &crate::discover::Options {
                    no_vectors: true,
                    ..Default::default()
                },
            );
            (d.discovery.funcs.iter())
                .filter(|f| f.noreturn)
                .map(|f| f.addr)
                .chain(never_return(img))
                .collect()
        };
        let (na, nb) = (stuck(a), stuck(b));
        let noreturn: HashSet<String> = (paired.iter())
            // (What one compiler knew about a function holds for the function.)
            .filter(|(_, e)| na.contains(&e[0]) || nb.contains(&e[1]))
            .map(|(n, _)| n.clone())
            .collect();
        let layout = Arc::new(layout);
        let values = Arc::new(Values {
            layout: layout.clone(),
            fns: paired.values().map(|e| (e[1], e[0])).collect(),
        });
        Space {
            a,
            b,
            da: Arc::new(da),
            db: Arc::new(db),
            layout,
            values,
            paired,
            folded,
            fn_key,
            obj_pairs,
            ext_names: [
                a.externals.values().cloned().collect(),
                b.externals.values().cloned().collect(),
            ],
            mmio: mmio.to_vec(),
            noreturn,
            span: a.segments.iter().chain(&b.segments).fold((u32::MAX, 0), |(lo, hi), s| {
                (lo.min(s.addr), hi.max(s.addr + s.data.len() as u32))
            }),
            explain: false,
            notes: Default::default(),
        }
    }

    fn image(&self, side: usize) -> &'a Image {
        if side == 0 { self.a } else { self.b }
    }

    fn data(&self, side: usize) -> &Arc<Image> {
        if side == 0 { &self.da } else { &self.db }
    }

    fn translate(&self, side: usize, ctx: &mut Ctx, addr: T) -> T {
        if side == 0 {
            addr
        } else {
            self.layout.translate(ctx, addr)
        }
    }

    /// Does the constant lie inside one of the images?
    fn is_address(&self, k: u32) -> bool {
        self.span.0 <= k && k <= self.span.1 && (self.a.segment_at(k).is_some() || self.b.segment_at(k).is_some())
    }

    fn same_const(&self, ka: u32, kb: u32) -> bool {
        same_const(self.a, self.b, &self.layout, ka, kb)
    }

    /// Are the two values the same without further proof: the same term, or pointers to the
    /// same thing in their respective images?
    fn corr(&self, ctx: &Ctx, va: T, vb: T) -> bool {
        if va == vb {
            // The same number is not the same pointer if the images hold different things there.
            return match ctx.tm.as_const(va) {
                Some(k) if ctx.tm.width(va) == 32 && self.is_address(k as u32) => self.same_const(k as u32, k as u32),
                _ => true,
            };
        }
        if ctx.tm.width(va) != 32 || ctx.tm.width(vb) != 32 {
            return false;
        }
        if let (Node::Ite(c1, x1, y1), Node::Ite(c2, x2, y2)) = (ctx.tm.node(va), ctx.tm.node(vb))
            && c1 == c2
        {
            return self.corr(ctx, *x1, *x2) && self.corr(ctx, *y1, *y2);
        }
        let ((ta, ka), (tb, kb)) = (ctx.tm.linear(va), ctx.tm.linear(vb));
        if ta != tb {
            return false;
        }
        let (ka, kb) = (ka as u32, kb as u32);
        if !ta.is_empty() && (ka < SMALL_OFFSET || kb < SMALL_OFFSET) {
            return ka == kb;
        }
        self.same_const(ka, kb)
    }
}

// ----- comparison of one function ---------------------------------------------------------

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

/// Argument words considered at a call: r0-r3 and four words of stack.
const ARG_WORDS: usize = 8;

struct Job<'a> {
    sp: &'a Space<'a>,
    entry: [u32; 2],
    regs: [[T; 16]; 2],
    lr0: T,
    stack: Vec<(u32, T)>,
    /// Follow every call into the code of the image instead of matching calls one to one.
    inline: bool,
    /// Functions followed on both sides although calls are matched one to one: one image
    /// calls them where the other has their code in place.
    follow: &'a HashSet<String>,
    /// Compare the stack at and above the entry stack pointer (assumption `caller-stack`).
    caller_stack: bool,
}

/// What the paths of one function establish beyond the verdict.
#[derive(Default)]
struct Facts {
    /// Functions of the images called as one shared event.
    calls: BTreeSet<String>,
    /// Callees after a call to which the old code decides on what the call left in a
    /// scratch register: taken not to return.
    stuck: BTreeSet<String>,
    /// A difference that needs a load to overlap a store made through another address.
    overlap: Option<String>,
    /// Functions one image called where the other did something else.
    culprits: BTreeSet<String>,
    saw_internal: RefCell<bool>,
    ret0_diff: Option<String>,
    ret1_diff: bool,
    /// Argument words that differ at a call: callee -> mask of words it must not read, and
    /// the first such difference.
    needs: BTreeMap<String, (u8, BTreeMap<u8, String>)>,
    /// Argument words some call leaves holding garbage: the callee does not read them.
    dead: BTreeSet<(String, u8)>,
    /// A frame slot a callee can reach holds different values.
    slot_diff: Option<String>,
    /// Input words (bit i: word i) the observable behaviour depends on: always, through the
    /// result in r0, through r1.
    in_always: u8,
    in_r0: u8,
    in_r1: u8,
    /// Input words passed on in word `.1` of a call to `.0`.
    in_arg: BTreeSet<(String, u8, u8)>,
    /// Results of calls (symbol ids) the behaviour depends on, likewise.
    ret_always: BTreeSet<u32>,
    ret_r0: BTreeSet<u32>,
    ret_r1: BTreeSet<u32>,
    ret_arg: BTreeSet<(String, u8, u32)>,
    /// Result symbols: id -> (callee, is the high word).
    ret_syms: HashMap<u32, (String, bool)>,
    inputs: HashMap<T, u8>,
    memo: HashMap<T, (u8, Arc<BTreeSet<u32>>)>,
}

impl Facts {
    /// The input words and call results a term depends on.
    fn deps(&mut self, ctx: &Ctx, t: T) -> (u8, Arc<BTreeSet<u32>>) {
        if let Some(d) = self.memo.get(&t) {
            return d.clone();
        }
        let d = match ctx.tm.node(t) {
            Node::Sym(id) => {
                let mut s = BTreeSet::new();
                if self.ret_syms.contains_key(id) {
                    s.insert(*id);
                }
                (self.inputs.get(&t).copied().unwrap_or(0), Arc::new(s))
            }
            n => {
                let mut mask = 0u8;
                let mut set: Option<Arc<BTreeSet<u32>>> = None;
                for c in crate::bv::Prover::children_of(n) {
                    let (m, s) = self.deps(ctx, c);
                    mask |= m;
                    if !s.is_empty() {
                        set = Some(match set {
                            None => s,
                            Some(old) if s.is_subset(&old) => old,
                            Some(old) => Arc::new(old.union(&s).copied().collect()),
                        });
                    }
                }
                (mask, set.unwrap_or_default())
            }
        };
        self.memo.insert(t, d.clone());
        d
    }

    fn always(&mut self, ctx: &Ctx, t: T) {
        let (m, s) = self.deps(ctx, t);
        self.in_always |= m;
        self.ret_always.extend(s.iter().copied());
    }
}

thread_local! {
    /// The counterexamples printed while the current function was analysed.
    static MODELS: RefCell<Vec<replay::Model>> = const { RefCell::new(Vec::new()) };
}

fn witness(ctx: &Ctx, env: &Env) -> String {
    let text = witness_text(ctx, env);
    MODELS.with(|m| {
        let mut m = m.borrow_mut();
        if m.len() < 1024 && !m.iter().any(|x| x.text == text) {
            m.push(replay::Model {
                text: text.clone(),
                syms: (env.syms.iter())
                    .map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
                    .collect(),
                mem: env.mem.clone(),
                inline: false,
                follow: Vec::new(),
            });
        }
    });
    text
}

fn witness_text(ctx: &Ctx, env: &Env) -> String {
    let mut items: Vec<(String, u64)> = env
        .syms
        .iter()
        .map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
        .filter(|(n, _)| {
            let b = n.as_bytes();
            (b.len() <= 3 && b[0] == b'r' && b[1..].iter().all(u8::is_ascii_digit))
                || n.starts_with("stk")
                || n.starts_with("ret")
                || n.starts_with("io")
        })
        .collect();
    items.sort_by(|x, y| (x.0.len(), &x.0).cmp(&(y.0.len(), &y.0)));
    let mut parts: Vec<String> = items.iter().map(|(n, v)| format!("{n}={v:#x}")).collect();
    let mut mem: Vec<(u64, u8)> = env
        .mem
        .iter()
        .filter(|((m, _), _)| *m < 0x8000_0000)
        .map(|((_, a), v)| (*a, *v))
        .collect();
    mem.sort();
    for (a, v) in mem.iter().take(8) {
        parts.push(format!("mem[{a:#x}]={v:#04x}"));
    }
    if parts.is_empty() {
        "any input".into()
    } else {
        parts.join(" ")
    }
}

/// Are two observable values the same?  None if they are; otherwise how they differ, with
/// an input that tells them apart.
fn difference(ctx: &mut Ctx, sp: &Space, va: T, vb: T, what: &str) -> R<Option<String>> {
    if sp.corr(ctx, va, vb) {
        return Ok(None);
    }
    if ctx.tm.width(va) != ctx.tm.width(vb) {
        return Ok(Some("different sizes".into()));
    }
    // A value that is one of several constants (a pointer stored earlier, read back through
    // an address that may be another's): each constant of the new image that designates
    // something stands for what designates the same thing in the old one.
    let vt = sp.revalue(ctx, vb, &mut 0);
    if vt != vb {
        let e = ctx.tm.eq(va, vt);
        if ctx.check(e).is_ok() {
            return Ok(None);
        }
    }
    // Pointers read from constant tables: each value the new one can take must designate
    // what the old one then designates.
    if ctx.tm.as_const(vb).is_none()
        && sp.layout.reads_rom(ctx, vb)
        && let Some(values) = enumerate(ctx, vb, MAX_TABLE_VALUES)
    {
        let mut all = true;
        for k in values {
            let kt = ctx.tm.konst(32, k as u64);
            let c = ctx.tm.eq(vb, kt);
            ctx.pc.push(c);
            let ka = enumerate(ctx, va, 2).filter(|v| v.len() == 1).map(|v| v[0]);
            ctx.pc.pop();
            match ka {
                Some(ka) if sp.same_const(ka, k) => {}
                Some(ka) if sp.is_address(ka) || sp.is_address(k) => {
                    return Ok(Some(format!(
                        "old gives {ka:#x}, new gives {k:#x}, which do not designate the same thing in the two images"
                    )));
                }
                _ => {
                    all = false;
                    break;
                }
            }
        }
        if all {
            return Ok(None);
        }
    }
    if let (Some(x), Some(y)) = (ctx.tm.as_const(va), ctx.tm.as_const(vb))
        && (sp.is_address(x as u32) || sp.is_address(y as u32))
    {
        return Ok(Some(format!(
            "old gives {x:#x}, new gives {y:#x}, which do not designate the same thing in the two images"
        )));
    }
    // Equal, or a pair of pointers to the same thing: an input for which the two are such
    // a pair is no counterexample, and is set aside (a large table of pointers, or one
    // indexed without a visible bound).
    let mut e = ctx.tm.eq(va, vb);
    for round in 0.. {
        let env = match ctx.check(e) {
            Ok(()) => return Ok(None),
            Err(Some(env)) => env,
            Err(None) => break,
        };
        let mut memo = Default::default();
        let (x, y) = (ctx.tm.eval(va, &env, &mut memo), ctx.tm.eval(vb, &env, &mut memo));
        if ctx.tm.width(va) != 32 || x == y || !sp.same_const(x as u32, y as u32) {
            break;
        }
        if round >= MAX_POINTER_PAIRS {
            return Err(Stop::Truncated(format!(
                "{what}: more than {MAX_POINTER_PAIRS} pairs of corresponding pointers"
            )));
        }
        let (kx, ky) = (ctx.tm.konst(32, x), ctx.tm.konst(32, y));
        let (ex, ey) = (ctx.tm.eq(va, kx), ctx.tm.eq(vb, ky));
        let pair = ctx.tm.and(ex, ey);
        e = ctx.tm.or(e, pair);
    }
    match ctx.check(e) {
        Ok(()) => Ok(None),
        Err(Some(env)) => {
            let mut memo = Default::default();
            let (x, y) = (ctx.tm.eval(va, &env, &mut memo), ctx.tm.eval(vb, &env, &mut memo));
            let how = format!("old gives {x:#x}, new gives {y:#x} for {}", witness(ctx, &env));
            if overlap_only(ctx, va, vb) {
                if ctx.notes.len() < 4 {
                    ctx.notes.push(format!("{what}: {how}"));
                }
                return Ok(None);
            }
            if sp.explain {
                let note = explain_terms(ctx, sp, va, vb, &env);
                sp.notes
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .push((format!("{what}: {how}"), note));
            }
            Ok(Some(how))
        }
        Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
    }
}

/// Do two values differ only for inputs where a load overlaps a store made through another
/// address expression?  Both compilers may order such a pair as they like when the language
/// says the two are distinct objects, which machine code does not show.
fn overlap_only(ctx: &mut Ctx, va: T, vb: T) -> bool {
    let base = ctx.pc.len();
    if !assume_no_overlap(ctx) {
        return false;
    }
    let f = ctx.tm.fals();
    let e = ctx.tm.eq(va, vb);
    // (A path that itself needs an overlap is one too.)
    let sat = ctx.check(f);
    let same = ctx.check(e);
    let only = sat.is_ok() || (matches!(sat, Err(Some(_))) && same.is_ok());
    ctx.pc.truncate(base);
    only
}

/// Is the path taken only by inputs for which a load overlaps such a store?
fn path_needs_overlap(ctx: &mut Ctx) -> bool {
    let base = ctx.pc.len();
    if !assume_no_overlap(ctx) {
        return false;
    }
    let f = ctx.tm.fals();
    let only = ctx.check(f).is_ok();
    ctx.pc.truncate(base);
    only
}

/// Add to the path condition that no byte read was one a store through another address
/// expression wrote; false (and nothing added) when there was no such possibility.  (Where
/// the path itself says that two such addresses are one, what differs there does need them
/// to be.)
fn assume_no_overlap(ctx: &mut Ctx) -> bool {
    let base = ctx.pc.len();
    for c in ctx.overlaps.clone() {
        let no = ctx.tm.not(c);
        if !ctx.pc.contains(&no) {
            ctx.pc.push(no);
        }
    }
    ctx.pc.len() > base
}

/// The two values that differ as expressions over the inputs, with their values under the
/// counterexample and the places where the expressions part.
fn explain_terms(ctx: &Ctx, sp: &Space, va: T, vb: T, env: &Env) -> String {
    use crate::explain::{Dag, Names, Printer, Style, show_val};
    let (dag, ids) = Dag::from_terms(&ctx.tm, &[va, vb], Some(env));
    let names = Names::new(sp.a, None);
    let pr = Printer::new(&dag, &names, &ids, Style::default());
    let val = |n: u32| match dag.val(n) {
        Some(v) => format!("  = {}", show_val(v, dag.width(n))),
        None => String::new(),
    };
    let mut o = String::new();
    let _ = writeln!(o, "old: {}{}", pr.expr(ids[0]), val(ids[0]));
    let _ = writeln!(o, "new: {}{}", pr.expr(ids[1]), val(ids[1]));
    let d = pr.diff(ids[0], ids[1]);
    if !(d.holes.len() == 1 && d.skeleton == d.holes[0].label) {
        let _ = writeln!(o, "differ in: {}", d.skeleton);
        for h in &d.holes {
            let v = |v: Option<u64>| v.map_or(String::new(), |v| format!("  = {}", show_val(v, h.width)));
            let _ = writeln!(o, "  {} old: {}{}", h.label, h.source, v(h.source_val));
            let _ = writeln!(o, "  {} new: {}{}", h.label, h.binary, v(h.binary_val));
        }
    }
    let lets: Vec<_> = pr.lets().into_iter().filter(|l| o.contains(&l.name)).collect();
    if !lets.is_empty() {
        let _ = writeln!(o, "where:");
        for l in lets {
            let v = l
                .value
                .map_or(String::new(), |v| format!("  = {}", show_val(v, l.width)));
            let _ = writeln!(o, "  {} = {}{v}", l.name, l.text);
        }
    }
    o
}

/// Prove two observable values equal, or report the input that tells them apart.
fn prove_same(ctx: &mut Ctx, sp: &Space, va: T, vb: T, what: &str) -> R<()> {
    match difference(ctx, sp, va, vb, what)? {
        None => Ok(()),
        Some(how) => Err(Stop::Mismatch(format!("{what}: {how}"), None)),
    }
}

fn classify(job: &Job, side: usize, facts: &Facts, addr: u32) -> Callee {
    let (img, other) = (job.sp.image(side), 1 - side);
    if let Some(name) = img.externals.get(&addr) {
        return Callee::External(name.clone());
    }
    let Some(s) = img.func_at(addr) else {
        return Callee::Internal;
    };
    if is_fragment(&s.name) {
        return Callee::Internal;
    }
    // A function the other image leaves undefined is a call there: it is one here.
    if job.sp.ext_names[other].contains(&s.name) {
        return Callee::External(s.name.clone());
    }
    if let Some(key) = job.sp.fn_key[side].get(&addr) {
        // Nothing follows a call to a function that cannot return: it is the last event of
        // the path, and the function is compared on its own.
        if job.sp.noreturn.contains(key) {
            return Callee::External(key.clone());
        }
        *facts.saw_internal.borrow_mut() = true;
        if !job.inline && !job.follow.contains(key) {
            return Callee::External(key.clone());
        }
    }
    Callee::Internal
}

/// libgcc's Thumb-1 switch dispatchers (see `verify::model_switch_helper`).
fn switch_helper(ctx: &mut Ctx, image: &Image, m: &mut Machine, name: &str, count: &mut usize) -> R<bool> {
    let (esize, signed) = match name {
        "__gnu_thumb1_case_sqi" => (1u32, true),
        "__gnu_thumb1_case_uqi" => (1, false),
        "__gnu_thumb1_case_shi" => (2, true),
        "__gnu_thumb1_case_uhi" => (2, false),
        "__gnu_thumb1_case_si" => (4, true),
        _ => return Ok(false),
    };
    let ret = m.resume_pc();
    let idx = m.regs[0];
    let mut found = None;
    for i in 0..1024u32 {
        let k = ctx.tm.konst(32, i as u64);
        let e = ctx.tm.eq(idx, k);
        if ctx.branch(e)? {
            found = Some(i);
            break;
        }
    }
    let Some(i) = found else {
        return Err(Stop::Unsupported(format!(
            "switch table with more than 1024 entries at {ret:#x}"
        )));
    };
    let base = if esize == 4 { (ret + 3) & !3 } else { ret };
    let eaddr = base + esize * i;
    let Some(bytes) = image.read_const(eaddr, esize) else {
        return Err(Stop::Unsupported(format!(
            "switch table entry outside the image at {eaddr:#x}"
        )));
    };
    let mut v = 0u32;
    for (j, &b) in bytes.iter().enumerate() {
        v |= (b as u32) << (8 * j);
    }
    let target = match (esize, signed) {
        (4, _) => base.wrapping_add(v),
        (1, true) => ret.wrapping_add((v as u8 as i8 as i32 as u32) << 1),
        (2, true) => ret.wrapping_add((v as u16 as i16 as i32 as u32) << 1),
        _ => ret.wrapping_add(v << 1),
    };
    *count += 1;
    m.resume_at(ctx, 1000 + *count, target);
    Ok(true)
}

/// A memory helper with a known length is a plain memory effect (see `verify::model_mem_call`).
fn mem_call(ctx: &mut Ctx, job: &Job, side: usize, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    use crate::c::exec::{MAX_MEM_INLINE, mem_fill};
    let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
    let zero = ctx.tm.konst(32, 0);
    let (dst, arg, len, fill) = match name {
        "memset" => (r0, r1, r2, true),
        "__aeabi_memset" | "__aeabi_memset4" | "__aeabi_memset8" => (r0, r2, r1, true),
        "__aeabi_memclr" | "__aeabi_memclr4" | "__aeabi_memclr8" => (r0, zero, r1, true),
        "memcpy" | "__aeabi_memcpy" | "__aeabi_memcpy4" | "__aeabi_memcpy8" => (r0, r1, r2, false),
        _ => return false,
    };
    let Some(n) = ctx.unique_value(len).filter(|&n| n <= MAX_MEM_INLINE) else {
        return false;
    };
    let n = n as u32;
    let to = job.sp.translate(side, ctx, dst);
    // Peripheral registers are not plain memory.
    let periph = |ctx: &Ctx, t: T| {
        ctx.tm.as_const(t).is_some_and(|a| {
            let (a, end) = (a as u32, (a as u32).wrapping_add(n.max(1) - 1));
            job.sp.mmio.iter().any(|&(lo, hi)| a <= hi && end >= lo)
        })
    };
    if periph(ctx, to) {
        return false;
    }
    if fill {
        let byte = ctx.tm.trunc(arg, 8);
        mem_fill(ctx, &mut m.mem, to, byte, n);
    } else {
        let from = job.sp.translate(side, ctx, arg);
        if periph(ctx, from) {
            return false;
        }
        let data = job.sp.data(side).clone();
        let mut chunks = Vec::new();
        let mut off = 0;
        while off < n {
            let sz = if n - off >= 4 { 4u8 } else { 1 };
            let a = ctx.tm.add_const(from, off as u64);
            let mut init = image_init(&data, m.mem.epoch, None);
            chunks.push((off, sz, ctx.mem_read(&m.mem, a, sz, &mut init)));
            off += sz as u32;
        }
        for (off, sz, v) in chunks {
            let a = ctx.tm.add_const(to, off as u64);
            ctx.mem_write(&mut m.mem, a, sz, v);
        }
    }
    *count += 1;
    let ret = if name.starts_with("__aeabi") { None } else { Some(dst) };
    m.finish_call(ctx, 1000 + *count, ret, None);
    true
}

/// Run one machine up to its next observable exit.
fn run_side(ctx: &mut Ctx, job: &Job, facts: &Facts, side: usize, m: &mut Machine, helpers: &mut usize) -> R<Exit> {
    let image = job.sp.image(side);
    let cl = |addr: u32| classify(job, side, facts, addr);
    let who = if side == 0 { "old image" } else { "new image" };
    loop {
        ctx.dead_garbage = true;
        ctx.dead_hit = false;
        let e = match m.run(ctx, image, job.lr0, &cl) {
            Ok(e) => e,
            // Only the new code goes on to decide on what a call left behind: it knows that
            // the call does not return, the old code did not.
            Err(Stop::Halt) if ctx.dead_hit && side == 1 => {
                return Err(Stop::Unsupported(format!(
                    "{who}: the code after a call decides on a register the call may clobber (the old code does not)"
                )));
            }
            // A machine that breaks the rules on its own: the old code is the reference, so
            // nothing can be said if it does; the new code differs if only it does.
            Err(Stop::Mismatch(why, env)) => {
                let why = format!("{who}: {}", why.replacen("binary ", "", 1));
                return Err(if side == 0 {
                    Stop::Unsupported(why)
                } else {
                    Stop::Mismatch(why, env)
                });
            }
            Err(Stop::Unsupported(why)) => return Err(Stop::Unsupported(format!("{who}: {why}"))),
            Err(e) => return Err(e),
        };
        if let Exit::Call { name } = &e {
            if switch_helper(ctx, image, m, name, helpers)? {
                continue;
            }
            if model_runtime_call(ctx, m, name, helpers) || mem_call(ctx, job, side, m, name, helpers) {
                continue;
            }
        }
        return Ok(e);
    }
}

/// Is `pc`, the return address of a call, past the end of the function that makes the call?
/// The compiler then knew that the callee does not return.
fn last_insn(img: &Image, pc: u32) -> bool {
    let site = pc.wrapping_sub(1);
    // (Padding before a literal pool is not an instruction that follows the call.)
    let mut pc = pc;
    while pc & 2 != 0 && matches!(img.read(pc, 2), Some([0x00, 0xbf] | [0xc0, 0x46])) {
        pc += 2;
    }
    img.is_data_in_code(pc)
        || img.symbols.iter().any(|s| {
            s.kind == SymKind::Func && s.size > 0 && site.wrapping_sub(s.addr) < s.size && pc - s.addr >= s.size
        })
}

/// Entries of the functions some call to which is the last instruction of the caller: the
/// compiler knew that they do not return.
fn never_return(img: &Image) -> HashSet<u32> {
    let mut out = HashSet::new();
    for f in img.symbols.iter().filter(|s| s.kind == SymKind::Func && s.size >= 4) {
        let Some(d) = img.read(f.addr, f.size) else { continue };
        let hw = |i: usize| u16::from_le_bytes([d[i], d[i + 1]]) as u32;
        let mut i = 0usize;
        while i + 2 <= d.len() {
            let at = f.addr + i as u32;
            if img.is_data_in_code(at) {
                i += 2;
                continue;
            }
            let h1 = hw(i);
            if h1 < 0xe800 {
                i += 2;
                continue;
            }
            if i + 4 > d.len() {
                break;
            }
            let h2 = hw(i + 2);
            if h1 & 0xf800 == 0xf000 && h2 & 0xd000 == 0xd000 {
                let s = h1 >> 10 & 1;
                let (i1, i2) = (!(h2 >> 13 ^ s) & 1, !(h2 >> 11 ^ s) & 1);
                let imm = s << 24 | i1 << 23 | i2 << 22 | (h1 & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
                let imm = ((imm << 7) as i32 >> 7) as u32;
                let target = at.wrapping_add(4).wrapping_add(imm);
                if last_insn(img, at + 4) {
                    out.insert(target);
                }
            }
            i += 4;
        }
    }
    out
}

fn describe(e: &Exit) -> String {
    match e {
        Exit::Return => "returns".into(),
        Exit::Trap => "traps".into(),
        Exit::Hang => "loops for ever".into(),
        Exit::Call { name } => format!("calls {name}"),
        Exit::Cut(a) => format!("stops at {a:#x}"),
        Exit::Asm { name, .. } => format!("executes `{name}`"),
    }
}

/// The state of the two machines at an observable point.
struct Pair {
    m: [Machine; 2],
    /// Peripheral accesses already compared.
    io_pos: usize,
    /// Lowest frame offset (from the entry stack pointer) of a stack object whose address a
    /// callee holds.
    escaped: Option<i64>,
}

/// Peripheral accesses and caller-visible memory since the last observable point.
fn compare_effects(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, what: &str) -> R<()> {
    let sp = job.sp;
    let n = p.m[0].io.len().max(p.m[1].io.len());
    for i in p.io_pos..n {
        let show = |ctx: &Ctx, a: &crate::thumb::exec::VolAccess| {
            format!(
                "{} {} byte(s) at {}",
                if a.write { "writes" } else { "reads" },
                a.size,
                ctx.tm.show(a.addr)
            )
        };
        match (p.m[0].io.get(i).cloned(), p.m[1].io.get(i).cloned()) {
            (Some(x), Some(y)) => {
                if x.write != y.write || x.size != y.size || x.addr != y.addr {
                    return Err(Stop::Mismatch(
                        format!(
                            "peripheral access #{} {what}: old {}, new {}",
                            i + 1,
                            show(ctx, &x),
                            show(ctx, &y)
                        ),
                        None,
                    ));
                }
                if x.write {
                    let at = ctx.tm.show(x.addr);
                    prove_same(
                        ctx,
                        sp,
                        x.val,
                        y.val,
                        &format!("value written to the peripheral register at {at} {what}"),
                    )?;
                    facts.always(ctx, x.val);
                    facts.always(ctx, y.val);
                }
            }
            (Some(x), None) => {
                return Err(Stop::Mismatch(
                    format!("peripheral access {what}: old {}, new does not", show(ctx, &x)),
                    None,
                ));
            }
            (None, Some(y)) => {
                return Err(Stop::Mismatch(
                    format!("peripheral access {what}: new {}, old does not", show(ctx, &y)),
                    None,
                ));
            }
            (None, None) => {}
        }
    }
    p.io_pos = n;
    let mut revalued: Option<Vec<crate::sym::Write>> = None;
    let mut seen: HashSet<(T, u8)> = HashSet::new();
    let entries: Vec<(T, u8)> = p.m[0]
        .mem
        .world
        .iter()
        .chain(p.m[1].mem.world.iter())
        .map(|w| (w.addr, w.size))
        .collect();
    for (addr, size) in entries {
        if !seen.insert((addr, size)) || ctx.region(addr).is_some() {
            continue;
        }
        let mut ia = image_init(&sp.da, p.m[0].mem.epoch, None);
        let va = ctx.read_world(&p.m[0].mem.world, addr, size, &mut ia);
        let mut ib = image_init(&sp.db, p.m[1].mem.epoch, None);
        let vb = ctx.read_world(&p.m[1].mem.world, addr, size, &mut ib);
        let at = ctx.tm.show(addr);
        if va != vb && (ctx.mentions_private(va) || ctx.mentions_private(vb)) {
            return Err(Stop::Unsupported(format!(
                "{what}: a stack address is stored at {at} (the extent of stack objects is unknown without the source)"
            )));
        }
        // Pointers the new image stored, read back in parts or through an address that may
        // be another's: with every stored pointer replaced by the old image's pointer to the
        // same thing, the bytes must be the old image's bytes.  (The result is not revalued
        // again: it is in the old image's terms already.)
        if !sp.corr(ctx, va, vb) {
            let log = revalued.get_or_insert_with(|| {
                let mut log = p.m[1].mem.world.clone();
                for w in &mut log {
                    if w.havoc.is_none() && w.size == 4 {
                        w.val = sp.revalue(ctx, w.val, &mut 0);
                    }
                }
                log
            });
            let mut ib = image_init(&sp.db, p.m[1].mem.epoch, None);
            let vr = ctx.read_world(log, addr, size, &mut ib);
            if vr != vb && {
                let e = ctx.tm.eq(va, vr);
                va == vr || ctx.check(e).is_ok()
            } {
                for t in [addr, va, vb] {
                    facts.always(ctx, t);
                }
                continue;
            }
        }
        prove_same(ctx, sp, va, vb, &format!("{what}: {size}-byte value stored at {at}"))?;
        for t in [addr, va, vb] {
            facts.always(ctx, t);
        }
    }
    Ok(())
}

/// Slots of the frame at or above offset `from` that either machine has written.
fn frame_slots(ctx: &mut Ctx, job: &Job, p: &Pair, from: i64) -> Vec<(T, u8)> {
    let sp0 = job.regs[0][13];
    let mut out: Vec<(T, u8)> = Vec::new();
    for m in &p.m {
        let Some(log) = m.mem.private.get(&sp0) else { continue };
        for w in log {
            let keep = match ctx.tm.const_diff(w.addr, sp0) {
                Some(d) => d as u32 as i32 as i64 + w.size as i64 > from,
                None => true,
            };
            if keep && !out.contains(&(w.addr, w.size)) {
                out.push((w.addr, w.size));
            }
        }
    }
    out
}

/// The stack at and above the entry stack pointer when the function is left: without a
/// signature there is no telling the function's own stack arguments from its caller's frame,
/// so whatever either version stored there has to be the same in both.
fn compare_caller_stack(ctx: &mut Ctx, job: &Job, p: &Pair, what: &str) -> R<()> {
    if !job.caller_stack {
        return Ok(());
    }
    let sp0 = job.regs[0][13];
    for (addr, size) in frame_slots(ctx, job, p, 0) {
        let va = frame_read(ctx, job, p, 0, addr, size);
        let vb = frame_read(ctx, job, p, 1, addr, size);
        if va == vb {
            continue;
        }
        let at = match ctx.tm.const_diff(addr, sp0) {
            Some(d) => format!("entry sp+{}", d as u32 as i32),
            None => ctx.tm.show(addr),
        };
        prove_same(
            ctx,
            job.sp,
            va,
            vb,
            &format!("{what}: {size}-byte value in the caller's stack at {at} (assumption caller-stack)"),
        )?;
    }
    Ok(())
}

/// Values a frame slot holds when it keeps a register saved at entry.
fn saved_regs(job: &Job) -> Vec<T> {
    (4..=11)
        .flat_map(|r| [job.regs[0][r], job.regs[1][r]])
        .chain([job.lr0])
        .collect()
}

fn frame_read(ctx: &mut Ctx, job: &Job, p: &Pair, side: usize, addr: T, size: u8) -> T {
    let data = job.sp.data(side).clone();
    let mut init = image_init(&data, p.m[side].mem.epoch, None);
    ctx.mem_read(&p.m[side].mem, addr, size, &mut init)
}

/// The two machines are at a call to `name`: compare what the callee can observe.
fn compare_call(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, name: &str) -> R<()> {
    let sp = job.sp;
    let sp0 = job.regs[0][13];
    for i in 0..ARG_WORDS {
        let (ta, tb) = if i < 4 {
            (p.m[0].regs[i], p.m[1].regs[i])
        } else {
            let off = 4 * (i as u64 - 4);
            let (aa, ab) = (
                ctx.tm.add_const(p.m[0].regs[13], off),
                ctx.tm.add_const(p.m[1].regs[13], off),
            );
            (frame_read(ctx, job, p, 0, aa, 4), frame_read(ctx, job, p, 1, ab, 4))
        };
        for t in [ta, tb] {
            let (m, s) = facts.deps(ctx, t);
            if m != 0 {
                facts.in_arg.insert((name.to_string(), i as u8, m));
            }
            for &id in s.iter() {
                facts.ret_arg.insert((name.to_string(), i as u8, id));
            }
        }
        if i < 4 && (ctx.region(ta).is_some() || ctx.region(tb).is_some()) {
            if ta == tb {
                // The callee gets the address of a stack object.
                let off = match ctx.tm.const_diff(ta, sp0) {
                    Some(d) => d as u32 as i32 as i64,
                    None => i64::MIN,
                };
                p.escaped = Some(p.escaped.map_or(off, |e| e.min(off)));
                continue;
            }
            if ctx.region(ta).is_some() && ctx.region(tb).is_some() {
                return Err(Stop::Unsupported(format!(
                    "the address of a stack object is passed to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
                )));
            }
        }
        if sp.corr(ctx, ta, tb) {
            continue;
        }
        // What an earlier call clobbered, or stack nobody wrote, is not an argument.
        let garbage = |ctx: &Ctx, t: T| match ctx.tm.node(t) {
            Node::Sym(id) => ctx.tm.sym_name(*id).starts_with("clob"),
            Node::Load(epoch, _) => *epoch == crate::sym::UNINIT_EPOCH,
            _ => false,
        };
        if garbage(ctx, ta) || garbage(ctx, tb) {
            for j in i..if i < 4 { i + 1 } else { ARG_WORDS } {
                facts.dead.insert((name.to_string(), j as u8));
            }
            continue;
        }
        let word = if i < 4 {
            format!("r{i}")
        } else {
            format!("sp[{}]", 4 * (i - 4))
        };
        let known = facts.needs.get(name).is_some_and(|n| n.0 >> i & 1 != 0);
        if known {
            continue;
        }
        let what = format!("{word} at the call to {name}");
        if let Some(how) = difference(ctx, sp, ta, tb, &what)? {
            let n = facts.needs.entry(name.to_string()).or_default();
            n.0 |= 1 << i;
            n.1.insert(i as u8, format!("{what}: {how}"));
        }
    }
    // What the callee reaches may itself hold the address of a stack object further down.
    while let Some(from) = p.escaped {
        let mut lowest = from;
        for (addr, size) in frame_slots(ctx, job, p, from) {
            for side in 0..2 {
                let v = frame_read(ctx, job, p, side, addr, size);
                if size == 4 && ctx.region(v).is_some() {
                    lowest = lowest.min(match ctx.tm.const_diff(v, sp0) {
                        Some(d) => d as u32 as i32 as i64,
                        None => i64::MIN,
                    });
                }
            }
        }
        if lowest == from {
            break;
        }
        p.escaped = Some(lowest);
    }
    if let Some(from) = p.escaped {
        // The callee may read the frame: it must hold the same values at the same places.
        if p.m[0].regs[13] != p.m[1].regs[13] {
            return Err(Stop::Unsupported(format!(
                "the address of a stack object is known to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
            )));
        }
        let saved = saved_regs(job);
        for (addr, size) in frame_slots(ctx, job, p, from) {
            let (va, vb) = (
                frame_read(ctx, job, p, 0, addr, size),
                frame_read(ctx, job, p, 1, addr, size),
            );
            if sp.corr(ctx, va, vb) {
                continue;
            }
            // A slot that holds a saved register in one frame only: not the same frame.
            if saved.contains(&va) != saved.contains(&vb) {
                return Err(Stop::Unsupported(format!(
                    "the address of a stack object is known to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
                )));
            }
            if facts.slot_diff.is_some() {
                continue;
            }
            let what = format!(
                "{size} byte(s) of the frame at {} that {name} can reach",
                ctx.tm.show(addr)
            );
            if let Some(how) = difference(ctx, sp, va, vb, &what)? {
                facts.slot_diff = Some(format!("{what}: {how}"));
            }
        }
    }
    Ok(())
}

/// Both machines continue after call number `k`, to `name`.
fn after_call(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, name: &str, k: usize) {
    let lo = ctx.named_sym(&format!("ret{k}:lo:{name}"), 32);
    let hi = ctx.named_sym(&format!("ret{k}:hi:{name}"), 32);
    for (t, high) in [(lo, false), (hi, true)] {
        if let Node::Sym(id) = *ctx.tm.node(t) {
            facts.ret_syms.insert(id, (name.to_string(), high));
        }
    }
    // What the callee may have done to the frame, before the machines forget what lies below
    // their stack pointers.
    let slots = match p.escaped {
        Some(from) => frame_slots(ctx, job, p, from),
        None => Vec::new(),
    };
    for (side, m) in p.m.iter_mut().enumerate() {
        m.finish_call(ctx, 2000 * side + k, Some(lo), Some(hi));
        m.mem.world.clear();
        m.mem.epoch = k as u32 + 1;
    }
    // Every slot the callee can reach holds a new value, the same in both frames; the slots
    // that hold a register saved at entry are not objects of the program.
    let saved = saved_regs(job);
    for (n, (addr, size)) in slots.into_iter().enumerate() {
        let cur = frame_read(ctx, job, p, 0, addr, size);
        if saved.contains(&cur) {
            continue;
        }
        let v = ctx.named_sym(&format!("esc{k}.{n}w{size}"), size * 8);
        for m in p.m.iter_mut() {
            ctx.mem_write(&mut m.mem, addr, size, v);
        }
    }
}

fn run_path(ctx: &mut Ctx, job: &Job, facts: &mut Facts) -> R<()> {
    let sp = job.sp;
    let mk = |ctx: &mut Ctx, side: usize| {
        let mut m = Machine::new(ctx, job.entry[side], job.regs[side]);
        let layout = sp.layout.clone();
        let values = sp.values.clone();
        m.remap = Some(Remap {
            // What the new code compares is compared as the old image's pointer to the same
            // thing: an input is the same pointer for both.
            value: if side == 0 {
                Arc::new(|_: &mut Ctx, t: T| t)
            } else {
                Arc::new(move |ctx: &mut Ctx, t: T| values.revalue(ctx, t, &mut 0))
            },
            addr: if side == 0 {
                Arc::new(|_: &mut Ctx, t: T| t)
            } else {
                Arc::new(move |ctx: &mut Ctx, t: T| layout.translate(ctx, t))
            },
            data: sp.data(side).clone(),
        });
        m.mmio = sp.mmio.clone();
        m.stack_top = job.stack.iter().map(|a| a.0 + 4).max().unwrap_or(0);
        // The garbage one machine finds below its stack pointer is not the other's.
        m.clobbers = (side as u32) << 20;
        for &(off, v) in &job.stack {
            let a = ctx.tm.add_const(job.regs[side][13], off as u64);
            ctx.mem_write(&mut m.mem, a, 4, v);
        }
        m
    };
    let mut p = Pair {
        m: [mk(ctx, 0), mk(ctx, 1)],
        io_pos: 0,
        escaped: None,
    };
    let mut helpers = [0usize, 2000];
    let mut k = 0usize;
    let mut last: Option<String> = None;
    loop {
        let [ma, mb] = &mut p.m;
        let ea = match run_side(ctx, job, facts, 0, ma, &mut helpers[0]) {
            // Code that decides on what a call left in a scratch register is not reached:
            // the call does not return, and nothing after it is compared.
            Err(Stop::Halt) if ctx.dead_hit => {
                if let Some(callee) = last.take() {
                    facts.stuck.insert(callee);
                }
                return Err(Stop::Halt);
            }
            r => r?,
        };
        let eb = run_side(ctx, job, facts, 1, mb, &mut helpers[1])?;
        match (&ea, &eb) {
            (Exit::Return, Exit::Return) => {
                compare_effects(ctx, job, facts, &mut p, "at return")?;
                compare_caller_stack(ctx, job, &p, "at return")?;
                for r in (4..=11).chain([13]) {
                    let (fa, fb) = (p.m[0].regs[r], p.m[1].regs[r]);
                    if fa == job.regs[0][r] && fb == job.regs[1][r] {
                        continue;
                    }
                    let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
                    prove_same(ctx, sp, fa, fb, &format!("callee-saved register {name} at return"))?;
                }
                // A register both sides leave holding what a call clobbered is no result.
                let garbage = |ctx: &Ctx, t: T| matches!(ctx.tm.node(t), Node::Sym(id) if ctx.tm.sym_name(*id).starts_with("clob"));
                let (a0, b0) = (p.m[0].regs[0], p.m[1].regs[0]);
                if facts.ret0_diff.is_none()
                    && !(garbage(ctx, a0) && garbage(ctx, b0))
                    && let Some(how) = difference(ctx, sp, a0, b0, "r0 at return")?
                {
                    facts.ret0_diff = Some(format!("r0 at return: {how}"));
                }
                let (a1, b1) = (p.m[0].regs[1], p.m[1].regs[1]);
                if !facts.ret1_diff && !(garbage(ctx, a1) && garbage(ctx, b1)) && !sp.corr(ctx, a1, b1) {
                    let e = ctx.tm.eq(a1, b1);
                    facts.ret1_diff = !ctx.implied(e);
                }
                for t in [a0, b0] {
                    let (m, s) = facts.deps(ctx, t);
                    facts.in_r0 |= m;
                    facts.ret_r0.extend(s.iter().copied());
                }
                for t in [a1, b1] {
                    let (m, s) = facts.deps(ctx, t);
                    facts.in_r1 |= m;
                    facts.ret_r1.extend(s.iter().copied());
                }
                break;
            }
            (Exit::Trap, Exit::Trap) => {
                compare_effects(ctx, job, facts, &mut p, "at trap")?;
                compare_caller_stack(ctx, job, &p, "at trap")?;
                break;
            }
            (Exit::Hang, Exit::Hang) => {
                compare_effects(ctx, job, facts, &mut p, "at the endless loop")?;
                compare_caller_stack(ctx, job, &p, "at the endless loop")?;
                break;
            }
            (Exit::Call { name: na }, Exit::Call { name: nb }) if na == nb => {
                let what = format!("at call #{} ({na})", k + 1);
                if let (Some(ta), Some(tb)) = (p.m[0].indirect.take(), p.m[1].indirect.take()) {
                    // A jump through what a call left in a scratch register: likewise.
                    if ctx.mentions_garbage(ta) && last.is_some() {
                        facts.stuck.extend(last.take());
                        return Err(Stop::Halt);
                    }
                    prove_same(ctx, sp, ta, tb, &format!("target of the call through a pointer {what}"))?;
                    facts.always(ctx, ta);
                    facts.always(ctx, tb);
                }
                compare_effects(ctx, job, facts, &mut p, &what)?;
                compare_call(ctx, job, facts, &mut p, na)?;
                if sp.paired.contains_key(na.as_str()) {
                    facts.calls.insert(na.clone());
                }
                if NORETURN.contains(&na.as_str())
                    || sp.noreturn.contains(na.as_str())
                    || (0..2).any(|s| last_insn(sp.image(s), p.m[s].resume_pc()))
                {
                    break;
                }
                after_call(ctx, job, facts, &mut p, na, k);
                last = Some(na.clone());
                k += 1;
            }
            (
                Exit::Asm {
                    name: na,
                    arg: aa,
                    out: oa,
                },
                Exit::Asm {
                    name: nb,
                    arg: ab,
                    out: ob,
                },
            ) if na == nb && aa.is_some() == ab.is_some() && oa.is_some() == ob.is_some() => {
                // A system instruction: the same one on both sides, with everything observable
                // done before it in place, the same value written and the same unknown value read.
                let what = format!("at `{na}` (event #{})", k + 1);
                compare_effects(ctx, job, facts, &mut p, &what)?;
                if let (Some(va), Some(vb)) = (*aa, *ab) {
                    prove_same(ctx, sp, va, vb, &format!("value written {what}"))?;
                }
                if let (Some(ra), Some(rb)) = (*oa, *ob) {
                    let v = ctx.named_sym(&format!("ret{k}:asm:{na}"), 32);
                    p.m[0].regs[ra as usize] = v;
                    p.m[1].regs[rb as usize] = v;
                }
                k += 1;
            }
            _ => {
                if path_needs_overlap(ctx) {
                    if ctx.notes.len() < 4 {
                        ctx.notes.push(format!(
                            "after {k} matching call(s): old {}, new {}",
                            describe(&ea),
                            describe(&eb)
                        ));
                    }
                    return Err(Stop::Halt);
                }
                for e in [&ea, &eb] {
                    if let Exit::Call { name } = e
                        && sp.paired.contains_key(name.as_str())
                    {
                        facts.culprits.insert(name.clone());
                    }
                }
                // An input that takes this path.
                let f = ctx.tm.fals();
                let on = match ctx.check(f) {
                    Err(Some(env)) => format!(" for {}", witness(ctx, &env)),
                    _ => String::new(),
                };
                return Err(Stop::Mismatch(
                    format!(
                        "after {k} matching call(s): old {}, new {}{on}",
                        describe(&ea),
                        describe(&eb)
                    ),
                    None,
                ));
            }
        }
    }
    for c in ctx.pc.clone() {
        facts.always(ctx, c);
    }
    Ok(())
}

/// Result of comparing one function in one mode.
struct Raw {
    verdict: Verdict,
    facts: Facts,
    inline: bool,
    paths: usize,
    millis: u128,
    /// The counterexamples met, and whether calls were followed when they were.
    models: Vec<(replay::Model, bool)>,
}

/// The functions and the objects a function of the source names.
type SrcRefs = (BTreeSet<String>, BTreeSet<String>);

/// What two sources say differently, and what each function of them depends on.
///
/// Definitions are compared as parsed (after preprocessing, with the types they use), without
/// their positions: white space, comments and the place of a definition in its file are no
/// change, a changed macro or type that the definition uses is one.  A function written in
/// assembly (or with a body the front end has no meaning for) is compared by its text.
struct SrcDelta {
    /// Functions defined differently (or by one source only), and how.
    changed: BTreeMap<String, &'static str>,
    /// Objects defined differently.
    objects: BTreeSet<String>,
    /// Functions whose callers may rely on something that differs: the signature, what is
    /// declared about them (noreturn, returns twice, restrict), what the sources show (a
    /// parameter only borrowed or returned unchanged, a result nobody uses, the argument
    /// values their callers pass).
    interface: BTreeSet<String>,
    /// For each source, by function name: the functions and the objects its bodies name.
    refs: [HashMap<String, SrcRefs>; 2],
    /// For each source, by object name: the objects and functions its initial value names.
    obj_refs: [HashMap<String, BTreeSet<String>>; 2],
}

const CHANGED: &str = "CHANGED IN SOURCE";
const CHANGED_LINES: &str = "CHANGED IN SOURCE (line numbers and file names only)";

impl SrcDelta {
    /// Is `name`, whose definition is unchanged and which matches its source in both images,
    /// equivalent through the source?  `events`: for each image, the functions its proof
    /// compared as calls instead of following them.  The proof of a caller depends on such a
    /// callee through its interface only, so a change in the callee's body is none of the
    /// caller's; a callee that was followed is part of what was proved.
    fn through_source(&self, name: &str, events: [&HashSet<&str>; 2]) -> Result<(), String> {
        for side in 0..2 {
            let mut seen: BTreeSet<&str> = BTreeSet::new();
            let mut objs: BTreeSet<&str> = BTreeSet::new();
            let mut work = vec![name];
            while let Some(f) = work.pop() {
                if !seen.insert(f) {
                    continue;
                }
                if self.interface.contains(f) {
                    return Err(if f == name {
                        "what its callers may rely on differs between the sources".to_string()
                    } else {
                        format!("what the callers of {f} may rely on differs between the sources")
                    });
                }
                if f != name && events[side].contains(f) {
                    continue;
                }
                if let Some(how) = self.changed.get(f) {
                    return Err(if f == name {
                        how.to_string()
                    } else {
                        format!("has the code of {f} in place, which is changed in the source")
                    });
                }
                let Some((callees, globals)) = self.refs[side].get(f) else {
                    continue;
                };
                work.extend(callees.iter().map(|c| c.as_str()));
                objs.extend(globals.iter().map(|g| g.as_str()));
            }
            // The objects it names, and those their initial values lead to.
            let mut work: Vec<&str> = objs.into_iter().collect();
            let mut seen: BTreeSet<&str> = BTreeSet::new();
            while let Some(g) = work.pop() {
                if !seen.insert(g) {
                    continue;
                }
                if self.objects.contains(g) {
                    return Err(format!("uses {g}, which is defined differently in the two sources"));
                }
                if let Some(next) = self.obj_refs[side].get(g) {
                    work.extend(next.iter().map(|c| c.as_str()));
                }
            }
        }
        Ok(())
    }
}

/// The text of a definition the front end did not read (assembly): from its first line to the
/// next definition of the file, without comments and with white space collapsed.
fn source_text(p: &Program, f: &crate::c::ast::Func) -> Option<String> {
    let file = p.files.get(f.loc.file as usize)?;
    let text = std::fs::read_to_string(file).ok()?;
    let next = (p.funcs.iter().map(|g| g.loc))
        .chain(p.globals.iter().map(|g| g.loc))
        .filter(|l| l.file == f.loc.file && l.line > f.loc.line)
        .map(|l| l.line)
        .min();
    let mut o = String::new();
    let mut in_comment = false;
    for (i, line) in text.lines().enumerate() {
        let n = i as u32 + 1;
        if n < f.loc.line || next.is_some_and(|e| n >= e) {
            continue;
        }
        let mut rest = line;
        loop {
            if in_comment {
                match rest.find("*/") {
                    Some(j) => {
                        rest = &rest[j + 2..];
                        in_comment = false;
                    }
                    None => break,
                }
            }
            let (a, b) = (rest.find("/*"), rest.find("//"));
            match (a, b) {
                (Some(a), b) if b.is_none_or(|b| a < b) => {
                    o.push_str(&rest[..a]);
                    o.push(' ');
                    rest = &rest[a + 2..];
                    in_comment = true;
                }
                (_, Some(b)) => {
                    o.push_str(&rest[..b]);
                    break;
                }
                _ => {
                    o.push_str(rest);
                    break;
                }
            }
        }
        o.push(' ');
    }
    Some(o.split_whitespace().collect::<Vec<_>>().join(" "))
}

fn source_delta(pa: &Program, pb: &Program) -> SrcDelta {
    fn type_shape(p: &Program, t: u32, depth: u8, memo: &mut HashMap<(u32, u8), String>) -> String {
        use crate::c::ast::Type;
        let key = (t, depth.min(2));
        if let Some(s) = memo.get(&key) {
            return s.clone();
        }
        let s = match p.ty(t) {
            Type::Ptr(u) => format!("*{}", type_shape(p, *u, depth + 1, memo)),
            Type::Array(u, n) => format!("[{n:?}]{}", type_shape(p, *u, depth, memo)),
            Type::Func(ft) => {
                let ps: Vec<String> = ft.params.iter().map(|&x| type_shape(p, x, depth + 1, memo)).collect();
                format!(
                    "fn({};{}{})",
                    type_shape(p, ft.ret, depth + 1, memo),
                    ps.join(","),
                    if ft.variadic { ",..." } else { "" }
                )
            }
            Type::Record(r) => {
                let rec = &p.records[*r as usize];
                let mut o = format!("rec {:?} {} {}", rec.name, rec.size, rec.align);
                if depth < 2 {
                    for f in &rec.fields {
                        let _ = write!(
                            o,
                            " {}@{}{:?}:{}",
                            f.name,
                            f.offset,
                            f.bits,
                            type_shape(p, f.ty, depth + 1, memo)
                        );
                    }
                }
                format!("{{{o}}}")
            }
            other => format!("{other:?}"),
        };
        memo.insert(key, s.clone());
        s
    }
    // Something parsed, with what it refers to by number spelled out and without positions
    // and coverage points.  `lines`: numbers in this range are written as a line number
    // (what `__LINE__` gave), and a string that is the name of a source file as a file name.
    let spell = |p: &Program, text: &str, lines: Option<(u32, u32)>, memo: &mut HashMap<(u32, u8), String>| -> String {
        let mut o = String::new();
        let b = text.as_bytes();
        let mut i = 0;
        let id = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
        'scan: while i < b.len() {
            if text[i..].starts_with("Loc {") {
                i += text[i..].find('}').map_or(text.len() - i, |j| j + 1);
                continue;
            }
            if i == 0 || !id(b[i - 1]) {
                for key in ["ty: ", "term_cov: ", "cov: ", "Str(", "Global(", "Func("] {
                    if !text[i..].starts_with(key) {
                        continue;
                    }
                    let from = i + key.len();
                    let n = b[from..].iter().take_while(|c| c.is_ascii_digit()).count();
                    let Ok(v) = text[from..from + n].parse::<usize>() else {
                        continue;
                    };
                    o.push_str(key);
                    match key {
                        "ty: " => o.push_str(&type_shape(p, v as u32, 0, memo)),
                        "Str(" => match p.strings.get(v) {
                            Some(s) if lines.is_some() && p.files.iter().any(|f| f.as_bytes() == &**s) => {
                                o.push_str("<file>")
                            }
                            s => {
                                let _ = write!(o, "{s:?}");
                            }
                        },
                        "Global(" => o.push_str(p.globals.get(v).map_or("?", |g| &g.name)),
                        "Func(" => o.push_str(p.funcs.get(v).map_or("?", |g| &g.name)),
                        _ => {}
                    }
                    i = from + n;
                    continue 'scan;
                }
            }
            let c = text[i..].chars().next().unwrap();
            o.push(c);
            i += c.len_utf8();
        }
        o
    };
    // The lines a definition extends over, from the positions in it.
    let extent = |text: &str, first: u32| -> (u32, u32) {
        let mut last = first;
        let mut rest = text;
        while let Some(i) = rest.find("line: ") {
            rest = &rest[i + 6..];
            let n = rest.bytes().take_while(|c| c.is_ascii_digit()).count();
            if let Ok(v) = rest[..n].parse::<u32>() {
                last = last.max(v);
            }
        }
        (first, last)
    };
    // (exact, with line numbers and file names blanked)
    let shape = |p: &Program, f: &crate::c::ast::Func, memo: &mut HashMap<(u32, u8), String>| -> (String, String) {
        let params: Vec<String> = f.ty.params.iter().map(|&x| type_shape(p, x, 0, memo)).collect();
        let head = format!(
            "fn({};{};{}) {} {} {} {} {} ",
            type_shape(p, f.ty.ret, 0, memo),
            params.join(","),
            f.ty.variadic,
            f.is_static,
            f.is_inline,
            f.nparams,
            f.variadic_def,
            f.opaque
        );
        let body = format!("{:?} {:?}", f.locals, f.body);
        if f.opaque || f.unsupported.is_some() {
            // Not read by the front end: its text decides.
            let text = source_text(p, f).unwrap_or_else(|| {
                let why = f.unsupported.as_deref().unwrap_or("");
                format!("{body} {}", why.split_once(": ").map_or(why, |w| w.1))
            });
            let s = format!("{head}{text}");
            return (s.clone(), s);
        }
        let lines = extent(&body, f.loc.line);
        let exact = format!("{head}{}", spell(p, &body, None, memo));
        // Numbers that are lines of the definition, written as such.
        let loose = spell(p, &body, Some(lines), memo);
        let mut blank = String::with_capacity(loose.len());
        let b = loose.as_bytes();
        let mut i = 0;
        while i < b.len() {
            if b[i].is_ascii_digit() && (i == 0 || !(b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) {
                let n = b[i..].iter().take_while(|c| c.is_ascii_digit()).count();
                let end = i + n;
                let word = end < b.len() && (b[end].is_ascii_alphanumeric() || b[end] == b'_');
                match loose[i..end].parse::<u32>() {
                    Ok(v) if !word && v >= lines.0 && v <= lines.1 => blank.push_str("<line>"),
                    _ => blank.push_str(&loose[i..end]),
                }
                i = end;
            } else {
                let c = loose[i..].chars().next().unwrap();
                blank.push(c);
                i += c.len_utf8();
            }
        }
        (exact, format!("{head}{blank}"))
    };
    type Defs = BTreeMap<String, (Vec<String>, Vec<String>)>;
    let defs = |p: &Program| -> Defs {
        let mut m: Defs = BTreeMap::new();
        let mut memo = HashMap::new();
        for f in p.funcs.iter().filter(|f| f.body.is_some() || f.opaque) {
            let (exact, loose) = shape(p, f, &mut memo);
            let e = m.entry(f.name.to_string()).or_default();
            e.0.push(exact);
            e.1.push(loose);
        }
        for v in m.values_mut() {
            v.0.sort();
            v.0.dedup();
            v.1.sort();
            v.1.dedup();
        }
        m
    };
    let (da, db) = (defs(pa), defs(pb));
    let mut changed: BTreeMap<String, &'static str> = BTreeMap::new();
    for n in da.keys().chain(db.keys()) {
        match (da.get(n), db.get(n)) {
            (Some(x), Some(y)) if x.0 == y.0 => {}
            (Some(x), Some(y)) if x.1 == y.1 => {
                changed.insert(n.clone(), CHANGED_LINES);
            }
            _ => {
                changed.insert(n.clone(), CHANGED);
            }
        }
    }
    // Objects: type, qualifiers, initial value.
    let objects_of = |p: &Program| -> BTreeMap<String, Vec<String>> {
        let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let mut memo = HashMap::new();
        for g in p.globals.iter().filter(|g| g.defined) {
            let text = format!(
                "{} {} {} {} {} {:?}",
                type_shape(p, g.ty, 0, &mut memo),
                g.is_static,
                g.is_local_static,
                g.is_const,
                g.is_volatile,
                g.init
            );
            let text = spell(p, &text, None, &mut memo);
            m.entry(g.name.to_string()).or_default().push(text);
        }
        for v in m.values_mut() {
            v.sort();
            v.dedup();
        }
        m
    };
    let (oa, ob) = (objects_of(pa), objects_of(pb));
    let objects: BTreeSet<String> = (oa.keys().chain(ob.keys()))
        .filter(|n| oa.get(*n) != ob.get(*n))
        .cloned()
        .collect();
    // What callers may rely on.
    let interface_of = |p: &Program| -> BTreeMap<String, Vec<String>> {
        let borrowed = crate::c::borrow::borrowed_params(p);
        let callers = crate::c::callers::callers(p);
        let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let mut memo = HashMap::new();
        for (i, f) in p.funcs.iter().enumerate() {
            let params: Vec<String> = f.ty.params.iter().map(|&x| type_shape(p, x, 0, &mut memo)).collect();
            let mut restrict: Vec<u32> = (p.restrict_params.iter())
                .filter(|r| r.0 == i as u32)
                .map(|r| r.1)
                .collect();
            restrict.sort();
            let mut who: Vec<&str> = (callers.callers.get(i).into_iter().flatten())
                .map(|c| &*p.funcs[*c as usize].name)
                .collect();
            who.sort();
            who.dedup();
            let private = callers.private.get(i).copied().unwrap_or(false);
            let text = format!(
                "fn({};{};{}) body {} static {} opaque {} noreturn {} twice {} restrict {restrict:?} borrowed {:?} given {:?} private {private} callers {:?} unused {:?} returns {:?}",
                type_shape(p, f.ty.ret, 0, &mut memo),
                params.join(","),
                f.ty.variadic,
                f.body.is_some(),
                f.is_static,
                f.opaque,
                p.noreturn.contains(&f.name),
                p.returns_twice.contains(&f.name),
                borrowed.get(i),
                callers.given.get(i),
                // Who calls a function matters where it is only meaningful with its callers.
                if private { who } else { Vec::new() },
                callers.result_unused.get(i),
                p.returns_param(i as u32),
            );
            m.entry(f.name.to_string()).or_default().push(text);
        }
        for v in m.values_mut() {
            v.sort();
            v.dedup();
        }
        m
    };
    let (ia, ib) = (interface_of(pa), interface_of(pb));
    let interface: BTreeSet<String> = (ia.keys().chain(ib.keys()))
        .filter(|n| ia.get(*n) != ib.get(*n))
        .cloned()
        .collect();
    let refs_of = |p: &Program| {
        let mut m: HashMap<String, SrcRefs> = HashMap::new();
        for (i, f) in p.funcs.iter().enumerate() {
            let sig = crate::discover::matcher::refs(p, i as u32);
            let e = m.entry(f.name.to_string()).or_default();
            e.0.extend(sig.callees.iter().map(|c| p.funcs[*c as usize].name.to_string()));
            e.1.extend(sig.globals.iter().map(|g| p.globals[*g as usize].name.to_string()));
        }
        m
    };
    let obj_refs_of = |p: &Program| {
        let mut m: HashMap<String, BTreeSet<String>> = HashMap::new();
        for g in &p.globals {
            let e = m.entry(g.name.to_string()).or_default();
            for (_, t, _) in g.init.iter().flat_map(|i| &i.relocs) {
                if let crate::c::ast::SymRef::Global(x) = t {
                    e.insert(p.globals[*x as usize].name.to_string());
                }
            }
        }
        m
    };
    SrcDelta {
        changed,
        objects,
        interface,
        refs: [refs_of(pa), refs_of(pb)],
        obj_refs: [obj_refs_of(pa), obj_refs_of(pb)],
    }
}

/// Most functions followed one at a time before every call is followed.
const MAX_FOLLOWED: usize = 8;

/// Calls matched one to one; where one image calls a function and the other does something
/// else (it has the function's code in place, say), that function is followed on both sides
/// and the comparison starts again.
fn analyse_calls(sp: &Space, entry: [u32; 2], opts: &Options) -> Raw {
    let mut follow: HashSet<String> = HashSet::new();
    loop {
        let r = analyse(sp, entry, false, &follow, opts);
        if std::env::var_os("CVERIF_DEBUG").is_some() {
            eprintln!("compare: {:#x} following {follow:?}: {:?}", entry[0], r.verdict);
        }
        let more: Vec<String> = match &r.verdict {
            Verdict::Different(_) => r
                .facts
                .culprits
                .iter()
                .filter(|c| !follow.contains(*c))
                .cloned()
                .collect(),
            _ => Vec::new(),
        };
        if more.is_empty() || follow.len() + more.len() > MAX_FOLLOWED {
            return r;
        }
        follow.extend(more);
    }
}

fn analyse(sp: &Space, entry: [u32; 2], inline: bool, follow: &HashSet<String>, opts: &Options) -> Raw {
    let v = &opts.verify;
    let start = Instant::now();
    MODELS.with(|m| m.borrow_mut().clear());
    let mut ctx = Ctx::new(v.limits);
    if v.check_solver {
        ctx.prover = crate::bv::Prover::new_checked();
    }
    let mut deadline = start + v.time_limit;
    if let Some(d) = v.deadline {
        deadline = deadline.min(d);
    }
    ctx.set_budget(v.work_limit, v.max_terms, Some(deadline));
    ctx.track_overlaps = true;
    ctx.prover.rom = sp
        .db
        .segments
        .iter()
        .filter(|s| !s.writable)
        .map(|s| (s.addr, s.data.clone()))
        .collect();
    let mut facts = Facts::default();
    let mut shared = [0 as T; 16];
    for (i, r) in shared.iter_mut().enumerate().take(13) {
        *r = ctx.named_sym(&format!("r{i}"), 32);
        if i < 4 {
            facts.inputs.insert(*r, 1 << i);
        }
    }
    shared[13] = ctx.private_base("SP0");
    shared[14] = ctx.named_sym("LR0", 32);
    shared[15] = ctx.tm.konst(32, 0);
    let mut regs = [shared, shared];
    for (side, r) in regs.iter_mut().enumerate() {
        if let Some(sb) = sp.image(side).static_base {
            r[9] = ctx.tm.konst(32, sb as u64);
        }
    }
    let mut stack = Vec::new();
    for i in 0..8u32 {
        let s = ctx.named_sym(&format!("stk{}", 4 * i), 32);
        if i < 4 {
            facts.inputs.insert(s, 1 << (4 + i));
        }
        stack.push((4 * i, s));
    }
    let bits = if opts.assume.sp_aligned { 3 } else { 2 };
    let low = ctx.tm.extract(shared[13], 0, bits);
    let z = ctx.tm.konst(bits, 0);
    let pre = vec![ctx.tm.eq(low, z)];
    let job = Job {
        sp,
        entry,
        regs,
        lr0: shared[14],
        stack,
        inline,
        follow,
        caller_stack: opts.assume.caller_stack,
    };
    let mut verdict = Verdict::Equivalent;
    let mut bounded: Option<String> = None;
    let mut inconclusive: Option<String> = None;
    let mut explored = 0usize;
    let mut paths = 0usize;
    let mut best_paths = 0usize;
    let mut steps = 0u64;
    let step_budget = v.work_limit.saturating_mul(10).max(200_000);
    let max_depth = v.limits.max_depth;
    let mut schedule: Vec<usize> = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32]
        .into_iter()
        .filter(|&d| d < max_depth)
        .collect();
    schedule.push(max_depth);
    'rounds: for (round, &depth) in schedule.iter().enumerate() {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        let mut depth_hit = false;
        inconclusive = None;
        paths = 0;
        loop {
            ctx.restart(&pre);
            explored += 1;
            match run_path(&mut ctx, &job, &mut facts) {
                Ok(()) => paths += 1,
                Err(Stop::Undefined) | Err(Stop::Halt) => {}
                Err(Stop::Truncated(why)) => {
                    if why == "branch depth limit" {
                        depth_hit = true;
                    } else {
                        bounded.get_or_insert(why);
                    }
                }
                Err(Stop::Inconclusive(why)) => match ctx.check_deadline() {
                    Err(Stop::Truncated(limit)) => {
                        bounded.get_or_insert(limit);
                    }
                    _ => {
                        inconclusive.get_or_insert(why);
                    }
                },
                Err(Stop::Mismatch(why, _)) => {
                    verdict = Verdict::Different(why);
                    break 'rounds;
                }
                Err(Stop::Unsupported(why)) => {
                    verdict = Verdict::Unsupported(why);
                    break 'rounds;
                }
            }
            best_paths = best_paths.max(paths);
            // Instructions on constants build no terms and cost the work budget nothing.
            steps += ctx.steps;
            if steps > step_budget {
                bounded.get_or_insert_with(|| "step budget".into());
                break 'rounds;
            }
            if let Err(Stop::Truncated(limit)) = ctx.check_deadline() {
                bounded.get_or_insert(limit);
                break 'rounds;
            }
            if explored >= v.limits.max_paths {
                bounded.get_or_insert_with(|| "path limit".into());
                break 'rounds;
            }
            if !ctx.next_path() {
                break;
            }
        }
        if !depth_hit {
            break;
        }
        if round + 1 == schedule.len() {
            bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
        }
    }
    let paths = paths.max(best_paths);
    if verdict == Verdict::Equivalent {
        if let Some(why) = inconclusive {
            verdict = Verdict::Inconclusive(why);
        } else if let Some(why) = bounded {
            verdict = Verdict::Bounded(format!("{why}; {paths} paths compared"));
        }
    }
    facts.overlap = ctx.notes.first().cloned();
    Raw {
        verdict,
        facts,
        inline,
        paths,
        millis: start.elapsed().as_millis(),
        models: MODELS.with(|m| {
            (m.borrow_mut().drain(..))
                .map(|mut m| {
                    m.inline = inline;
                    m.follow = follow.iter().cloned().collect();
                    (m, inline)
                })
                .collect()
        }),
    }
}

/// The verdict covers every path: what the paths established can be relied upon.
fn complete(v: &Verdict) -> bool {
    matches!(v, Verdict::Equivalent)
}

// ----- data ---------------------------------------------------------------------------

fn compare_data(sp: &Space, out: &mut Comparison) {
    // Labels and what the compiler generates (switch tables) are no objects of the program:
    // the code that uses them is compared.
    let local = |n: &str| {
        n.starts_with(".L") || n.starts_with("__") || n.starts_with("CSWTCH.") || n.starts_with("switch.table")
    };
    for (name, x, y) in &sp.obj_pairs {
        if local(name) {
            continue;
        }
        out.data_checked += 1;
        if x.size != y.size {
            out.data.push((
                name.clone(),
                format!("size {} in the old image, {} in the new", x.size, y.size),
            ));
            continue;
        }
        let (Some(xs), Some(ys)) = (sp.a.read(x.addr, x.size), sp.b.read(y.addr, y.size)) else {
            continue;
        };
        if let Some((off, wa, wb)) = first_difference(sp.a, sp.b, &sp.layout, xs, ys) {
            out.data.push((
                name.clone(),
                format!("initial contents differ at offset {off}: old {wa:#x}, new {wb:#x}"),
            ));
        }
    }
    let (oa, ob) = (objects(sp.a), objects(sp.b));
    let only = |l: &[Named], other: &[Named]| -> Vec<String> {
        let mut v: Vec<String> = l
            .iter()
            .filter(|o| !local(&o.name) && !other.iter().any(|p| p.name == o.name))
            .map(|o| o.name.clone())
            .collect();
        v.sort();
        v.dedup();
        v
    };
    out.data_removed = only(&oa, &ob);
    out.data_added = only(&ob, &oa);
}

// ----- the whole comparison -----------------------------------------------------------------

thread_local! {
    static REPLAY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// `compare`, with the counterexample of every DIFFERENT verdict run on both functions by
/// the reference interpreter (`FuncDiff::replay`).
pub fn compare_replayed(a: &Image, b: &Image, src: Option<(&Program, &Program)>, opts: &Options) -> Comparison {
    REPLAY.with(|r| r.set(true));
    let c = compare(a, b, src, opts);
    REPLAY.with(|r| r.set(false));
    c
}

/// Compare two images.  With `src` (the source parsed for the old and for the new image) every
/// function is first verified against the source on both sides.
pub fn compare(a: &Image, b: &Image, src: Option<(&Program, &Program)>, opts: &Options) -> Comparison {
    let mut sp = Space::new(a, b, &opts.verify.mmio);
    sp.explain = opts.explain;
    let mut out = Comparison {
        assume: opts.assume.clone(),
        with_source: src.is_some(),
        ..Default::default()
    };
    compare_data(&sp, &mut out);
    let wanted = |n: &str| opts.verify.only.is_empty() || opts.verify.only.iter().any(|o| o == n);

    // Three-way: both images against the source.
    let mut by_source: HashMap<String, (Verdict, String)> = HashMap::new();
    let mut voids: HashMap<String, bool> = HashMap::new();
    // Functions the source has that match it on both sides as far as they were explored, or
    // on which the source check said nothing: (no mismatch, some bound).
    let mut in_source: HashMap<String, (bool, bool)> = HashMap::new();
    let mut src_diff: HashMap<String, (String, &'static str)> = HashMap::new();
    // With a source for each image: what "both match the source" says about a function
    // holds only where the two sources say the same.
    let delta = src.map(|(pa, pb)| source_delta(pa, pb));
    // The same instructions, whose call targets and address constants designate the same
    // things: nothing to tell the two apart, and nothing to explore or to prove.
    let same_code: HashSet<&String> = (sp.paired.iter())
        .filter(|(_, [ea, eb])| {
            let size = |img: &Image, e: u32| img.func_at(e).map_or(0, |s| s.size);
            let (sa, sb) = (size(a, *ea), size(b, *eb));
            sa == sb && same_instructions(&sp, *ea, *eb, sa)
        })
        .map(|(n, _)| n)
        .collect();
    let lazy = std::env::var_os("CVERIF_COMPARE_FULL").is_none();
    let mut src_status: HashMap<String, String> = HashMap::new();
    // Callees of a function settled through the source that its proofs compared as calls.
    let mut src_events: HashMap<String, Vec<String>> = HashMap::new();
    if let (Some((pa, pb)), Some(delta)) = (src, &delta) {
        out.source_changed = delta.changed.keys().cloned().collect();
        // Only what the instructions do not settle is checked against the source.
        let mut vopts = opts.verify.clone();
        let mut none = false;
        if lazy && vopts.only.is_empty() {
            let (mut rest, mut left_out) = (BTreeSet::new(), 0);
            for f in pa.funcs.iter().chain(pb.funcs.iter()).filter(|f| f.body.is_some()) {
                if same_code.contains(&f.name.to_string()) {
                    left_out += 1;
                } else {
                    rest.insert(f.name.to_string());
                }
            }
            if left_out > 0 {
                none = rest.is_empty();
                vopts.only = rest.into_iter().collect();
                out.source_unchecked = same_code.len();
            }
        }
        let (ra, rb) = if none {
            Default::default()
        } else {
            (verify(pa, a, &vopts), verify(pb, b, &vopts))
        };
        for f in pa.funcs.iter().filter(|f| f.body.is_some()) {
            voids.insert(f.name.to_string(), f.ty.ret == VOID);
        }
        for fa in &ra.funcs {
            let Some(fb) = rb.funcs.iter().find(|f| f.name == fa.name) else {
                continue;
            };
            fn events(r: &crate::verify::FuncReport) -> HashSet<&str> {
                r.modulo.iter().map(|m| m.0.as_str()).collect()
            }
            let (ea, eb) = (events(fa), events(fb));
            if let Err(how) = delta.through_source(&fa.name, [&ea, &eb]) {
                // Each image against its own source says nothing about the two together:
                // the machine code decides.
                let word = |s: &Status| match s {
                    Status::Proved => "PROVED".to_string(),
                    Status::Bounded(_) => "BOUNDED".to_string(),
                    Status::Mismatch(why) => format!("MISMATCH ({why})"),
                    _ => "not established".to_string(),
                };
                if !delta.changed.contains_key(&fa.name) {
                    out.source_affected.push(fa.name.clone());
                }
                src_status.insert(
                    fa.name.clone(),
                    format!(
                        "{how}; against its own source the old image is {}, the new image is {}",
                        word(&fa.status),
                        word(&fb.status)
                    ),
                );
                continue;
            }
            let mut called: Vec<String> = ea.union(&eb).map(|c| c.to_string()).collect();
            called.sort();
            src_events.insert(fa.name.clone(), called);
            let r = match (&fa.status, &fb.status) {
                (Status::Proved, Status::Proved) => (
                    Verdict::Equivalent,
                    if delta.changed.is_empty() {
                        "both match the source".to_string()
                    } else {
                        "both match the source, which says the same in both versions".to_string()
                    },
                ),
                // One side does not match the source.  The source side follows calls, so the
                // difference may lie in a callee: the machine code is compared as well.
                (Status::Proved, Status::Mismatch(why)) => {
                    src_diff.insert(
                        fa.name.clone(),
                        (
                            format!("the new image does not match the source: {why}"),
                            "old matches the source",
                        ),
                    );
                    continue;
                }
                (Status::Mismatch(why), Status::Proved) => {
                    src_diff.insert(
                        fa.name.clone(),
                        (
                            format!("the old image does not match the source: {why}"),
                            "new matches the source",
                        ),
                    );
                    continue;
                }
                (x, y) => {
                    let mismatch = matches!(x, Status::Mismatch(_)) || matches!(y, Status::Mismatch(_));
                    let ok = |s: &Status| matches!(s, Status::Proved | Status::Bounded(_));
                    in_source.insert(fa.name.clone(), (!mismatch, ok(x) && ok(y)));
                    continue;
                }
            };
            by_source.insert(fa.name.clone(), r);
        }
    }

    // Machine code against machine code, for everything the source did not settle.
    let names: Vec<&String> = sp
        .paired
        .keys()
        .filter(|n| wanted(n) && !by_source.contains_key(*n))
        .collect();
    let run = |which: &[u32], inline: bool| -> Vec<Raw> {
        run_jobs(which, opts.verify.jobs, |i| {
            let n = names[i as usize];
            // A defect of the tool is the one function's result, not the end of the run.
            crate::verify::caught(|| {
                // (For the tests of `caught`.)
                if std::env::var("CVERIF_TEST_PANIC").is_ok_and(|v| v == *n) {
                    panic!("requested by CVERIF_TEST_PANIC");
                }
                if inline {
                    analyse(&sp, sp.paired[n], true, &HashSet::new(), opts)
                } else {
                    analyse_calls(&sp, sp.paired[n], opts)
                }
            })
            .unwrap_or_else(|what| Raw {
                verdict: Verdict::Inconclusive(crate::verify::internal_error(&what)),
                facts: Facts::default(),
                inline,
                paths: 0,
                millis: 0,
                models: Vec::new(),
            })
        })
    };
    let all: Vec<u32> = (0..names.len() as u32).collect();
    // A pair with the same instructions is only analysed when what a function that differs
    // does with it has to be known (which argument words it reads, whether its callers read
    // its result).
    let same: Vec<bool> = names.iter().map(|n| same_code.contains(*n)).collect();
    let mut skipped: Vec<bool> = same.iter().map(|s| *s && lazy).collect();
    // The paired functions each one calls or jumps to directly (old image).
    let direct: Vec<BTreeSet<String>> = (names.iter())
        .map(|n| {
            let ea = sp.paired[*n][0];
            let size = a.func_at(ea).map_or(0, |s| s.size);
            direct_targets(a, ea, size)
                .into_iter()
                .filter_map(|t| sp.fn_key[0].get(&t).cloned())
                .collect()
        })
        .collect();
    let mut raw: Vec<Raw> = (0..names.len())
        .map(|i| Raw {
            verdict: Verdict::Equivalent,
            facts: Facts {
                calls: if skipped[i] { direct[i].clone() } else { BTreeSet::new() },
                ..Default::default()
            },
            inline: false,
            paths: 0,
            millis: 0,
            models: Vec::new(),
        })
        .collect();
    let active: Vec<u32> = all.iter().copied().filter(|&i| !skipped[i as usize]).collect();
    for (i, r) in active.iter().zip(run(&active, false)) {
        raw[*i as usize] = r;
    }
    let mut notes: Vec<Option<String>> = vec![None; names.len()];
    // A difference found while calls were matched one to one may only be a difference in which
    // calls are made: decide with the callees followed on both sides.
    let redo = |raw: &mut Vec<Raw>, notes: &mut Vec<Option<String>>, which: Vec<u32>| {
        let again = run(&which, true);
        for (i, r) in which.into_iter().zip(again) {
            let i = i as usize;
            let decisive = complete(&r.verdict) || matches!(r.verdict, Verdict::Different(_));
            // Tried: what the call-by-call comparison established stands otherwise.
            notes[i] = Some(String::new());
            if decisive {
                // Different either way: the difference seen in the function's own calls is
                // the one to report.
                let own = match (&raw[i].verdict, &r.verdict) {
                    (Verdict::Different(why), Verdict::Different(_)) => Some(why.clone()),
                    _ => None,
                };
                let mut models = std::mem::take(&mut raw[i].models);
                raw[i] = r;
                raw[i].models.append(&mut models);
                if let Some(why) = own {
                    raw[i].verdict = Verdict::Different(why);
                }
            } else if !matches!(raw[i].verdict, Verdict::Different(_)) {
                // Keep the call-by-call result and what it says about the callees.
            } else {
                let Verdict::Different(old) = &raw[i].verdict else {
                    unreachable!()
                };
                let why = match &r.verdict {
                    Verdict::Bounded(w) | Verdict::Inconclusive(w) | Verdict::Unsupported(w) => w.clone(),
                    _ => String::new(),
                };
                let msg =
                    format!("differs when calls are matched one to one ({old}); with the callees followed: {why}");
                raw[i].verdict = match &r.verdict {
                    Verdict::Bounded(_) => Verdict::Bounded(msg),
                    Verdict::Unsupported(_) => Verdict::Unsupported(msg),
                    _ => Verdict::Inconclusive(msg),
                };
                raw[i].inline = true;
            }
        }
    };
    let first: Vec<u32> = all
        .iter()
        .copied()
        .filter(|&i| {
            let r = &raw[i as usize];
            !complete(&r.verdict) && *r.facts.saw_internal.borrow()
        })
        .collect();
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        for &i in &first {
            eprintln!(
                "compare: {} call by call: {:?}",
                names[i as usize], raw[i as usize].verdict
            );
        }
    }
    if !first.is_empty() {
        redo(&mut raw, &mut notes, first);
    }

    // Which argument words each function reads, and whose results are read.
    let index: HashMap<&str, usize> = names.iter().enumerate().map(|(i, n)| (n.as_str(), i)).collect();
    let solve_with = |raw: &[Raw], skipped: &[bool], passed_on: bool| -> (Vec<u8>, Vec<[bool; 2]>) {
        let n = raw.len();
        let mut uses = vec![0u8; n];
        let mut read = vec![[false; 2]; n];
        let reads = |uses: &[u8], callee: &str, word: u8| match index.get(callee) {
            Some(&j) => uses[j] >> word & 1 != 0,
            None => true,
        };
        loop {
            let mut changed = false;
            for (i, r) in raw.iter().enumerate() {
                let f = &r.facts;
                let mut u = if complete(&r.verdict) && !skipped[i] {
                    f.in_always | f.in_r0
                } else {
                    0xff
                };
                if read[i][1] {
                    u |= f.in_r1;
                }
                for (callee, word, mask) in &f.in_arg {
                    if reads(&uses, callee, *word) {
                        u |= mask;
                    }
                }
                if u != uses[i] {
                    uses[i] = u;
                    changed = true;
                }
                let mut hit: Vec<u32> = f.ret_always.iter().copied().collect();
                if read[i][0] {
                    hit.extend(f.ret_r0.iter().copied());
                }
                if read[i][1] {
                    hit.extend(f.ret_r1.iter().copied());
                }
                // Only what a callee is known to read shows that a result is read.
                for (callee, word, id) in &f.ret_arg {
                    if passed_on
                        && index
                            .get(callee.as_str())
                            .is_some_and(|&j| complete(&raw[j].verdict) && uses[j] >> word & 1 != 0)
                    {
                        hit.push(*id);
                    }
                }
                for id in hit {
                    let (callee, high) = &f.ret_syms[&id];
                    if let Some(&j) = index.get(callee.as_str())
                        && !read[j][*high as usize]
                    {
                        read[j][*high as usize] = true;
                        changed = true;
                    }
                }
            }
            if !changed {
                return (uses, read);
            }
        }
    };
    let solve = |raw: &[Raw], skipped: &[bool]| solve_with(raw, skipped, true);
    // Pairs left aside whose facts are needed after all: a callee that is passed different
    // values (does it read them?) or passes arguments on, and the callers of a function whose
    // result differs (do they read it?), with those that hand such a result on.
    loop {
        let mut wanted: BTreeSet<usize> = BTreeSet::new();
        let mut differs: BTreeSet<&str> = BTreeSet::new();
        // (A pair left aside is taken to read every argument word.)
        let uses = solve(&raw, &skipped).0;
        for (i, r) in raw.iter().enumerate().filter(|(i, _)| !skipped[*i]) {
            let f = &r.facts;
            if f.ret0_diff.is_some() || f.ret1_diff {
                differs.insert(names[i].as_str());
            }
            // Words that differ at a call and that the callee reads as far as is known: does
            // it, or the function it passes them on to?
            let mut work: Vec<(usize, u8)> = (f.needs.iter())
                .filter_map(|(c, (mask, _))| Some((*index.get(c.as_str())?, *mask)))
                .collect();
            let mut seen: BTreeSet<(usize, u8)> = BTreeSet::new();
            while let Some((j, mask)) = work.pop() {
                if mask & uses[j] == 0 || !seen.insert((j, mask)) {
                    continue;
                }
                if skipped[j] {
                    wanted.insert(j);
                    continue;
                }
                for (h, word, m) in &raw[j].facts.in_arg {
                    if m & mask != 0
                        && let Some(&k) = index.get(h.as_str())
                    {
                        work.push((k, 1 << word));
                    }
                }
            }
        }
        loop {
            let before = differs.len();
            for (i, r) in raw.iter().enumerate().filter(|(i, _)| !skipped[*i]) {
                let f = &r.facts;
                if (f.ret_r0.iter().chain(f.ret_r1.iter())).any(|id| differs.contains(f.ret_syms[id].0.as_str())) {
                    differs.insert(names[i].as_str());
                }
            }
            if differs.len() == before {
                break;
            }
        }
        // A result that differs and is passed on to a function left aside: does that one read it?
        for r in raw.iter().enumerate().filter(|(i, _)| !skipped[*i]).map(|x| x.1) {
            let f = &r.facts;
            for (callee, _, id) in &f.ret_arg {
                if differs.contains(f.ret_syms[id].0.as_str())
                    && let Some(&j) = index.get(callee.as_str())
                    && skipped[j]
                {
                    wanted.insert(j);
                }
            }
        }
        for (i, d) in direct.iter().enumerate() {
            if skipped[i] && d.iter().any(|c| differs.contains(c.as_str())) {
                wanted.insert(i);
            }
        }
        if wanted.is_empty() {
            break;
        }
        let which: Vec<u32> = wanted.iter().map(|&i| i as u32).collect();
        for (i, r) in which.iter().zip(run(&which, false)) {
            raw[*i as usize] = r;
            skipped[*i as usize] = false;
        }
        let again: Vec<u32> = which
            .iter()
            .copied()
            .filter(|&i| {
                let r = &raw[i as usize];
                !complete(&r.verdict) && *r.facts.saw_internal.borrow()
            })
            .collect();
        if !again.is_empty() {
            redo(&mut raw, &mut notes, again);
        }
    }
    let skipped = skipped;
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        eprintln!(
            "compare: {} pairs, {} with the same instructions, {} of them analysed all the same",
            names.len(),
            same.iter().filter(|s| **s).count(),
            (0..names.len()).filter(|&i| same[i] && !skipped[i]).count()
        );
        for (i, n) in names.iter().enumerate() {
            if !same[i] {
                eprintln!("compare: {n}: not the same instructions");
            }
        }
    }
    let (mut uses, mut read) = solve(&raw, &skipped);
    // Argument words some call site shows the callee does not read.
    let dead_of = |raw: &[Raw], callee: &str| -> u8 {
        let m = raw
            .iter()
            .flat_map(|r| r.facts.dead.iter())
            .filter(|d| d.0 == callee)
            .fold(0u8, |m, d| m | 1 << d.1);
        // Arguments fill r0-r3 before the stack, and only r1 or r3 can be skipped (to align
        // a 64-bit argument): a callee that does not read r0 reads nothing, one that does
        // not read r2 reads no stack word.
        if m & 1 != 0 {
            0xff
        } else if m & 4 != 0 {
            m | 0xf8
        } else {
            m
        }
    };
    // Words of a call to `callee` that differ and that it may read.
    let live = |raw: &[Raw], uses: &[u8], callee: &str, mask: u8| -> u8 {
        let mask = mask & !dead_of(raw, callee);
        match index.get(callee) {
            Some(&j) => mask & uses[j],
            None => mask,
        }
    };
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        for (i, r) in raw.iter().enumerate() {
            let f = &r.facts;
            let who = |ids: &BTreeSet<u32>| -> Vec<String> {
                ids.iter()
                    .map(|id| format!("{}{}", f.ret_syms[id].0, if f.ret_syms[id].1 { ":hi" } else { "" }))
                    .collect()
            };
            eprintln!(
                "compare: {} inputs {:#x}/{:#x}/{:#x} {:?} complete={} reads results always {:?}, if its r0 is read {:?}, if its r1 is read {:?}",
                names[i],
                f.in_always,
                f.in_r0,
                f.in_r1,
                f.in_arg,
                complete(&r.verdict),
                who(&f.ret_always),
                who(&f.ret_r0),
                who(&f.ret_r1)
            );
        }
    }
    for _ in 0..names.len() {
        // A function that passes different values in a word its callee reads is decided with
        // the callee followed.
        let again: Vec<u32> = all
            .iter()
            .copied()
            .filter(|&i| {
                let r = &raw[i as usize];
                !r.inline
                    && notes[i as usize].is_none()
                    && complete(&r.verdict)
                    && r.facts.needs.iter().any(|(callee, (mask, _))| {
                        index.contains_key(callee.as_str()) && live(&raw, &uses, callee, *mask) != 0
                    })
            })
            .collect();
        if again.is_empty() {
            break;
        }
        redo(&mut raw, &mut notes, again);
        (uses, read) = solve(&raw, &skipped);
    }

    // Results some caller computes with, as opposed to leaving them where the call put them.
    let used = solve_with(&raw, &skipped, false).1;
    // Verdicts.
    let mut diffs: Vec<FuncDiff> = Vec::new();
    // Functions whose only possible difference is r0 at return.
    let mut r0_only: HashSet<String> = HashSet::new();
    for (i, n) in names.iter().enumerate() {
        let r = &raw[i];
        let [ea, eb] = sp.paired[*n];
        let size = |img: &Image, e: u32| img.func_at(e).map_or(0, |s| s.size);
        let (sa, sb) = (size(a, ea), size(b, eb));
        let mut d = FuncDiff {
            name: (*n).clone(),
            old: Some((ea, sa)),
            new: Some((eb, sb)),
            verdict: r.verdict.clone(),
            same_code: sa == sb && sa > 0 && a.read(ea, sa) == b.read(eb, sb),
            conditions: Vec::new(),
            modulo: Vec::new(),
            inlined: r.inline,
            via_source: None,
            route: Route::Machine,
            replay: None,
            paths: r.paths,
            millis: r.millis,
            explanation: None,
        };
        // A difference seen on an explored path stands even if other paths hit a bound.
        if complete(&r.verdict) || matches!(r.verdict, Verdict::Bounded(_)) {
            let f = &r.facts;
            let mut hard: Option<String> = None;
            let mut weak: Vec<String> = Vec::new();
            for (callee, (mask, whys)) in &f.needs {
                let mask = live(&raw, &uses, callee, *mask);
                if mask == 0 {
                    continue;
                }
                let why = &whys[&(mask.trailing_zeros() as u8)];
                let words: Vec<String> = (0..ARG_WORDS)
                    .filter(|w| mask >> w & 1 != 0)
                    .map(|w| {
                        if w < 4 {
                            format!("r{w}")
                        } else {
                            format!("sp[{}]", 4 * (w - 4))
                        }
                    })
                    .collect();
                if opts.assume.ext_arity {
                    d.conditions
                        .push(format!("{callee} does not read {}", words.join(", ")));
                } else {
                    weak.push(format!(
                        "{why} (not a difference if {callee} does not read {})",
                        words.join(", ")
                    ));
                }
            }
            for callee in &f.stuck {
                d.conditions.push(format!(
                    "{callee} does not return here (the old code after the call decides on a register the call may clobber)"
                ));
            }
            if let Some(why) = &f.overlap {
                weak.push(format!(
                    "{why}, only when a load overlaps a store made through another address (not a difference if the two are distinct objects)"
                ));
            }
            if let Some(why) = &f.slot_diff {
                weak.push(format!("{why} (not a difference outside the object it was given)"));
            }
            if let Some(why) = &f.ret0_diff {
                let known = voids.get(n.as_str()).copied();
                if read[i][0] {
                    hard = Some(format!("{why} (callers read the result)"));
                } else if known == Some(true) {
                    d.via_source = Some("returns void in the source".into());
                } else if known == Some(false) {
                    hard = Some(why.clone());
                } else if opts.assume.void_r0 {
                    d.conditions.push("it returns nothing (r0 differs at return)".into());
                } else {
                    if weak.is_empty() {
                        r0_only.insert((*n).clone());
                    }
                    weak.push(format!("{why} (not a difference if it returns nothing)"));
                }
            }
            if f.ret1_diff && hard.is_none() {
                if used[i][1] {
                    hard = Some("r1 differs at return and callers read it".into());
                } else if read[i][1] {
                    // A caller that leaves r1 as a call left it and calls a function that
                    // reads r1: code after a call that does not return, or a caller that
                    // knows which registers its callee keeps.
                    weak.push(
                        "r1 differs at return, and some caller leaves it in place for its next call (not a difference unless it returns a 64-bit value or a caller relies on the registers it keeps)"
                            .into(),
                    );
                } else if !opts.assume.ret32 {
                    weak.push("r1 differs at return (not a difference unless it returns a 64-bit value)".into());
                } else if !voids.contains_key(n.as_str()) {
                    d.conditions
                        .push("it does not return a 64-bit value (r1 differs at return)".into());
                }
            }
            if let Some(why) = hard {
                d.verdict = Verdict::Different(why);
            } else if !weak.is_empty() {
                d.verdict = Verdict::MayDiffer(weak.join("; "));
            }
        }
        match in_source.get(n.as_str()) {
            Some(&(true, bounded)) => match &d.verdict {
                // Without a mismatch against the source the input that tells the two apart
                // may be one for which the source has no defined behaviour.
                Verdict::Different(why) | Verdict::MayDiffer(why) => {
                    let why = format!(
                        "the machine code differs ({why}), possibly only where the source is undefined: neither image is shown to differ from the source"
                    );
                    d.verdict = if bounded {
                        Verdict::Bounded(format!("{why}; both match it as far as explored"))
                    } else {
                        Verdict::Inconclusive(why)
                    };
                }
                Verdict::Equivalent => {}
                _ if bounded => {
                    d.verdict = Verdict::Bounded("both images match the source as far as explored".into());
                }
                _ => {}
            },
            Some(&(false, _)) => d.via_source = Some("differs from the source".into()),
            None => {}
        }
        // The same instructions, whose call targets and address constants designate the same
        // things: nothing to tell the two apart, whatever the path-by-path comparison made of
        // it (a function that restores the stack pointer from memory, for one).
        if same[i] && (skipped[i] || !matches!(d.verdict, Verdict::Equivalent)) {
            d.route = Route::SameInstructions;
            d.verdict = Verdict::Equivalent;
            d.conditions.clear();
            d.modulo.clear();
            d.via_source = Some(
                "the same instructions; the functions they call and the addresses they hold designate the same things"
                    .into(),
            );
        }
        diffs.push(d);
    }
    for d in diffs.iter_mut() {
        if let Some(how) = src_status.get(&d.name) {
            d.via_source = Some(how.clone());
        } else if let (Some(how), None) = (sp.folded.get(&d.name), &d.via_source) {
            d.via_source = Some(how.clone());
        }
    }
    // Callees assumed equivalent that are not proved so.
    let status: HashMap<String, &'static str> = diffs
        .iter()
        .map(|d| (d.name.clone(), d.label()))
        .chain(by_source.iter().map(|(n, v)| {
            (
                n.clone(),
                if v.0 == Verdict::Equivalent {
                    "EQUIVALENT"
                } else {
                    "DIFFERENT"
                },
            )
        }))
        .chain(src_diff.keys().map(|n| (n.clone(), "DIFFERENT")))
        .collect();
    for (i, d) in diffs.iter_mut().enumerate() {
        let f = &raw[i].facts;
        if !matches!(d.verdict, Verdict::Equivalent | Verdict::MayDiffer(_)) || !complete(&raw[i].verdict) {
            continue;
        }
        // Results the function hands on (its own result, an argument) rather than reads.
        let forwarded: BTreeSet<&str> = f
            .ret_r0
            .iter()
            .chain(f.ret_r1.iter())
            .chain(f.ret_arg.iter().map(|x| &x.2))
            .filter(|id| !f.ret_syms[*id].1)
            .map(|id| f.ret_syms[id].0.as_str())
            .collect();
        for callee in &f.calls {
            if *callee == d.name {
                continue;
            }
            match status.get(callee.as_str()).copied() {
                Some("EQUIVALENT" | "IDENTICAL" | "MOVED") | None => {}
                Some("MAY-DIFFER") if r0_only.contains(callee) && !forwarded.contains(callee.as_str()) => {}
                Some(s) => d.modulo.push((callee.clone(), s.to_string())),
            }
        }
    }
    for d in diffs.iter_mut() {
        let Some((why, how)) = src_diff.get(&d.name) else {
            continue;
        };
        if d.verdict == Verdict::Equivalent && d.modulo.iter().any(|m| m.1 == "DIFFERENT") {
            d.via_source = Some("differs from the source only through what it calls".into());
        } else {
            d.verdict = Verdict::Different(why.clone());
            d.via_source = Some(how.to_string());
            d.modulo.clear();
            d.conditions.clear();
        }
    }
    for (n, (v, how)) in by_source {
        let [ea, eb] = sp.paired.get(&n).copied().unwrap_or([0, 0]);
        let at = |img: &Image, e: u32| img.func_at(e).or_else(|| img.func(&n)).map(|s| (s.addr, s.size));
        let (old, new) = (at(a, ea), at(b, eb));
        // Like any equivalence here, this one holds for the function's own code: what it
        // calls is listed where it is not equivalent itself.
        let modulo: Vec<(String, String)> = (src_events.get(&n).into_iter().flatten())
            .filter(|c| **c != n)
            .filter_map(|c| match status.get(c.as_str()).copied() {
                Some("EQUIVALENT" | "IDENTICAL" | "MOVED" | "MAY-DIFFER") | None => None,
                Some(s) => Some((c.clone(), s.to_string())),
            })
            .collect();
        diffs.push(FuncDiff {
            same_code: match (old, new) {
                (Some(x), Some(y)) => x.1 == y.1 && x.1 > 0 && a.read(x.0, x.1) == b.read(y.0, y.1),
                _ => false,
            },
            name: n,
            old,
            new,
            verdict: v,
            conditions: Vec::new(),
            modulo,
            inlined: false,
            via_source: Some(how),
            route: Route::Source,
            replay: None,
            paths: 0,
            millis: 0,
            explanation: None,
        });
    }
    // Functions only one image has.
    let (fa, fb) = (funcs_of(a), funcs_of(b));
    for (side, list) in [(0, &fa), (1, &fb)] {
        for f in list.iter() {
            if !wanted(&f.name) || sp.fn_key[side].contains_key(&f.addr) {
                continue;
            }
            let at = Some((f.addr, f.size));
            diffs.push(FuncDiff {
                name: f.name.clone(),
                old: if side == 0 { at } else { None },
                new: if side == 1 { at } else { None },
                verdict: if side == 0 { Verdict::Removed } else { Verdict::Added },
                same_code: false,
                conditions: Vec::new(),
                modulo: Vec::new(),
                inlined: false,
                via_source: None,
                route: Route::None,
                replay: None,
                paths: 0,
                millis: 0,
                explanation: None,
            });
        }
    }
    // Every counterexample is run on the two functions by an interpreter that shares nothing
    // with the comparison.  One that shows no difference there does not stand: whatever let
    // the prover find it (a pointer compared in a way the two layouts were not matched for,
    // say), DIFFERENT is not established.
    let show = REPLAY.with(|r| r.get()) || std::env::var_os("CVERIF_REPLAY").is_some();
    {
        for d in diffs.iter_mut() {
            let Verdict::Different(why) = &d.verdict else { continue };
            let Some(&i) = index.get(d.name.as_str()) else { continue };
            // The counterexample the verdict prints.
            // (Of two with the same text, the one from the analysis the verdict is from:
            // with the callees followed, or with calls compared as calls.)
            let found = (raw[i].models.iter())
                .filter(|(m, _)| m.text != "any input" && why.contains(&m.text))
                .max_by_key(|(m, inline)| (m.text.len(), *inline == d.inlined))
                .or_else(|| raw[i].models.iter().find(|(m, _)| why.contains(&m.text)));
            d.replay = Some(match found {
                _ if src_diff.contains_key(&d.name) => replay::Replay::NotModelled(
                    "the verdict and its counterexample come from the comparison with the source".into(),
                ),
                Some((m, _)) => replay::replay(&sp, sp.paired[&d.name], m, why),
                None => replay::Replay::NotModelled("the verdict has no counterexample of the machine code".into()),
            });
            if let Some(replay::Replay::NotReproduced(how)) = &d.replay {
                d.verdict = Verdict::Inconclusive(format!(
                    "the prover finds a difference ({why}) that running the old and the new code on that input does not show: {how}"
                ));
                d.modulo.clear();
                d.conditions.clear();
            }
            if !show && !matches!(d.replay, Some(replay::Replay::NotReproduced(_))) {
                d.replay = None;
            }
        }
    }
    diffs.sort_by(|x, y| {
        let key = |d: &FuncDiff| (d.old.or(d.new).map_or(0, |x| x.0), d.old.is_none());
        key(x).cmp(&key(y)).then(x.name.cmp(&y.name))
    });
    if opts.explain {
        let notes = std::mem::take(&mut *sp.notes.lock().unwrap_or_else(|e| e.into_inner()));
        let (na, nb) = (crate::explain::Names::new(a, None), crate::explain::Names::new(b, None));
        for d in diffs.iter_mut() {
            let (Verdict::Different(why) | Verdict::MayDiffer(why)) = &d.verdict else {
                continue;
            };
            let mut o = String::new();
            if let Some((_, note)) = notes.iter().find(|n| why.contains(&n.0)) {
                o.push_str(note);
            }
            for (label, image, names, at) in [("old", a, &na, d.old), ("new", b, &nb, d.new)] {
                if let Some((addr, size)) = at {
                    let _ = writeln!(o, "{label} code:");
                    o.push_str(&crate::explain::binary::listing(
                        image,
                        names,
                        addr & !1,
                        (addr & !1) + size,
                    ));
                }
            }
            d.explanation = Some(o);
        }
    }
    out.funcs = diffs;
    out
}