cverif 0.0.3

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

use crate::image::{Image, SymKind};
use crate::thumb::decode::{Addr, Cond, DpOp, Insn, Offset, Op, Operand, decode};
use std::fmt;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OptLevel {
    O0,
    O1,
    O2,
    O3,
    Os,
    Oz,
    Og,
}

impl OptLevel {
    pub const ALL: [OptLevel; 7] = [
        OptLevel::O0,
        OptLevel::O1,
        OptLevel::O2,
        OptLevel::O3,
        OptLevel::Os,
        OptLevel::Oz,
        OptLevel::Og,
    ];
}

impl fmt::Display for OptLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            OptLevel::O0 => "-O0",
            OptLevel::O1 => "-O1",
            OptLevel::O2 => "-O2",
            OptLevel::O3 => "-O3",
            OptLevel::Os => "-Os",
            OptLevel::Oz => "-Oz",
            OptLevel::Og => "-Og",
        })
    }
}

/// Structural measurements taken from the code of an image.
#[derive(Clone, Debug, Default)]
pub struct Features {
    /// Functions that could be decoded.
    pub funcs: u32,
    pub insns: u32,
    /// Functions that set up `r7` as a frame pointer in their prologue.
    pub frame_pointer_funcs: u32,
    /// Loads and stores relative to `sp` or the `r7` frame pointer.
    pub frame_accesses: u32,
    /// Loops whose back edge is an unconditional branch to a test at the top.
    pub loops_top_tested: u32,
    /// Bottom-tested loops entered by an unconditional jump to the test.
    pub loops_entry_jump: u32,
    /// Bottom-tested loops entered by falling in (header copied / guarded).
    pub loops_rotated: u32,
    /// Bottom-tested loops immediately followed by another compare-and-branch
    /// (remainder handling after an unrolled or widened loop).
    pub loops_with_remainder: u32,
    /// Functions containing at least one loop, and their total size in bytes.
    pub loop_funcs: u32,
    pub loop_func_bytes: u32,
    /// Conditional branches directly preceded by the flag-setting instruction.
    pub branch_adjacent: u32,
    /// Conditional branches with a non-flag-setting instruction in between.
    pub branch_separated: u32,
    pub it_blocks: u32,
    /// `udiv`/`sdiv` whose divisor was loaded as an immediate just before.
    pub div_by_immediate: u32,
    /// Long multiplies (reciprocal multiplication for division by a constant).
    pub long_multiplies: u32,
    /// Function starts where 4-byte alignment needed padding and got it / did not get it.
    pub starts_padded: u32,
    pub starts_unpadded: u32,
    /// Symbols of function clones (`.constprop`, `.isra`, `.part`).
    pub clones: u32,
    /// Paired or multi-word memory accesses typical of widened loops (`strd`/`ldrd` outside prologues).
    pub dual_accesses: u32,
    /// Windows of four consecutive instructions, and how many of them repeat an earlier
    /// window of the same function (same operations, any registers): duplicated code
    /// from unrolling, peeling and loop versioning.
    pub windows: u32,
    pub repeated_windows: u32,

    // ----- instruction set -----
    /// 32-bit encodings other than `bl` that ARMv8-M Baseline also has (wide `b`, `movw`, `movt`).
    pub wide_baseline: u32,
    /// Other 32-bit encodings: only ARMv7-M / ARMv8-M Mainline have them.
    pub wide_mainline: u32,
    pub cbz: u32,
    pub hw_divides: u32,
    pub movw_movt: u32,
    /// DSP-extension multiplies (`smulbb`, `smlabb`, ...).
    pub dsp_insns: u32,
    /// Undecoded coprocessor-space encodings (floating-point instructions).
    pub fp_insns: u32,
    pub undecoded: u32,

    // ----- prologues -----
    pub leaf_funcs: u32,
    pub nonleaf_funcs: u32,
    pub fp_leaf: u32,
    pub fp_nonleaf: u32,
    /// Leaf functions that have a stack frame at all (push or sp adjustment).
    pub framed_leaf: u32,
    /// Functions whose first instructions store argument registers to the frame.
    pub arg_spills: u32,
    /// `push {r7, lr}` with r7 otherwise unused (clang keeps the stack 8-byte aligned this way).
    pub push_r7_lr_pad: u32,
    /// Pushes that include r3 (GCC pads with a caller-saved register).
    pub push_r3_pad: u32,
    /// Pushes of {r4, lr} (or more) where r4 is otherwise unused in the function.
    pub push_r4_pad: u32,
    /// Frame pointer set up as `add r7, sp, #imm` (GCC) / `mov r7, sp` (clang at -O0 uses add too: measured, not assumed).
    pub fp_add: u32,
    pub fp_mov: u32,

    // ----- addressing -----
    /// `add rX, pc`: position-independent address formation.
    pub add_pc: u32,
    pub literal_loads: u32,
    /// Instructions that read r9, and that write it.
    pub r9_reads: u32,
    pub r9_writes: u32,

    // ----- switches -----
    pub table_branches: u32,
    /// Writes to pc other than returns and table branches (`mov pc, rX`, `add pc, rX`, `ldr pc, ...`).
    pub computed_jumps: u32,
    /// Functions that compare one register against five or more distinct, densely packed constants.
    pub dense_compare_chains: u32,
    /// Largest number of distinct constants one register is compared against in a function.
    pub longest_compare_chain: u32,

    // ----- memory idioms -----
    /// Places where four consecutive bytes are loaded (stored) one by one from the same base.
    pub bytewise_loads: u32,
    pub bytewise_stores: u32,

    // ----- calls -----
    pub direct_calls: u32,
    pub indirect_calls: u32,
    /// `blx rX` where rX was just loaded from a literal pool.
    pub literal_calls: u32,
    /// Unconditional branches that leave the function for the start of another one.
    pub tail_calls: u32,
    /// Calls to a division helper with a constant divisor set up just before.
    pub helper_div_by_immediate: u32,
    /// Machine-outliner symbols.
    pub outlined: u32,
    /// Bytes of code, and number of padding bytes between functions.
    pub code_bytes: u32,
    /// Local (static) functions, and those that are tiny yet called from exactly one place.
    pub local_funcs: u32,
    pub local_tiny_single_caller: u32,
    /// Function-end padding halfwords by value: `nop` (0xbf00), `mov r8, r8` (0x46c0), zero, other.
    pub pad_nop: u32,
    pub pad_mov_r8: u32,
    pub pad_zero: u32,
    /// Constants built on Thumb-1 as `movs` + `lsls` (clang) versus loaded from a literal pool.
    pub movs_lsls_consts: u32,
    /// Absolute addresses formed in code (literal-pool words, `movw`/`movt` pairs) that point
    /// into read-only and into writable parts of the image.
    pub abs_ro_refs: u32,
    pub abs_rw_refs: u32,
    /// Byte-wise loads whose bytes are then shifted together into one word.
    pub assembled_words: u32,
    /// Word or halfword accesses at an odd constant offset (only legal with unaligned access).
    pub odd_word_access: u32,
    /// `bl` to symbols not defined in the image.
    pub direct_extern_calls: u32,
    /// Calls to software floating-point helpers (`__aeabi_fadd`, `__aeabi_dmul`, ...).
    pub soft_float_calls: u32,
}

struct Decoded {
    addr: u32,
    insn: Insn,
    in_it: bool,
}

fn decode_function(image: &Image, start: u32, size: u32) -> Vec<Decoded> {
    let mut out = Vec::new();
    let mut pc = start;
    let end = start.saturating_add(size);
    let mut it_left = 0u32;
    // Without mapping symbols (raw binaries, stripped images) literal pools are found from the
    // loads that refer to them, so that constants are not read as instructions.
    let guess_pools = image.data_ranges.is_empty();
    let mut literals: std::collections::BTreeSet<u32> = Default::default();
    while pc < end {
        if guess_pools && literals.contains(&(pc & !3)) {
            pc = (pc & !3) + 4;
            it_left = 0;
            continue;
        }
        if image.is_data_in_code(pc) {
            // Literal pool: skip to the end of the data range.
            match image.data_ranges.iter().find(|&&(a, b)| pc >= a && pc < b) {
                Some(&(_, b)) => pc = b.max(pc + 2),
                None => pc += 2,
            }
            it_left = 0;
            continue;
        }
        let n = (end - pc).min(4);
        let Some(bytes) = image.read(pc, n) else { break };
        let in_it = it_left > 0;
        let Some(insn) = decode(bytes, pc, in_it) else { break };
        if in_it {
            it_left -= 1;
        } else if let Op::It { mask, .. } = insn.op {
            it_left = 4 - (mask & 0xf).trailing_zeros().min(3);
        }
        if let Op::Load { addr: Addr::Lit(a), .. } = insn.op {
            literals.insert(a & !3);
        }
        out.push(Decoded { addr: pc, insn, in_it });
        pc += insn.len as u32;
    }
    out
}

fn sets_flags(op: &Op) -> bool {
    match *op {
        Op::Dp { s, rd, .. } => s || rd.is_none(),
        Op::ShiftReg { s, .. } | Op::Mul { s, .. } => s,
        _ => false,
    }
}

fn is_compare(op: &Op) -> bool {
    matches!(op, Op::Dp { rd: None, .. })
}

/// The operation of an instruction with registers and immediates abstracted away.
fn shape(op: &Op) -> u32 {
    match *op {
        Op::Dp { op, s, rd, src, .. } => {
            1 | (op as u32) << 8
                | (s as u32) << 16
                | (rd.is_none() as u32) << 17
                | (matches!(src, Operand::Imm { .. }) as u32) << 18
        }
        Op::Load { size, signed, addr, .. } => 2 | (size as u32) << 8 | (signed as u32) << 16 | addr_shape(&addr) << 17,
        Op::Store { size, addr, .. } => 3 | (size as u32) << 8 | addr_shape(&addr) << 17,
        Op::B { cond, .. } => 4 | (cond as u32) << 8,
        Op::ShiftReg { shift, .. } => 5 | (shift as u32) << 8,
        Op::Mul { .. } => 6,
        Op::Mla { .. } => 7,
        Op::Mls { .. } => 8,
        Op::MulLong { signed, accumulate, .. } => 9 | (signed as u32) << 8 | (accumulate as u32) << 9,
        Op::Div { signed, .. } => 10 | (signed as u32) << 8,
        Op::LoadDual { .. } => 11,
        Op::StoreDual { .. } => 12,
        Op::LoadMulti { .. } => 13,
        Op::StoreMulti { .. } => 14,
        Op::Bl { .. } => 15,
        Op::Bx { .. } => 16,
        Op::Blx { .. } => 17,
        Op::Cbz { nonzero, .. } => 18 | (nonzero as u32) << 8,
        Op::It { cond, mask } => 19 | (cond as u32) << 8 | (mask as u32) << 16,
        Op::Extend { signed, size, .. } => 20 | (signed as u32) << 8 | (size as u32) << 9,
        Op::Bfx { signed, .. } => 21 | (signed as u32) << 8,
        Op::Movt { .. } => 22,
        Op::Adr { .. } => 23,
        Op::TableBranch { .. } => 24,
        Op::Nop => 25,
        _ => 26,
    }
}

fn addr_shape(a: &Addr) -> u32 {
    match a {
        Addr::Lit(_) => 0,
        Addr::Base {
            offset: Offset::Imm(_),
            wback: false,
            ..
        } => 1,
        Addr::Base {
            offset: Offset::Imm(_), ..
        } => 2,
        Addr::Base { .. } => 3,
    }
}

fn frame_access(addr: &Addr) -> bool {
    matches!(
        addr,
        Addr::Base {
            rn: 7 | 13,
            offset: Offset::Imm(_),
            wback: false,
            ..
        }
    )
}

/// Measure the structural features of all function symbols in the image.
pub fn features(image: &Image) -> Features {
    let mut f = Features::default();
    let mut funcs: Vec<(u32, u32, &str)> = image
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Func && s.size >= 2 && image.segment_at(s.addr).is_some_and(|g| g.exec))
        .map(|s| (s.addr, s.size, s.name.as_str()))
        .collect();
    funcs.sort();
    funcs.dedup_by_key(|x| x.0);
    for &(_, _, name) in &funcs {
        if [".constprop", ".isra", ".part"].iter().any(|k| name.contains(k)) {
            f.clones += 1;
        }
    }
    // Alignment: a function ending at an address that is 2 modulo 4 is followed either
    // directly by the next one (no alignment) or after 2 bytes of padding (4-byte alignment).
    for w in funcs.windows(2) {
        let end = w[0].0 + w[0].1;
        if end % 4 == 2 {
            if w[1].0 == end {
                f.starts_unpadded += 1;
            } else if w[1].0 == end + 2 {
                f.starts_padded += 1;
            }
        }
    }
    let starts: Vec<u32> = funcs.iter().map(|x| x.0).collect();
    for &(addr, size, _) in &funcs {
        let code = decode_function(image, addr, size);
        if code.is_empty() {
            continue;
        }
        f.funcs += 1;
        f.insns += code.len() as u32;
        let is_fp = code.iter().take(6).any(|d| {
            matches!(
                d.insn.op,
                Op::Dp {
                    op: DpOp::Add,
                    rd: Some(7),
                    rn: Some(13),
                    src: Operand::Imm { .. },
                    ..
                } | Op::Dp {
                    op: DpOp::Mov,
                    rd: Some(7),
                    src: Operand::Reg { rm: 13, .. },
                    ..
                }
            )
        });
        f.frame_pointer_funcs += is_fp as u32;
        let shapes: Vec<u32> = code.iter().map(|d| shape(&d.insn.op)).collect();
        let mut seen = std::collections::HashSet::new();
        for w in shapes.windows(4) {
            f.windows += 1;
            if !seen.insert([w[0], w[1], w[2], w[3]]) {
                f.repeated_windows += 1;
            }
        }
        let mut has_loop = false;
        for (i, d) in code.iter().enumerate() {
            let prev = if i > 0 { Some(&code[i - 1]) } else { None };
            match d.insn.op {
                Op::Load { addr: a, .. } | Op::Store { addr: a, .. } => f.frame_accesses += frame_access(&a) as u32,
                Op::LoadDual { addr: a, .. } | Op::StoreDual { addr: a, .. } => {
                    if frame_access(&a) {
                        f.frame_accesses += 1;
                    } else {
                        f.dual_accesses += 1;
                    }
                }
                Op::It { .. } => f.it_blocks += 1,
                Op::MulLong { accumulate: false, .. } => f.long_multiplies += 1,
                Op::Div { rm, .. } => {
                    if let Some(p) = prev
                        && matches!(p.insn.op, Op::Dp { op: DpOp::Mov, rd: Some(r), src: Operand::Imm { .. }, .. } if r == rm)
                    {
                        f.div_by_immediate += 1;
                    }
                }
                Op::B { cond, target } => {
                    if cond != Cond::Al
                        && !d.in_it
                        && let Some(p) = prev
                    {
                        if sets_flags(&p.insn.op) {
                            f.branch_adjacent += 1;
                        } else {
                            f.branch_separated += 1;
                        }
                    }
                    if target <= d.addr && target >= addr && !d.in_it {
                        if cond == Cond::Al {
                            // A loop tested at the top: the head starts with a compare and a conditional
                            // branch.  (Other backward jumps merely share an epilogue or a block.)
                            let tested = code.iter().skip_while(|e| e.addr < target).take(4).any(|e| {
                                matches!(e.insn.op, Op::B { cond: c, target: t } if c != Cond::Al && t > e.addr)
                                    || matches!(e.insn.op, Op::Cbz { .. })
                            });
                            if tested {
                                has_loop = true;
                                f.loops_top_tested += 1;
                            }
                        } else {
                            has_loop = true;
                            // Is the loop entered by an unconditional jump from before its head to its test?
                            let entry = code.iter().any(|e| {
                                e.addr < target
                                    && matches!(e.insn.op, Op::B { cond: Cond::Al, target: t } if t > target && t <= d.addr)
                            });
                            if entry {
                                f.loops_entry_jump += 1;
                            } else {
                                f.loops_rotated += 1;
                                let next = &code[i + 1..];
                                let rem = next.iter().take(2).any(|n| is_compare(&n.insn.op))
                                    && next.iter().take(3).any(|n| {
                                        matches!(n.insn.op, Op::B { cond: c, target: t } if c != Cond::Al && t > n.addr)
                                    });
                                f.loops_with_remainder += rem as u32;
                            }
                        }
                    }
                }
                _ => {}
            }
        }
        if has_loop {
            f.loop_funcs += 1;
            f.loop_func_bytes += size;
        }
        function_features(image, addr, size, &code, &starts, &mut f);
    }
    global_features(image, &funcs, &mut f);
    f
}

fn operand_reads(src: &Operand) -> u16 {
    match *src {
        Operand::Reg { rm, .. } => 1 << rm,
        Operand::Imm { .. } => 0,
    }
}

fn addr_reads(a: &Addr) -> u16 {
    match *a {
        Addr::Lit(_) => 0,
        Addr::Base { rn, offset, .. } => {
            (1 << rn)
                | match offset {
                    Offset::Reg { rm, .. } => 1 << rm,
                    Offset::Imm(_) => 0,
                }
        }
    }
}

/// Registers an instruction reads and writes (bit i = register i); approximate for rare forms.
fn reg_use(op: &Op) -> (u16, u16) {
    let b = |r: u8| 1u16 << r;
    let o = |r: Option<u8>| r.map_or(0, b);
    match *op {
        Op::Dp { rd, rn, src, .. } => (o(rn) | operand_reads(&src), o(rd)),
        Op::ShiftReg { rd, rn, rm, .. } | Op::Mul { rd, rn, rm, .. } | Op::Div { rd, rn, rm, .. } => {
            (b(rn) | b(rm), b(rd))
        }
        Op::Movt { rd, .. } => (b(rd), b(rd)),
        Op::Adr { rd, .. } => (0, b(rd)),
        Op::Mla { rd, rn, rm, ra } | Op::Mls { rd, rn, rm, ra } => (b(rn) | b(rm) | b(ra), b(rd)),
        Op::MulHalves { rd, rn, rm, ra, .. } => (b(rn) | b(rm) | o(ra), b(rd)),
        Op::MulLong { rdlo, rdhi, rn, rm, .. } => (b(rn) | b(rm), b(rdlo) | b(rdhi)),
        Op::Load { rt, addr, .. } => (addr_reads(&addr), b(rt)),
        Op::Store { rt, addr, .. } => (addr_reads(&addr) | b(rt), 0),
        Op::LoadDual { rt, rt2, addr } => (addr_reads(&addr), b(rt) | b(rt2)),
        Op::StoreDual { rt, rt2, addr } => (addr_reads(&addr) | b(rt) | b(rt2), 0),
        Op::LoadMulti { rn, regs, .. } => (b(rn), regs),
        Op::StoreMulti { rn, regs, .. } => (b(rn) | regs, 0),
        Op::Bx { rm } | Op::Blx { rm } => (b(rm), 0),
        Op::Cbz { rn, .. } => (b(rn), 0),
        Op::TableBranch { rn, rm, .. } => (b(rn) | b(rm), 0),
        Op::Bfi { rd, rn, .. } => (b(rd) | b(rn), b(rd)),
        Op::Bfc { rd, .. } => (b(rd), b(rd)),
        Op::Bfx { rd, rn, .. } | Op::Sat { rd, rn, .. } => (b(rn), b(rd)),
        Op::Extend { rd, rn, rm, .. } => (o(rn) | b(rm), b(rd)),
        Op::Clz { rd, rm } | Op::Rbit { rd, rm } | Op::Rev { rd, rm } | Op::Rev16 { rd, rm } | Op::Revsh { rd, rm } => {
            (b(rm), b(rd))
        }
        _ => (0, 0),
    }
}

const DIV_HELPERS: [&str; 8] = [
    "__aeabi_uidiv",
    "__aeabi_idiv",
    "__aeabi_uidivmod",
    "__aeabi_idivmod",
    "__udivsi3",
    "__divsi3",
    "__umodsi3",
    "__modsi3",
];

fn function_features(image: &Image, start: u32, size: u32, code: &[Decoded], starts: &[u32], f: &mut Features) {
    let end = start + size;
    f.code_bytes += size;
    let mut leaf = true;
    let (mut reads, mut writes) = (0u16, 0u16);
    // Per register: distinct constants it is compared against.
    let mut cmp_consts: [Vec<u32>; 16] = Default::default();
    for (i, d) in code.iter().enumerate() {
        let op = &d.insn.op;
        let (r, w) = reg_use(op);
        // Pushes and pops only save and restore.
        if !matches!(op, Op::StoreMulti { rn: 13, .. } | Op::LoadMulti { rn: 13, .. }) {
            reads |= r;
            writes |= w;
            f.r9_reads += (r >> 9 & 1) as u32;
            f.r9_writes += (w >> 9 & 1) as u32;
        }
        if d.insn.len == 4 {
            match op {
                // (MRS, MSR and the barriers exist in every M-profile architecture)
                Op::Bl { .. } | Op::Sys(_) => {}
                Op::B { .. } | Op::Movt { .. } | Op::Div { .. } => f.wide_baseline += 1,
                Op::Dp {
                    op: DpOp::Mov,
                    s: false,
                    src: Operand::Imm { .. },
                    ..
                } => f.wide_baseline += 1,
                Op::Unsupported(w) => {
                    f.undecoded += 1;
                    // Coprocessor space: 0b111x_11xx in the top byte of the first halfword.
                    if (w >> 24) & 0xec == 0xec && (w >> 24) & 0x10 == 0 {
                        f.fp_insns += 1;
                    }
                }
                _ => f.wide_mainline += 1,
            }
        } else if matches!(op, Op::Unsupported(_)) {
            f.undecoded += 1;
        }
        match *op {
            Op::Cbz { .. } => f.cbz += 1,
            Op::Div { .. } => f.hw_divides += 1,
            Op::Movt { .. } => f.movw_movt += 1,
            Op::MulHalves { .. } => f.dsp_insns += 1,
            Op::TableBranch { .. } => f.table_branches += 1,
            Op::Load { addr: Addr::Lit(_), .. } => f.literal_loads += 1,
            Op::Dp {
                op: DpOp::Add,
                src: Operand::Reg { rm: 15, .. },
                rd,
                ..
            } if rd != Some(15) => f.add_pc += 1,
            Op::Dp {
                op: DpOp::Sub,
                rd: None,
                rn: Some(rn),
                src: Operand::Imm { value, .. },
                ..
            } if !cmp_consts[rn as usize].contains(&value) => cmp_consts[rn as usize].push(value),
            Op::Bl { target } => {
                leaf = false;
                f.direct_calls += 1;
                let name = image
                    .externals
                    .get(&(target & !1))
                    .map(String::as_str)
                    .or_else(|| image.func_at(target & !1).map(|s| s.name.as_str()))
                    .unwrap_or("");
                if DIV_HELPERS.contains(&name) {
                    // Divisor in r1: set from an immediate within the three preceding instructions?
                    let konst = code[i.saturating_sub(3)..i].iter().any(|p| {
                        matches!(
                            p.insn.op,
                            Op::Dp {
                                op: DpOp::Mov,
                                rd: Some(1),
                                src: Operand::Imm { .. },
                                ..
                            }
                        ) || matches!(
                            p.insn.op,
                            Op::Load {
                                rt: 1,
                                addr: Addr::Lit(_),
                                ..
                            }
                        )
                    });
                    f.helper_div_by_immediate += konst as u32;
                }
            }
            Op::Blx { rm } => {
                leaf = false;
                f.indirect_calls += 1;
                if code[i.saturating_sub(3)..i]
                    .iter()
                    .any(|p| matches!(p.insn.op, Op::Load { rt, addr: Addr::Lit(_), .. } if rt == rm))
                {
                    f.literal_calls += 1;
                }
            }
            Op::B { cond: Cond::Al, target }
                if !d.in_it
                    && (target < start || target >= end)
                    && (starts.binary_search(&(target & !1)).is_ok()
                        || image.externals.contains_key(&(target & !1))) =>
            {
                leaf = false;
                f.tail_calls += 1;
            }
            _ => {}
        }
        // Absolute addresses formed in code.
        let abs = match *op {
            Op::Load {
                size: 4,
                addr: Addr::Lit(a),
                ..
            } => image.read(a, 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
            Op::Movt { rd, imm } => code[i.saturating_sub(2)..i].iter().rev().find_map(|p| match p.insn.op {
                Op::Dp {
                    op: DpOp::Mov,
                    s: false,
                    rd: Some(r),
                    src: Operand::Imm { value, .. },
                    ..
                } if r == rd && p.insn.len == 4 => Some((imm as u32) << 16 | (value & 0xffff)),
                _ => None,
            }),
            _ => None,
        };
        if let Some(v) = abs
            && let Some(seg) = image.segment_at(v & !1)
        {
            if seg.writable {
                f.abs_rw_refs += 1;
            } else {
                f.abs_ro_refs += 1;
            }
        }
        match *op {
            Op::Load {
                size: 2 | 4,
                addr:
                    Addr::Base {
                        rn,
                        offset: Offset::Imm(o),
                        ..
                    },
                ..
            }
            | Op::Store {
                size: 2 | 4,
                addr:
                    Addr::Base {
                        rn,
                        offset: Offset::Imm(o),
                        ..
                    },
                ..
            } if o & 1 == 1 && rn != 13 && rn != 15 => f.odd_word_access += 1,
            Op::Bl { target } => {
                if let Some(name) = image.externals.get(&(target & !1)) {
                    f.direct_extern_calls += 1;
                    let n = name.as_str();
                    if (n.starts_with("__aeabi_f")
                        || n.starts_with("__aeabi_d")
                        || n.starts_with("__aeabi_i2")
                        || n.starts_with("__aeabi_ui2")
                        || n.starts_with("__aeabi_l2")
                        || n.starts_with("__aeabi_ul2"))
                        && !n.contains("div")
                    {
                        f.soft_float_calls += 1;
                    }
                }
            }
            _ => {}
        }
        // A write to pc that is not a pop or a plain return.
        let (_, w) = reg_use(op);
        if w >> 15 & 1 == 1 && !matches!(op, Op::LoadMulti { rn: 13, .. }) {
            f.computed_jumps += 1;
        }
        // movs rX, #imm ; lsls rX, rX, #n : a constant built without a literal pool.
        if let Op::Dp {
            op: DpOp::Mov,
            rd: Some(rd),
            src: Operand::Imm { .. },
            ..
        } = *op
            && d.insn.len == 2
            && let Some(n) = code.get(i + 1)
            && matches!(n.insn.op, Op::Dp { op: DpOp::Mov, rd: Some(r2), src: Operand::Reg { rm, shift: crate::thumb::decode::Shift::Lsl, amount }, .. } if r2 == rd && rm == rd && amount > 0)
        {
            f.movs_lsls_consts += 1;
        }
    }
    // Dense compare chains.
    for consts in &cmp_consts {
        let n = consts.len() as u32;
        f.longest_compare_chain = f.longest_compare_chain.max(n);
        if n >= 5 {
            let (lo, hi) = (*consts.iter().min().unwrap(), *consts.iter().max().unwrap());
            if hi - lo < 3 * n {
                f.dense_compare_chains += 1;
            }
        }
    }
    // Byte-wise word access: four byte loads (stores) at consecutive offsets from one base, close together.
    let mut assembled = 0;
    for (kind, counter) in [(false, &mut f.bytewise_loads), (true, &mut f.bytewise_stores)] {
        let mut seen: Vec<(u8, i32, usize)> = Vec::new(); // (base, offset, index)
        for (i, d) in code.iter().enumerate() {
            let hit = match d.insn.op {
                Op::Load {
                    size: 1,
                    addr:
                        Addr::Base {
                            rn,
                            offset: Offset::Imm(o),
                            wback: false,
                            ..
                        },
                    ..
                } if !kind => Some((rn, o)),
                Op::Store {
                    size: 1,
                    addr:
                        Addr::Base {
                            rn,
                            offset: Offset::Imm(o),
                            wback: false,
                            ..
                        },
                    ..
                } if kind => Some((rn, o)),
                _ => None,
            };
            if let Some((rn, o)) = hit
                && rn != 13
                && rn != 7
            {
                seen.push((rn, o, i));
            }
        }
        let mut used = vec![false; seen.len()];
        for a in 0..seen.len() {
            if used[a] {
                continue;
            }
            let (rn, o, i) = seen[a];
            let group: Vec<usize> = (0..4)
                .filter_map(|k| {
                    seen.iter()
                        .position(|&(r2, o2, i2)| r2 == rn && o2 == o + k && i2 >= i && i2 - i <= 16)
                })
                .collect();
            if group.len() == 4 {
                let (first, last) = (seen[group[0]].2, group.iter().map(|&g| seen[g].2).max().unwrap());
                for &g in &group {
                    used[g] = true;
                }
                *counter += 1;
                // Shifted together into one word (within a few instructions after the last byte)?
                let shifts = code[first..(last + 8).min(code.len())]
                    .iter()
                    .filter(|d| {
                        matches!(
                            d.insn.op,
                            Op::Dp {
                                src: Operand::Reg {
                                    shift: crate::thumb::decode::Shift::Lsl,
                                    amount: 8 | 16 | 24,
                                    ..
                                },
                                ..
                            }
                        )
                    })
                    .count();
                if !kind && shifts >= 2 {
                    assembled += 1;
                }
            }
        }
    }
    f.assembled_words += assembled;
    // Prologue.
    let head = &code[..code.len().min(8)];
    let push = head.iter().find_map(|d| match d.insn.op {
        Op::StoreMulti {
            rn: 13,
            regs,
            wback: true,
            before: true,
        } => Some(regs),
        _ => None,
    });
    let sp_adjust = head.iter().any(|d| {
        matches!(
            d.insn.op,
            Op::Dp {
                op: DpOp::Sub,
                rd: Some(13),
                rn: Some(13),
                ..
            }
        )
    });
    let fp_add = head.iter().any(|d| {
        matches!(
            d.insn.op,
            Op::Dp {
                op: DpOp::Add,
                rd: Some(7),
                rn: Some(13),
                src: Operand::Imm { .. },
                ..
            }
        )
    });
    let fp_mov = head.iter().any(|d| {
        matches!(
            d.insn.op,
            Op::Dp {
                op: DpOp::Mov,
                rd: Some(7),
                src: Operand::Reg { rm: 13, .. },
                ..
            }
        )
    });
    let is_fp = fp_add || fp_mov;
    f.fp_add += fp_add as u32;
    f.fp_mov += fp_mov as u32;
    if leaf {
        f.leaf_funcs += 1;
        f.fp_leaf += is_fp as u32;
        f.framed_leaf += (push.is_some() || sp_adjust) as u32;
    } else {
        f.nonleaf_funcs += 1;
        f.fp_nonleaf += is_fp as u32;
    }
    if let Some(regs) = push {
        let untouched = |r: u8| (reads | writes) >> r & 1 == 0;
        if regs == (1 << 7 | 1 << 14) && untouched(7) {
            f.push_r7_lr_pad += 1;
        }
        if regs >> 3 & 1 == 1 {
            f.push_r3_pad += 1;
        }
        if regs >> 4 & 1 == 1 && regs >> 14 & 1 == 1 && untouched(4) {
            f.push_r4_pad += 1;
        }
    }
    f.arg_spills +=
        head.iter()
            .any(|d| matches!(d.insn.op, Op::Store { rt: 0, size: 4, addr, .. } if frame_access(&addr))) as u32;
}

fn global_features(image: &Image, funcs: &[(u32, u32, &str)], f: &mut Features) {
    f.outlined = funcs.iter().filter(|x| x.2.starts_with("OUTLINED_FUNCTION_")).count() as u32;
    // Padding between consecutive functions.
    for w in funcs.windows(2) {
        let (mut a, b) = (w[0].0 + w[0].1, w[1].0);
        if b <= a || b - a > 14 || image.is_data_in_code(a) {
            continue;
        }
        while a + 2 <= b {
            match image.read(a, 2).map(|x| u16::from_le_bytes([x[0], x[1]])) {
                Some(0xbf00) => f.pad_nop += 1,
                Some(0x46c0) => f.pad_mov_r8 += 1,
                Some(0) => f.pad_zero += 1,
                _ => {}
            }
            a += 2;
        }
    }
    // Static functions that are tiny and have a single direct caller.
    let mut callers: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
    for &(addr, size, _) in funcs {
        for d in decode_function(image, addr, size) {
            if let Op::Bl { target } = d.insn.op {
                *callers.entry(target & !1).or_default() += 1;
            }
        }
    }
    for s in image
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Func && !s.global && s.size >= 2)
    {
        if s.name.starts_with("OUTLINED_FUNCTION_") {
            continue;
        }
        f.local_funcs += 1;
        if s.size <= 24 && callers.get(&s.addr) == Some(&1) {
            f.local_tiny_single_caller += 1;
        }
    }
}

fn ratio(a: u32, b: u32) -> f32 {
    if a + b == 0 { 0.0 } else { a as f32 / (a + b) as f32 }
}

// ----- declared information ---------------------------------------------------------------------

/// Decode `.ARM.attributes` into (tag name, value) pairs for the `aeabi` vendor, file scope.
pub fn build_attributes(raw: &[u8]) -> Vec<(&'static str, String)> {
    fn uleb(b: &[u8], p: &mut usize) -> Option<u64> {
        let mut v = 0u64;
        let mut shift = 0;
        loop {
            let c = *b.get(*p)?;
            *p += 1;
            if shift < 64 {
                v |= ((c & 0x7f) as u64) << shift;
            }
            shift += 7;
            if c & 0x80 == 0 {
                return Some(v);
            }
        }
    }
    fn ntbs(b: &[u8], p: &mut usize) -> Option<String> {
        let end = b[*p..].iter().position(|&c| c == 0)? + *p;
        let s = String::from_utf8_lossy(&b[*p..end]).into_owned();
        *p = end + 1;
        Some(s)
    }
    fn pick(names: &[&str], v: u64) -> String {
        names.get(v as usize).map_or_else(|| v.to_string(), |s| s.to_string())
    }
    let mut out = Vec::new();
    if raw.first() != Some(&b'A') {
        return out;
    }
    let mut p = 1;
    while p + 4 <= raw.len() {
        let len = u32::from_le_bytes([raw[p], raw[p + 1], raw[p + 2], raw[p + 3]]) as usize;
        let end = (p + len).min(raw.len());
        let mut q = p + 4;
        let Some(vendor) = ntbs(&raw[..end], &mut q) else { break };
        while vendor == "aeabi" && q + 5 <= end {
            let tag = raw[q];
            let sublen = u32::from_le_bytes([raw[q + 1], raw[q + 2], raw[q + 3], raw[q + 4]]) as usize;
            let subend = (q + sublen).min(end);
            let b = &raw[..subend];
            let mut r = q + 5;
            while tag == 1 && r < subend {
                let Some(t) = uleb(b, &mut r) else { break };
                // String-valued tags: 4, 5, 65, 67 and odd tags above 32; 32 has a number and a string.
                let is_str = matches!(t, 4 | 5 | 65 | 67) || (t > 32 && t % 2 == 1);
                if t == 32 {
                    let _ = uleb(b, &mut r);
                    let _ = ntbs(b, &mut r);
                    continue;
                }
                if is_str {
                    let Some(s) = ntbs(b, &mut r) else { break };
                    match t {
                        4 => out.push(("Tag_CPU_raw_name", s)),
                        5 => out.push(("Tag_CPU_name", s)),
                        67 => out.push(("Tag_conformance", s)),
                        _ => {}
                    }
                    continue;
                }
                let Some(v) = uleb(b, &mut r) else { break };
                let e: Option<(&'static str, String)> = match t {
                    6 => Some((
                        "Tag_CPU_arch",
                        pick(
                            &[
                                "pre-v4",
                                "v4",
                                "v4T",
                                "v5T",
                                "v5TE",
                                "v5TEJ",
                                "v6",
                                "v6KZ",
                                "v6T2",
                                "v6K",
                                "v7",
                                "v6-M",
                                "v6S-M",
                                "v7E-M",
                                "v8-A",
                                "v8-R",
                                "v8-M.baseline",
                                "v8-M.mainline",
                                "v8.1-A",
                                "v8.2-A",
                                "v8.3-A",
                                "v8.1-M.mainline",
                                "v9",
                            ],
                            v,
                        ),
                    )),
                    7 => Some(("Tag_CPU_arch_profile", (v as u8 as char).to_string())),
                    9 => Some(("Tag_THUMB_ISA_use", pick(&["none", "Thumb-1", "Thumb-2", "yes"], v))),
                    10 => Some(("Tag_FP_arch", if v == 0 { "none".into() } else { format!("FP v{v}") })),
                    14 => Some(("Tag_ABI_PCS_R9_use", pick(&["V6", "SB", "TLS", "unused"], v))),
                    15 => Some((
                        "Tag_ABI_PCS_RW_data",
                        pick(&["absolute", "PC-relative", "SB-relative", "none"], v),
                    )),
                    16 => Some(("Tag_ABI_PCS_RO_data", pick(&["absolute", "PC-relative", "none"], v))),
                    17 => Some(("Tag_ABI_PCS_GOT_use", pick(&["none", "direct", "GOT-indirect"], v))),
                    18 => Some(("Tag_ABI_PCS_wchar_t", v.to_string())),
                    24 => Some(("Tag_ABI_align_needed", v.to_string())),
                    25 => Some(("Tag_ABI_align_preserved", v.to_string())),
                    26 => Some(("Tag_ABI_enum_size", pick(&["unused", "small", "int", "forced-int"], v))),
                    27 => Some(("Tag_ABI_HardFP_use", v.to_string())),
                    28 => Some((
                        "Tag_ABI_VFP_args",
                        pick(&["soft", "hard", "toolchain", "compatible"], v),
                    )),
                    30 => Some((
                        "Tag_ABI_optimization_goals",
                        pick(
                            &[
                                "none",
                                "prefer speed",
                                "aggressive speed",
                                "prefer size",
                                "aggressive size",
                                "prefer debug",
                                "aggressive debug",
                            ],
                            v,
                        ),
                    )),
                    31 => Some(("Tag_ABI_FP_optimization_goals", v.to_string())),
                    34 => Some(("Tag_CPU_unaligned_access", pick(&["none", "allowed"], v))),
                    44 => Some(("Tag_DIV_use", pick(&["if in architecture", "none", "allowed"], v))),
                    46 => Some(("Tag_DSP_extension", pick(&["none", "allowed"], v))),
                    _ => None,
                };
                out.extend(e);
            }
            q = subend.max(q + 5);
        }
        p = end.max(p + 4);
    }
    out
}

/// Find an optimisation flag among command-line tokens (the last one wins).
fn declared_level(producer: &str) -> Option<OptLevel> {
    let mut found = None;
    for tok in producer.split_whitespace() {
        let l = match tok {
            "-O0" => OptLevel::O0,
            "-O" | "-O1" => OptLevel::O1,
            "-O2" => OptLevel::O2,
            "-O3" | "-Ofast" => OptLevel::O3,
            "-Os" => OptLevel::Os,
            "-Oz" => OptLevel::Oz,
            "-Og" => OptLevel::Og,
            _ => continue,
        };
        found = Some(l);
    }
    found
}

/// The optimisation levels a recorded `Tag_ABI_optimization_goals` value is produced by.
fn goal_levels(family: Option<Compiler>, goal: &str) -> Option<Vec<OptLevel>> {
    use OptLevel::*;
    let gcc = family != Some(Compiler::Clang);
    Some(match goal {
        "aggressive debug" => vec![O0],
        "prefer speed" if gcc => vec![O1, Og],
        "prefer speed" => vec![O1, O2],
        "aggressive speed" if gcc => vec![O2, O3],
        "aggressive speed" => vec![O3],
        "prefer size" => vec![Os],
        "aggressive size" if gcc => vec![Os, Oz],
        "aggressive size" => vec![Oz],
        _ => return None,
    })
}

// ----- the report ---------------------------------------------------------------------------------

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Compiler {
    Gcc,
    Clang,
}

impl fmt::Display for Compiler {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Compiler::Gcc => "GCC",
            Compiler::Clang => "clang",
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Verdict {
    Yes,
    No,
    Unknown,
}

impl Verdict {
    pub fn label(self) -> &'static str {
        match self {
            Verdict::Yes => "yes",
            Verdict::No => "no",
            Verdict::Unknown => "unknown",
        }
    }
}

/// What the binary tells about one compiler flag.
#[derive(Clone, Debug)]
pub struct Finding {
    pub flag: &'static str,
    /// Conclusion from the code (and, for relocatable objects, its relocations and section layout).
    pub verdict: Verdict,
    /// 0..=1; 0 for `Unknown`.
    pub confidence: f32,
    pub evidence: Vec<String>,
    /// What the toolchain recorded about this flag (build attributes, producer string), if anything.
    /// A claim made by the file, kept apart from the evidence.
    pub declared: Option<(bool, String)>,
}

impl Finding {
    fn new(flag: &'static str) -> Finding {
        Finding {
            flag,
            verdict: Verdict::Unknown,
            confidence: 0.0,
            evidence: Vec::new(),
            declared: None,
        }
    }

    fn set(&mut self, yes: bool, confidence: f32, why: String) {
        self.verdict = if yes { Verdict::Yes } else { Verdict::No };
        self.confidence = confidence.clamp(0.0, 1.0);
        self.evidence.push(why);
    }

    fn note(&mut self, why: impl Into<String>) {
        self.evidence.push(why.into());
    }

    /// The best available answer: the code's verdict, else the declared value.
    pub fn effective(&self) -> Option<bool> {
        match self.verdict {
            Verdict::Yes => Some(true),
            Verdict::No => Some(false),
            Verdict::Unknown => self.declared.as_ref().map(|d| d.0),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct FlagReport {
    /// Compiler identification from .comment, e.g. "GCC: (Gentoo 16.2.1_p20260926 p1) 16.2.1 20260926".
    pub compiler: Option<String>,
    /// Flags recorded in debug info (DW_AT_producer) or a recorded command line, when present.
    /// These are a claim by the binary, not evidence.
    pub declared: Option<String>,
    /// Candidate levels with a confidence in 0..=1, best first, from the code alone. Levels that cannot
    /// be told apart for this code share similar scores.
    pub candidates: Vec<(OptLevel, f32)>,
    /// Human-readable observations that drove the optimisation-level guess.
    pub evidence: Vec<String>,

    /// Compiler family: from recorded strings when present, else from code style.
    pub family: Option<Compiler>,
    /// Family suggested by code style alone, with a confidence.
    pub family_from_code: Option<(Compiler, f32)>,
    pub family_evidence: Vec<String>,
    pub version: Option<String>,
    /// Architecture the instructions require, e.g. "ARMv7-M or ARMv8-M Mainline".
    pub arch: Option<&'static str>,
    pub arch_evidence: Vec<String>,
    /// Decoded `.ARM.attributes` (declared by the toolchain).
    pub attributes: Vec<(&'static str, String)>,
    /// Optimisation levels consistent with the recorded optimisation goal.
    pub declared_levels: Vec<OptLevel>,
    pub findings: Vec<Finding>,
    /// Places where what the file declares disagrees with what its code shows.
    pub contradictions: Vec<String>,
    /// Flags that leave no trace in this binary, with the reason.
    pub undecidable: Vec<(&'static str, &'static str)>,
    /// Best-guess command line.
    pub command_line: String,
}

impl FlagReport {
    pub fn best(&self) -> Option<OptLevel> {
        self.candidates.first().map(|c| c.0)
    }

    /// Candidates whose confidence is close to the best one: the levels that cannot be told apart.
    pub fn tied(&self) -> Vec<OptLevel> {
        let Some(best) = self.candidates.first() else {
            return Vec::new();
        };
        self.candidates
            .iter()
            .filter(|c| c.1 >= best.1 * 0.5)
            .map(|c| c.0)
            .collect()
    }

    /// The level to quote: the best code candidate, narrowed by the recorded goal when they agree.
    pub fn level(&self) -> Option<OptLevel> {
        let best = self.candidates.first()?;
        self.candidates
            .iter()
            .find(|c| self.declared_levels.contains(&c.0) && c.1 >= best.1 * 0.25)
            .or(Some(best))
            .map(|c| c.0)
    }

    pub fn finding(&self, flag: &str) -> Option<&Finding> {
        self.findings.iter().find(|f| f.flag == flag)
    }

    pub fn attribute(&self, tag: &str) -> Option<&str> {
        self.attributes.iter().find(|a| a.0 == tag).map(|a| a.1.as_str())
    }

    /// The text section of the CLI report.  `explain` lists every piece of evidence.
    pub fn render(&self, explain: bool) -> String {
        use std::fmt::Write;
        let mut o = String::new();
        let fam = match (self.family, &self.family_from_code) {
            (Some(f), _) => f.to_string(),
            (None, _) => "unknown".into(),
        };
        match &self.compiler {
            Some(c) => {
                // A linked image repeats the string once per object.
                let mut ids: Vec<&str> = Vec::new();
                for part in c.split("; ") {
                    if !ids.contains(&part) {
                        ids.push(part);
                    }
                }
                let _ = writeln!(o, "compiler:        {}", ids.join("; "));
            }
            None => {
                let how = match self.family_from_code {
                    Some((_, c)) => format!(" (from code style, {:.0}%)", c * 100.0),
                    None => String::new(),
                };
                let _ = writeln!(o, "compiler:        {fam}{how}");
            }
        }
        if let Some(d) = &self.declared {
            let _ = writeln!(o, "declared flags:  {d}");
        }
        if let Some(a) = self.arch {
            let cpu = self
                .attribute("Tag_CPU_name")
                .map(|c| format!("; declared CPU {c}"))
                .unwrap_or_default();
            let _ = writeln!(o, "target:          {a}{cpu}");
        }
        if !self.candidates.is_empty() {
            let best = self.candidates[0].1;
            let c: Vec<String> = self
                .candidates
                .iter()
                .filter(|c| c.1 >= best - 0.15)
                .map(|(l, s)| format!("{l} ({:.0}%)", s * 100.0))
                .collect();
            let decl = if self.declared_levels.is_empty() {
                String::new()
            } else {
                let d: Vec<String> = self.declared_levels.iter().map(|l| l.to_string()).collect();
                format!("; recorded goal: {}", d.join("/"))
            };
            let _ = writeln!(o, "optimisation:    {}{decl}", c.join(", "));
        }
        let pick = |v: Verdict| -> Vec<String> {
            self.findings
                .iter()
                .filter(|f| f.verdict == v)
                .map(|f| format!("{} ({:.0}%)", f.flag, f.confidence * 100.0))
                .collect()
        };
        let (on, off) = (pick(Verdict::Yes), pick(Verdict::No));
        if !on.is_empty() {
            let _ = writeln!(o, "flags in effect: {}", on.join(", "));
        }
        if !off.is_empty() {
            let _ = writeln!(o, "flags not used:  {}", off.join(", "));
        }
        let declared: Vec<String> = self
            .findings
            .iter()
            .filter(|f| f.verdict == Verdict::Unknown)
            .filter_map(|f| {
                f.declared
                    .as_ref()
                    .map(|d| format!("{} {}", f.flag, if d.0 { "on" } else { "off" }))
            })
            .collect();
        if !declared.is_empty() {
            let _ = writeln!(o, "declared only:   {}", declared.join(", "));
        }
        if !self.command_line.is_empty() {
            let _ = writeln!(o, "likely built as: {}", self.command_line);
        }
        for c in &self.contradictions {
            let _ = writeln!(o, "CONTRADICTION:   {c}");
        }
        if explain {
            for e in &self.family_evidence {
                let _ = writeln!(o, "  compiler: {e}");
            }
            for e in &self.arch_evidence {
                let _ = writeln!(o, "  target: {e}");
            }
            for e in &self.evidence {
                let _ = writeln!(o, "  optimisation: {e}");
            }
            for f in &self.findings {
                let conf = match f.verdict {
                    Verdict::Unknown => String::new(),
                    _ => format!(" ({:.0}%)", f.confidence * 100.0),
                };
                let _ = writeln!(o, "  {}: {}{conf}", f.flag, f.verdict.label());
                for e in &f.evidence {
                    let _ = writeln!(o, "      {e}");
                }
                if let Some((_, d)) = &f.declared {
                    let _ = writeln!(o, "      declared: {d}");
                }
            }
            for (name, value) in &self.attributes {
                let _ = writeln!(o, "  attribute {name}: {value}");
            }
            for (flag, why) in &self.undecidable {
                let _ = writeln!(o, "  cannot tell {flag}: {why}");
            }
        }
        o
    }

    /// The report as a JSON object (for the `--json` output).
    pub fn json(&self) -> String {
        fn q(s: &str) -> String {
            let mut o = String::from("\"");
            for c in s.chars() {
                match c {
                    '"' => o.push_str("\\\""),
                    '\\' => o.push_str("\\\\"),
                    '\n' => o.push_str("\\n"),
                    c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
                    c => o.push(c),
                }
            }
            o.push('"');
            o
        }
        let opt = |s: &Option<String>| s.as_deref().map_or("null".to_string(), q);
        let list = |v: &[String]| format!("[{}]", v.iter().map(|s| q(s)).collect::<Vec<_>>().join(","));
        let mut parts = Vec::new();
        parts.push(format!("\"compiler\":{}", opt(&self.compiler)));
        parts.push(format!(
            "\"compiler_family\":{}",
            self.family.map_or("null".to_string(), |f| q(&f.to_string()))
        ));
        parts.push(format!("\"compiler_evidence\":{}", list(&self.family_evidence)));
        parts.push(format!("\"declared\":{}", opt(&self.declared)));
        parts.push(format!("\"architecture\":{}", self.arch.map_or("null".to_string(), q)));
        let cands: Vec<String> = self
            .candidates
            .iter()
            .map(|(l, c)| format!("{{\"level\":{},\"confidence\":{c:.3}}}", q(&l.to_string())))
            .collect();
        parts.push(format!("\"optimisation\":[{}]", cands.join(",")));
        let dl: Vec<String> = self.declared_levels.iter().map(|l| l.to_string()).collect();
        parts.push(format!("\"optimisation_recorded_goal\":{}", list(&dl)));
        parts.push(format!("\"optimisation_evidence\":{}", list(&self.evidence)));
        let flags: Vec<String> = self
            .findings
            .iter()
            .map(|f| {
                format!(
                    "{{\"flag\":{},\"verdict\":{},\"confidence\":{:.2},\"evidence\":{},\"declared\":{}}}",
                    q(f.flag),
                    q(f.verdict.label()),
                    f.confidence,
                    list(&f.evidence),
                    f.declared.as_ref().map_or("null".to_string(), |(v, why)| format!(
                        "{{\"value\":{v},\"source\":{}}}",
                        q(why)
                    ))
                )
            })
            .collect();
        parts.push(format!("\"flags\":[{}]", flags.join(",")));
        let attrs: Vec<String> = self
            .attributes
            .iter()
            .map(|(k, v)| format!("{}:{}", q(k), q(v)))
            .collect();
        parts.push(format!("\"attributes\":{{{}}}", attrs.join(",")));
        parts.push(format!("\"contradictions\":{}", list(&self.contradictions)));
        let und: Vec<String> = self
            .undecidable
            .iter()
            .map(|(f, w)| format!("{}:{}", q(f), q(w)))
            .collect();
        parts.push(format!("\"undecidable\":{{{}}}", und.join(",")));
        parts.push(format!("\"command_line\":{}", q(&self.command_line)));
        format!("{{{}}}", parts.join(","))
    }
}

// ----- analysis ---------------------------------------------------------------------------------

/// Index of a level in `OptLevel::ALL`.
const O0: usize = 0;
const O1: usize = 1;
const O2: usize = 2;
const O3: usize = 3;
const OS: usize = 4;
const OZ: usize = 5;
const OG: usize = 6;

/// Does the code look unoptimised?  Arguments are stored to the frame on entry and most
/// instructions shuffle values to and from it.
fn looks_unoptimised(f: &Features) -> bool {
    let spill = f.arg_spills as f32 / f.funcs.max(1) as f32;
    let frame = f.frame_accesses as f32 / f.insns.max(1) as f32;
    spill >= 0.45 || frame >= 0.2
}

fn is_thumb2(f: &Features) -> bool {
    f.wide_mainline > 0 || f.it_blocks > 0
}

fn identify_compiler(f: &Features, image: &Image, r: &mut FlagReport) {
    // What the file says.
    let mut texts: Vec<&str> = image.meta.producers.iter().map(String::as_str).collect();
    texts.extend(image.comment.as_deref());
    texts.extend(image.producer.as_deref());
    let says_clang = texts.iter().any(|t| t.contains("clang"));
    let says_gcc = texts
        .iter()
        .any(|t| t.contains("GCC:") || t.contains("GNU C") || t.contains("GNU GIMPLE"));
    for t in &texts {
        let v = if let Some(p) = t.find("clang version ") {
            t[p + 14..].split_whitespace().next()
        } else if t.contains("GCC:") || t.contains("GNU C") {
            // The first token that looks like a version number after any parenthesised vendor text.
            let rest = t.rfind(')').map_or(*t, |p| &t[p + 1..]);
            rest.split_whitespace().find(|w| {
                w.split('.').count() >= 2
                    && w.split('.')
                        .all(|x| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit()))
            })
        } else {
            None
        };
        if r.version.is_none() {
            r.version = v.map(str::to_string);
        }
    }
    // What the code looks like.
    let (mut c, mut g) = (0.0f32, 0.0f32);
    let pads = f.push_r7_lr_pad + f.push_r3_pad + f.push_r4_pad;
    if pads > 0 {
        // With frame pointers kept, clang also pads with low registers: the habit says less.
        let framed = f.fp_nonleaf * 2 >= f.nonleaf_funcs.max(1);
        let w = pads.min(6) as f32 * if framed { 0.3 } else { 1.0 };
        c += w * f.push_r7_lr_pad as f32 / pads as f32;
        g += w * (f.push_r3_pad + f.push_r4_pad) as f32 / pads as f32;
        r.family_evidence.push(format!(
            "stack-alignment pushes: {} of {{r7, lr}} with r7 unused (clang), {} including r3 or an unused r4 (GCC)",
            f.push_r7_lr_pad,
            f.push_r3_pad + f.push_r4_pad
        ));
    }
    if f.outlined > 0 {
        c += 3.0 * f.outlined.min(2) as f32;
        r.family_evidence.push(format!(
            "{} OUTLINED_FUNCTION_n symbols (LLVM machine outliner)",
            f.outlined
        ));
    }
    if f.clones > 0 {
        g += 2.0 * f.clones.min(3) as f32;
        r.family_evidence.push(format!(
            "{} .constprop/.isra/.part function clones (GCC naming)",
            f.clones
        ));
    }
    let case_helpers = thumb1_case_helpers(image);
    if case_helpers > 0 {
        g += 3.0;
        r.family_evidence
            .push("uses __gnu_thumb1_case_* switch helpers (GCC, Thumb-1)".into());
    }
    if is_thumb2(f) && f.movw_movt >= 4 && f.movw_movt >= 2 * f.literal_loads {
        c += 2.0;
        r.family_evidence.push(format!(
            "addresses are built with movw/movt ({} pairs against {} literal-pool loads): clang's default on ARMv7-M",
            f.movw_movt, f.literal_loads
        ));
    } else if is_thumb2(f) && f.movw_movt == 0 && f.literal_loads >= 8 {
        g += 1.0;
        r.family_evidence.push(format!(
            "addresses come from literal pools ({} loads, no movw/movt): GCC's default (clang does this at -Oz)",
            f.literal_loads
        ));
    }
    // On Thumb-1 both compilers use `add r7, sp, #n`; on Thumb-2 clang uses `mov r7, sp`.
    if is_thumb2(f) && f.fp_add >= 3 && f.fp_mov == 0 {
        g += 3.0;
        r.family_evidence.push(format!(
            "{} frame pointers set up with `add r7, sp, #n` (GCC)",
            f.fp_add
        ));
    } else if f.fp_mov >= 3 && f.fp_add == 0 {
        c += 1.0;
        r.family_evidence
            .push(format!("{} frame pointers set up with `mov r7, sp`", f.fp_mov));
    }
    let total = c + g;
    if total >= 1.5 && (c - g).abs() >= 1.0 {
        let fam = if c > g { Compiler::Clang } else { Compiler::Gcc };
        r.family_from_code = Some((fam, c.max(g) / (total + 1.0)));
    }
    r.family = match (says_clang, says_gcc) {
        (true, false) => Some(Compiler::Clang),
        (false, true) => Some(Compiler::Gcc),
        (true, true) => {
            r.family_evidence
                .push("the file carries both GCC and clang identification strings (objects from both)".into());
            r.family_from_code.map(|x| x.0)
        }
        (false, false) => {
            if image.meta.present {
                r.family_evidence
                    .push("no compiler identification recorded in the file".into());
            }
            r.family_from_code.map(|x| x.0)
        }
    };
    if let (true, false) | (false, true) = (says_clang, says_gcc)
        && let Some((code, conf)) = r.family_from_code
        && Some(code) != r.family
        && conf >= 0.75
    {
        r.contradictions.push(format!(
            "the file identifies its compiler as {}, but the code is in the style of {code}",
            r.family.unwrap()
        ));
    }
}

fn thumb1_case_helpers(image: &Image) -> u32 {
    let n = |s: &str| s.starts_with("__gnu_thumb1_case_");
    (image.externals.values().filter(|s| n(s)).count() + image.symbols.iter().filter(|s| n(&s.name)).count()) as u32
}

fn identify_target(f: &Features, r: &mut FlagReport) {
    if f.insns == 0 {
        return;
    }
    let ev = &mut r.arch_evidence;
    let arch = if is_thumb2(f) {
        ev.push(format!(
            "{} Thumb-2 instructions that only ARMv7-M and ARMv8-M Mainline have ({} IT blocks)",
            f.wide_mainline, f.it_blocks
        ));
        ev.push(
            "ARMv7-M and ARMv8-M Mainline cannot be told apart unless security or v8-only instructions appear".into(),
        );
        match (f.dsp_insns > 0, f.fp_insns > 0) {
            (false, false) => "ARMv7-M or ARMv8-M Mainline",
            (true, false) => "ARMv7E-M or ARMv8-M Mainline with DSP",
            (false, true) => "ARMv7-M or ARMv8-M Mainline with FPU",
            (true, true) => "ARMv7E-M or ARMv8-M Mainline with DSP and FPU",
        }
    } else if f.wide_baseline > 0 || f.cbz > 0 || f.hw_divides > 0 {
        ev.push(format!(
            "no IT blocks or other Thumb-2 instructions, but {} wide branches/movw/movt, {} cbz, {} hardware divides",
            f.wide_baseline, f.cbz, f.hw_divides
        ));
        "ARMv8-M Baseline"
    } else {
        ev.push(format!(
            "all {} instructions are 16-bit Thumb-1 (plus bl): ARMv6-M code, or code for a larger core that happens to need nothing more",
            f.insns
        ));
        "ARMv6-M"
    };
    if f.dsp_insns > 0 {
        ev.push(format!("{} DSP-extension multiplies", f.dsp_insns));
    }
    if f.fp_insns > 0 {
        ev.push(format!("{} coprocessor (floating-point) instructions", f.fp_insns));
    }
    if f.hw_divides > 0 {
        ev.push(format!("{} udiv/sdiv instructions", f.hw_divides));
    }
    r.arch = Some(arch);
    // Cross-check against the recorded architecture.
    if let Some(decl) = r.attribute("Tag_CPU_arch").map(str::to_string) {
        let thumb1_only = decl.starts_with("v6") && decl.ends_with("-M");
        if thumb1_only && arch != "ARMv6-M" {
            r.contradictions.push(format!(
                "build attributes declare {decl} (Thumb-1 only), but the code uses instructions that need {arch}"
            ));
        }
        if decl == "v8-M.baseline" && is_thumb2(f) {
            r.contradictions.push(format!(
                "build attributes declare {decl}, but the code uses Thumb-2 instructions that need a Mainline core"
            ));
        }
    }
}

fn softmax(s: &[f32; 7], levels: &[usize]) -> Vec<(OptLevel, f32)> {
    let max = levels.iter().map(|&l| s[l]).fold(f32::MIN, f32::max);
    let exp: Vec<f32> = levels.iter().map(|&l| (s[l] - max).exp()).collect();
    let total: f32 = exp.iter().sum();
    let mut c: Vec<(OptLevel, f32)> = levels
        .iter()
        .zip(&exp)
        .map(|(&l, &e)| (OptLevel::ALL[l], e / total))
        .collect();
    c.sort_by(|a, b| b.1.total_cmp(&a.1));
    c
}

/// Optimisation level from the shape of the code.  GCC and clang leave different fingerprints,
/// so each has its own rules; with an unidentified compiler the GCC rules are used.
fn guess_level(f: &Features, thumb1_helpers: u32, r: &mut FlagReport) {
    let clang = r.family == Some(Compiler::Clang);
    let thumb2 = is_thumb2(f);
    let mut s = [0.0f32; 7];
    let ev = &mut r.evidence;
    if r.family.is_none() {
        ev.push("compiler not identified: using the rules for GCC".into());
    }

    // --- unoptimised code -----------------------------------------------------------
    let frame = f.frame_accesses as f32 / f.insns as f32;
    let what = format!(
        "{} of {} functions store their arguments to the stack on entry and {:.0}% of instructions access the frame",
        f.arg_spills,
        f.funcs,
        frame * 100.0
    );
    if looks_unoptimised(f) {
        s[O0] += 10.0;
        ev.push(format!("{what}: unoptimised code"));
    } else {
        s[O0] -= 10.0;
        ev.push(format!("{what}: optimised code"));
    }

    let loops = f.loops_top_tested + f.loops_entry_jump + f.loops_rotated;
    let (top, entry, rot) = if loops > 0 {
        (
            f.loops_top_tested as f32 / loops as f32,
            f.loops_entry_jump as f32 / loops as f32,
            f.loops_rotated as f32 / loops as f32,
        )
    } else {
        (0.0, 0.0, 0.0)
    };
    let nb = f.branch_adjacent + f.branch_separated;
    let na = f.starts_padded + f.starts_unpadded;
    let padded = if na > 0 {
        f.starts_padded as f32 / na as f32
    } else {
        0.0
    };
    // One sample is weak evidence (in a linked image, padding also appears between objects).
    let wa = na.min(3) as f32 / 3.0;
    let dup = if f.windows > 0 {
        f.repeated_windows as f32 / f.windows as f32
    } else {
        0.0
    };
    // A handful of loops is thin evidence: their shape counts in proportion to their number.
    let wl = loops.min(8) as f32 / 8.0;

    if clang {
        // --- clang ---------------------------------------------------------------------
        if loops > 0 {
            ev.push(format!(
                "{loops} loops: {} tested at the top (-Oz does not rotate loops), {} entered by a jump to the test, {} rotated",
                f.loops_top_tested, f.loops_entry_jump, f.loops_rotated
            ));
            s[OZ] += wl * (3.5 * top - 2.5 * (rot + entry));
            for l in [O1, O2, O3, OS] {
                s[l] += wl * (1.5 * (rot + entry) - 3.0 * top);
            }
            s[O1] += wl * 0.8 * entry.min(0.3) / 0.3;
        } else {
            ev.push("no loops: loop-shape evidence unavailable".into());
        }
        if f.outlined > 0 {
            ev.push(format!(
                "{} outlined functions: the machine outliner runs at -Oz",
                f.outlined
            ));
            s[OZ] += 4.0;
        }
        if f.push_r3_pad > 0 {
            ev.push(format!(
                "{} prologues push extra low registers to make room on the stack instead of adjusting sp (-Oz)",
                f.push_r3_pad
            ));
            s[OZ] += 2.5;
        } else if f.nonleaf_funcs >= 12 {
            s[OZ] -= 0.7;
        }
        if thumb2 && f.movw_movt == 0 && f.literal_loads >= 3 {
            ev.push(format!(
                "addresses and constants come from literal pools ({} loads) rather than movw/movt pairs (-Oz)",
                f.literal_loads
            ));
            s[OZ] += 2.5;
        } else if thumb2 && f.movw_movt >= 2 {
            ev.push(format!("{} movw/movt pairs (every level except -Oz)", f.movw_movt));
            s[OZ] -= 2.0;
        }
        if f.div_by_immediate + f.long_multiplies > 0 {
            ev.push(format!(
                "{} divisions by an immediate kept as udiv/sdiv (-Oz), {} long multiplies (reciprocal division elsewhere)",
                f.div_by_immediate, f.long_multiplies
            ));
            if f.div_by_immediate > 0 {
                s[OZ] += 2.5;
                for l in [O1, O2, O3, OS] {
                    s[l] -= 2.0;
                }
            } else {
                s[OZ] -= 1.5;
            }
        }
        if thumb2 && na > 0 {
            ev.push(format!(
                "{} of {na} function starts that needed padding for 4-byte alignment received it (clang aligns functions to 4 bytes except at -Os/-Oz)",
                f.starts_padded
            ));
            if padded >= 0.75 {
                for l in [O1, O2, O3] {
                    s[l] += 1.5 * wa;
                }
                s[OS] -= 2.0 * wa;
                s[OZ] -= 2.0 * wa;
            } else if padded <= 0.25 {
                for l in [O1, O2, O3] {
                    s[l] -= 2.0 * wa;
                }
                s[OS] += 1.5 * wa;
                s[OZ] += 1.5 * wa;
            }
        }
        if f.windows >= 150 && loops >= 2 {
            ev.push(format!(
                "{:.0}% of instruction windows repeat within their function (loop unrolling duplicates code at -O2/-O3)",
                dup * 100.0
            ));
            if dup >= 0.06 {
                s[O2] += 2.0;
                s[O3] += 2.0;
                for l in [O1, OS, OZ] {
                    s[l] -= 1.5;
                }
                // More duplication leans towards -O3, but the two overlap.
                if dup >= 0.115 {
                    s[O3] += 0.5;
                } else {
                    s[O2] += 0.3;
                }
            } else if dup <= 0.035 {
                s[O2] -= 1.5;
                s[O3] -= 1.5;
            }
        } else if !looks_unoptimised(f) {
            ev.push("too little looping code to tell -O1/-Os from -O2/-O3".into());
        }
        if !thumb2 {
            ev.push("on Thumb-1, clang's -O1 and -Os output differ very little: expect a tie".into());
        }
        r.candidates = softmax(&s, &[O0, O1, O2, O3, OS, OZ]);
        return;
    }

    // --- GCC ---------------------------------------------------------------------------
    if loops > 0 {
        ev.push(format!(
            "{loops} loops: {} test at the top (-Os), {} jump to a bottom test (-Og/-O0), {} guarded bottom-tested (-O1 and up)",
            f.loops_top_tested, f.loops_entry_jump, f.loops_rotated
        ));
        // Rotated loops occur at every level (the source may be written that way); loops tested
        // at the top and loops entered by a jump are the telling shapes.
        s[OS] += wl * (3.0 * top - 0.8 * rot - 2.0 * entry);
        if loops >= 4 && f.loops_entry_jump == 0 && top >= 0.2 {
            // -O1 and -Og leave some loops entered by a jump; -O2/-O3 rotate nearly all of them.
            s[OS] += 1.5;
        }
        if entry >= 0.15 {
            s[OS] -= 1.5 * wl;
        }
        // -Og keeps the source's loop shape: jumps to the test and tests at the top, few rotations.
        s[OG] += wl * (3.0 * entry + if entry > 0.0 { 1.5 * top } else { -0.5 * top } - 2.5 * rot);
        s[O1] += wl * (1.2 * rot - 2.5 * top - 0.8 * entry);
        for l in [O2, O3] {
            s[l] += wl * (1.2 * rot - 2.5 * (top + entry));
        }
    } else {
        ev.push("no loops: loop-shape evidence unavailable".into());
    }
    if f.div_by_immediate + f.long_multiplies > 0 {
        ev.push(format!(
            "{} divisions by an immediate kept as udiv/sdiv (-Os), {} long multiplies (reciprocal division at speed levels)",
            f.div_by_immediate, f.long_multiplies
        ));
        if f.div_by_immediate > 0 && f.long_multiplies <= f.div_by_immediate {
            s[OS] += 2.5;
            for l in [O1, O2, O3, OG] {
                s[l] -= 2.0;
            }
        } else if f.div_by_immediate == 0 {
            s[OS] -= 1.5;
        }
    }
    if nb >= 4 {
        let sep = ratio(f.branch_separated, f.branch_adjacent);
        ev.push(format!(
            "{} of {nb} conditional branches are separated from their compare (instruction scheduling: -O2/-O3/-Os)",
            f.branch_separated
        ));
        if sep >= 0.25 {
            s[O2] += 1.5;
            s[O3] += 1.5;
            s[OS] += 0.5;
            s[O1] -= 1.5;
            s[OG] -= 1.5;
        } else if sep <= 0.10 && nb >= 8 && thumb2 {
            s[O1] += 1.0;
            s[OG] += 1.0;
            s[O2] -= 1.0;
            s[O3] -= 1.0;
        }
    }
    if na > 0 {
        ev.push(format!(
            "{} of {na} function starts that needed padding for 4-byte alignment received it (-O2/-O3 align functions)",
            f.starts_padded
        ));
        if padded >= 0.75 {
            s[O2] += 1.5 * wa;
            s[O3] += 1.5 * wa;
            for l in [O1, OS, OG] {
                s[l] -= 1.5 * wa;
            }
        } else if padded <= 0.34 {
            s[O2] -= 2.0 * wa;
            s[O3] -= 2.0 * wa;
            for l in [O1, OS, OG] {
                s[l] += 0.5 * wa;
            }
        }
    }
    if thumb2 {
        if f.it_blocks == 0 && nb >= 6 {
            ev.push("no IT blocks despite conditional code: little if-conversion (-Og/-O0)".into());
            s[OG] += 0.5;
        } else if f.it_blocks > 0 {
            ev.push(format!("{} IT blocks (if-conversion: -O1 and up, -Os)", f.it_blocks));
            s[OG] -= 0.5;
        }
        if f.tail_calls > 0 {
            ev.push(format!(
                "{} tail calls (sibling-call optimisation: -O2, -O3, -Os)",
                f.tail_calls
            ));
            s[O1] -= 1.5;
            s[OG] -= 1.5;
        }
    }
    if !thumb2 && f.push_r3_pad > 0 {
        ev.push(format!(
            "{} prologues push extra low registers to make room on the stack instead of adjusting sp (a size optimisation)",
            f.push_r3_pad
        ));
        s[OS] += 1.5;
    }
    if thumb1_helpers > 0 {
        ev.push(
            "switches dispatch through __gnu_thumb1_case_* helpers, which GCC only uses when optimising for size"
                .into(),
        );
        s[OS] += 2.5;
        for l in [O1, O2, O3, OG] {
            s[l] -= 1.0;
        }
    }
    let mut o3 = 0.0;
    if f.clones > 0 {
        ev.push(format!(
            "{} function clone symbols (.constprop/.isra/.part): interprocedural cloning",
            f.clones
        ));
        o3 += 0.6;
    }
    if f.windows >= 40 {
        ev.push(format!(
            "{:.0}% of instruction windows repeat within their function (unrolling, peeling and loop versioning duplicate code at -O3)",
            dup * 100.0
        ));
        if dup >= 0.045 {
            o3 += 0.65;
        } else if dup <= 0.025 && loops >= 2 {
            o3 -= 1.0;
        }
    }
    if f.loops_rotated > 0 && f.loops_with_remainder > 0 {
        ev.push(format!(
            "{} of {} bottom-tested loops are followed by remainder handling{}",
            f.loops_with_remainder,
            f.loops_rotated,
            if f.dual_accesses > 0 {
                format!("; {} paired memory accesses", f.dual_accesses)
            } else {
                String::new()
            }
        ));
        if f.loops_with_remainder * 4 >= f.loops_rotated {
            o3 += 0.6;
        }
    }
    // Duplication speaks for -O3 over -O2, but -O2 also unrolls short constant loops completely:
    // lean, do not decide.
    s[O3] += o3;
    if o3 == 0.0 {
        ev.push("nothing distinguishes -O2 from -O3 in this code".into());
    }
    if !thumb2 && f.loops_entry_jump == 0 && s[O1] > s[OS] {
        // Thumb-1 leaves -Os little room to differ from -O1.
        ev.push("on Thumb-1, GCC's -O1 and -Os output differ very little: reported as a tie".into());
        s[OS] = s[O1] - 0.2;
    }
    // GCC's -Oz differs from -Os only in a few instruction choices that this code may not contain.
    s[OZ] = s[OS] - 0.1;
    ev.push("GCC's -Oz output is (nearly) identical to -Os: the two are reported together".into());
    r.candidates = softmax(&s, &[O0, O1, O2, O3, OS, OZ, OG]);
}

/// The counterpart of a flag: `-fno-x` for `-fx`, `-munaligned-access` for `-mno-unaligned-access`, ...
fn negation(flag: &str) -> Option<String> {
    let (p, rest) = flag.split_at(2);
    if p != "-f" && p != "-m" {
        return None;
    }
    Some(match rest.strip_prefix("no-") {
        Some(x) => format!("{p}{x}"),
        None => format!("{p}no-{rest}"),
    })
}

fn flag_findings(f: &Features, image: &Image, r: &mut FlagReport) {
    let meta = &image.meta;
    let unopt = looks_unoptimised(f);
    let thumb2 = is_thumb2(f);
    let tokens: Vec<String> = r
        .declared
        .as_deref()
        .unwrap_or("")
        .split_whitespace()
        .filter(|t| t.starts_with('-'))
        .map(str::to_string)
        .collect();
    // Adjacent byte loads are only merged into word loads at -O2, -O3, -Os and -Oz.
    let merges_loads = !unopt
        && r.candidates
            .first()
            .is_some_and(|c| !matches!(c.0, OptLevel::O0 | OptLevel::O1 | OptLevel::Og) && c.1 >= 0.5);
    let mut out: Vec<Finding> = Vec::new();
    let sec = |pred: &dyn Fn(&str) -> bool| meta.sections.iter().filter(|s| s.3 > 0 && pred(&s.0)).count();
    let reloc = |pred: &dyn Fn(&crate::image::RelocInfo) -> bool| meta.relocs.iter().filter(|x| pred(x)).count();

    // -fomit-frame-pointer
    let mut x = Finding::new("-fomit-frame-pointer");
    let fp = f.fp_leaf + f.fp_nonleaf;
    if f.nonleaf_funcs >= 2 && f.fp_nonleaf * 10 >= f.nonleaf_funcs * 8 {
        x.set(
            false,
            0.9,
            format!(
                "{} of {} non-leaf functions set up a frame pointer in r7",
                f.fp_nonleaf, f.nonleaf_funcs
            ),
        );
    } else if fp == 0 && f.nonleaf_funcs >= 3 {
        x.set(
            true,
            (0.6 + 0.02 * f.nonleaf_funcs as f32).min(0.9),
            format!("none of {} functions sets up a frame pointer", f.funcs),
        );
        x.note("frame pointers are omitted by default by GCC at -O1 and above, and by clang for bare-metal ARM: the flag itself may not have been given");
    } else {
        x.note(format!(
            "{fp} of {} functions set up a frame pointer: too few to tell",
            f.funcs
        ));
    }
    out.push(x);

    // -momit-leaf-frame-pointer
    let mut x = Finding::new("-momit-leaf-frame-pointer");
    if f.fp_nonleaf >= 2 {
        if f.fp_leaf == 0 && f.leaf_funcs >= 2 {
            x.set(
                true,
                0.8,
                format!(
                    "{} non-leaf functions keep a frame pointer, none of {} leaf functions does",
                    f.fp_nonleaf, f.leaf_funcs
                ),
            );
        } else if f.fp_leaf >= 2 {
            x.set(
                false,
                0.8,
                format!("{} leaf functions set up a frame pointer", f.fp_leaf),
            );
        }
    } else {
        x.note("no frame pointers are kept, so there is nothing to omit in leaf functions");
    }
    out.push(x);

    // -fropi
    let mut x = Finding::new("-fropi");
    let rel_ro = reloc(&|q| {
        q.in_code
            && matches!(q.rtype, 3 | 49 | 50)
            && matches!(
                q.target,
                crate::image::RelocTarget::ReadOnlyData | crate::image::RelocTarget::Code
            )
    });
    let abs_ro = reloc(&|q| {
        q.in_code
            && matches!(q.rtype, 2 | 47 | 48)
            && matches!(
                q.target,
                crate::image::RelocTarget::ReadOnlyData | crate::image::RelocTarget::Code
            )
    });
    if meta.relocatable && rel_ro + abs_ro >= 1 {
        x.note(format!(
            "code relocations against read-only data and functions: {rel_ro} PC-relative, {abs_ro} absolute"
        ));
        if rel_ro >= 1 && abs_ro == 0 {
            x.set(
                true,
                if rel_ro >= 3 { 0.95 } else { 0.8 },
                "all such references are PC-relative".into(),
            );
        } else if abs_ro >= 1 && rel_ro == 0 {
            x.set(
                false,
                if abs_ro >= 3 { 0.95 } else { 0.8 },
                "all such references are absolute".into(),
            );
        }
    } else if f.add_pc >= 2 && f.abs_ro_refs * 4 <= f.add_pc {
        x.set(
            true,
            if f.add_pc >= 4 { 0.85 } else { 0.6 },
            format!(
                "{} addresses are formed relative to pc (`add rX, pc`) against {} literals that look like absolute addresses of read-only memory",
                f.add_pc, f.abs_ro_refs
            ),
        );
    } else if f.abs_ro_refs >= 2 && f.add_pc * 4 <= f.abs_ro_refs {
        x.set(
            false,
            if f.abs_ro_refs >= 4 { 0.85 } else { 0.65 },
            format!(
                "{} absolute addresses of read-only memory are formed in code ({} PC-relative)",
                f.abs_ro_refs, f.add_pc
            ),
        );
    } else {
        x.note("the code takes no (or too few) addresses of constants or functions");
    }
    out.push(x);

    // -frwpi
    let mut x = Finding::new("-frwpi");
    let sb = reloc(&|q| matches!(q.rtype, 9 | 87..=89));
    let abs_rw =
        reloc(&|q| q.in_code && matches!(q.rtype, 2 | 47 | 48) && q.target == crate::image::RelocTarget::WritableData);
    if sb > 0 {
        x.set(true, 0.99, format!("{sb} static-base-relative relocations"));
    } else if f.r9_reads >= 2 && f.r9_writes == 0 {
        x.set(
            true,
            0.8,
            format!(
                "r9 is read {} times and never written: it holds the static base",
                f.r9_reads
            ),
        );
    } else if (abs_rw >= 2 || f.abs_rw_refs >= 2) && (f.r9_reads == 0 || f.r9_writes > 0) {
        x.set(
            false,
            0.9,
            format!(
                "writable data is addressed absolutely ({} references) and r9 is {}",
                abs_rw.max(f.abs_rw_refs as usize),
                if f.r9_writes > 0 {
                    "used as a scratch register"
                } else {
                    "never used as a base"
                }
            ),
        );
    } else {
        x.note("the code does not address writable data (or the image does not contain its data segments)");
    }
    out.push(x);

    // -fno-jump-tables
    let mut x = Finding::new("-fno-jump-tables");
    let helpers = thumb1_case_helpers(image);
    let tables = f.table_branches + f.computed_jumps + helpers;
    if tables > 0 {
        x.set(
            false,
            0.95,
            format!(
                "{} table branches, {} computed jumps, {} switch helper routines: jump tables are in use",
                f.table_branches, f.computed_jumps, helpers
            ),
        );
    } else if f.dense_compare_chains > 0 {
        let why = format!(
            "{} functions compare one register against five or more closely spaced constants (longest: {}) and no jump table exists anywhere",
            f.dense_compare_chains, f.longest_compare_chain
        );
        if unopt && r.family != Some(Compiler::Clang) {
            x.note(why);
            x.note("unoptimised GCC code often lowers such switches to compare chains anyway: not conclusive");
        } else {
            x.set(true, (0.55 + 0.1 * f.dense_compare_chains as f32).min(0.8), why);
        }
    } else {
        x.note("no switch large and dense enough for a jump table to be worthwhile");
    }
    out.push(x);

    // -mno-unaligned-access
    let mut x = Finding::new("-mno-unaligned-access");
    if !thumb2 && f.hw_divides == 0 && f.wide_baseline == 0 {
        x.note("ARMv6-M has no unaligned access at all: the flag changes nothing on this target");
    } else if f.assembled_words >= 2 && merges_loads {
        x.set(
            true,
            (0.55 + 0.05 * f.assembled_words as f32).min(0.7),
            format!(
                "{} words are assembled from single bytes in optimised code, where one unaligned load would do",
                f.assembled_words
            ),
        );
    } else if f.odd_word_access > 0 {
        // Compilers emit these with and without the flag (the base register's alignment is
        // unknown to us), so they decide nothing.
        x.note(format!(
            "{} word or halfword accesses at odd offsets, which occur with and without the flag: not conclusive",
            f.odd_word_access
        ));
    } else {
        x.note("the code contains no access that would have to be unaligned");
    }
    out.push(x);

    // -fshort-enums
    let mut x = Finding::new("-fshort-enums");
    x.note("the size of enumeration types is not visible in machine code without knowing the source");
    out.push(x);

    // -ffunction-sections / -fdata-sections
    let mut x = Finding::new("-ffunction-sections");
    let generic = |n: &str| {
        [
            ".text.unlikely",
            ".text.startup",
            ".text.hot",
            ".text.exit",
            ".text.cold",
        ]
        .iter()
        .any(|p| n.starts_with(p))
    };
    let per_fn = sec(&|n| n.starts_with(".text.") && !generic(n));
    if meta.relocatable {
        if per_fn > 0 {
            x.set(true, 0.95, format!("{per_fn} sections named .text.<function>"));
        } else if f.funcs >= 2 {
            x.set(false, 0.9, format!("{} functions share one .text section", f.funcs));
        }
    } else {
        x.note("section names do not survive linking");
    }
    out.push(x);
    let mut x = Finding::new("-fdata-sections");
    let merged = |n: &str| n.starts_with(".rodata.str") || n.starts_with(".rodata.cst") || n.starts_with(".data.rel");
    let per_obj =
        sec(&|n| (n.starts_with(".data.") || n.starts_with(".bss.") || n.starts_with(".rodata.")) && !merged(n));
    let shared = sec(&|n| n == ".data" || n == ".bss" || n == ".rodata");
    if meta.relocatable {
        if per_obj > 0 {
            x.set(
                true,
                0.95,
                format!("{per_obj} sections named .data.<object>, .bss.<object> or .rodata.<object>"),
            );
        } else if shared > 0 && image.symbols.iter().filter(|s| s.kind == SymKind::Object).count() >= 2 {
            x.set(false, 0.85, "several objects share .data/.bss/.rodata".into());
        }
    } else {
        x.note("section names do not survive linking");
    }
    out.push(x);

    // -fstack-protector
    let mut x = Finding::new("-fstack-protector");
    let has = |n: &str| {
        meta.undefined.iter().any(|s| s == n)
            || image.symbols.iter().any(|s| s.name == n)
            || image.externals.values().any(|s| s == n)
    };
    if has("__stack_chk_fail") || has("__stack_chk_guard") {
        x.set(true, 0.95, "references __stack_chk_fail / __stack_chk_guard".into());
    } else if f.funcs >= 5 {
        x.set(
            false,
            0.6,
            "no reference to __stack_chk_fail or __stack_chk_guard".into(),
        );
        x.note(
            "plain -fstack-protector only instruments functions with character arrays, so it can be on without a trace",
        );
    }
    out.push(x);

    // -g
    let mut x = Finding::new("-g");
    if sec(&|n| n == ".debug_info") > 0 {
        x.set(true, 1.0, "the file contains DWARF debug information".into());
    } else if meta.present {
        x.set(
            false,
            0.7,
            "no debug sections (they may also have been stripped)".into(),
        );
    }
    out.push(x);

    // -fpic
    let mut x = Finding::new("-fpic");
    let got = reloc(&|q| matches!(q.rtype, 24..=26 | 95..=97));
    if got > 0 {
        x.set(true, 0.95, format!("{got} GOT-relative relocations"));
    } else if sec(&|n| n == ".got") > 0 {
        x.set(true, 0.7, "the image has a global offset table".into());
    } else if meta.relocatable && reloc(&|q| q.in_code && q.target != crate::image::RelocTarget::Code) >= 2 {
        x.set(false, 0.85, "data is referenced without a global offset table".into());
    }
    out.push(x);

    // -mlong-calls
    let mut x = Finding::new("-mlong-calls");
    if f.literal_calls >= 2 && f.direct_extern_calls == 0 && (meta.relocatable || f.literal_calls >= f.direct_calls) {
        x.set(
            true,
            0.75,
            format!(
                "{} calls go through an address loaded from the literal pool and none is a direct bl to another object",
                f.literal_calls
            ),
        );
    } else if f.direct_extern_calls >= 2 {
        x.set(
            false,
            0.9,
            format!(
                "{} direct bl calls to functions defined elsewhere",
                f.direct_extern_calls
            ),
        );
    }
    out.push(x);

    // -mfloat-abi=soft
    let mut x = Finding::new("-mfloat-abi=soft");
    if f.fp_insns > 0 {
        x.set(false, 0.9, format!("{} floating-point instructions", f.fp_insns));
    } else if f.soft_float_calls > 0 {
        x.set(
            true,
            0.85,
            format!("{} calls to software floating-point routines", f.soft_float_calls),
        );
    } else {
        x.note("the code performs no floating-point arithmetic");
    }
    out.push(x);

    // -flto
    let mut x = Finding::new("-flto");
    let lto = sec(&|n| n.starts_with(".gnu.lto_") || n == ".llvmbc" || n == ".llvm.lto");
    if lto > 0 {
        x.set(true, 0.95, format!("{lto} LTO sections"));
    } else if meta.relocatable {
        x.set(false, 0.9, "a relocatable object without LTO sections".into());
    } else {
        x.note("link-time optimisation leaves no reliable trace in a linked image");
    }
    out.push(x);

    // -fno-inline
    let mut x = Finding::new("-fno-inline");
    if !unopt && f.local_tiny_single_caller >= 3 {
        x.set(
            true,
            0.5,
            format!(
                "{} tiny static functions with a single caller were not inlined in optimised code",
                f.local_tiny_single_caller
            ),
        );
        x.note("`noinline` attributes in the source have the same effect");
    }
    out.push(x);

    // What the toolchain recorded.
    let attr = |tag: &str| r.attribute(tag).map(str::to_string);
    let has_attrs = !r.attributes.is_empty();
    for x in &mut out {
        let from_attr: Option<(bool, String)> = match x.flag {
            // An absent tag has the value 0: absolute addressing.
            "-fropi" => attr("Tag_ABI_PCS_RO_data")
                .map(|v| (v == "PC-relative", format!("Tag_ABI_PCS_RO_data: {v}")))
                .or_else(|| has_attrs.then(|| (false, "no Tag_ABI_PCS_RO_data: absolute addressing".to_string()))),
            "-frwpi" => attr("Tag_ABI_PCS_R9_use")
                .map(|v| (v == "SB", format!("Tag_ABI_PCS_R9_use: {v}")))
                .or_else(|| {
                    attr("Tag_ABI_PCS_RW_data").map(|v| (v == "SB-relative", format!("Tag_ABI_PCS_RW_data: {v}")))
                })
                .or_else(|| {
                    has_attrs.then(|| (false, "no Tag_ABI_PCS_R9_use: r9 is an ordinary register".to_string()))
                }),
            "-mno-unaligned-access" => {
                attr("Tag_CPU_unaligned_access").map(|v| (v == "none", format!("Tag_CPU_unaligned_access: {v}")))
            }
            "-fshort-enums" => attr("Tag_ABI_enum_size").map(|v| (v == "small", format!("Tag_ABI_enum_size: {v}"))),
            "-mfloat-abi=soft" => attr("Tag_ABI_VFP_args").map(|v| (v == "soft", format!("Tag_ABI_VFP_args: {v}"))),
            "-fpic" => attr("Tag_ABI_PCS_GOT_use")
                .filter(|v| v == "GOT-indirect")
                .map(|v| (true, format!("Tag_ABI_PCS_GOT_use: {v}"))),
            _ => None,
        };
        let neg = negation(x.flag);
        let from_cmd = tokens.iter().rev().find_map(|t| {
            let t = t.split('=').next().unwrap_or(t);
            let base = x.flag.split('=').next().unwrap_or(x.flag);
            if x.flag.contains('=') {
                tokens
                    .iter()
                    .any(|t| t == x.flag)
                    .then(|| (true, format!("recorded command line: {}", x.flag)))
            } else if t == base {
                Some((true, format!("recorded command line: {t}")))
            } else if Some(t) == neg.as_deref() {
                Some((false, format!("recorded command line: {t}")))
            } else {
                None
            }
        });
        x.declared = from_cmd.or(from_attr);
    }
    // Contradictions between declarations and code.
    for x in &out {
        if let Some((d, src)) = &x.declared
            && x.verdict != Verdict::Unknown
            && x.confidence >= 0.75
            && *d != (x.verdict == Verdict::Yes)
            // Omitted frame pointers are the default; their absence does not contradict anything.
            && x.flag != "-fomit-frame-pointer"
            && x.flag != "-g"
        {
            r.contradictions.push(format!(
                "{} is declared {} ({src}), but the code says {}: {}",
                x.flag,
                if *d { "on" } else { "off" },
                x.verdict.label(),
                x.evidence.last().cloned().unwrap_or_default()
            ));
        }
    }
    r.findings = out;
    r.undecidable = vec![
        (
            "-fshort-enums",
            "enumeration sizes are only visible through build attributes or the source",
        ),
        (
            "-ffast-math",
            "only affects floating-point code generation; nothing to observe without it, and little with it",
        ),
        (
            "-fno-builtin / -ffreestanding",
            "calls to memcpy/memset may come from the source or from the compiler; their absence proves nothing",
        ),
        (
            "-fno-strict-aliasing / -fwrapv",
            "they only remove optimisations that would have needed specific source patterns",
        ),
        (
            "-mtune",
            "tuning for a CPU changes instruction selection too subtly to separate from version differences",
        ),
        (
            "-mcpu within one architecture",
            "cores sharing an instruction set (e.g. Cortex-M0, M0+ and M1) produce the same code",
        ),
        (
            "-W..., -std=..., -D..., -I...",
            "diagnostics, language dialect, macros and include paths leave no trace in machine code",
        ),
    ];
}

fn reconstruct(f: &Features, r: &FlagReport) -> String {
    let mut parts: Vec<String> = Vec::new();
    let clang = r.family == Some(Compiler::Clang);
    parts.push(match r.family {
        Some(Compiler::Clang) => "clang".into(),
        Some(Compiler::Gcc) => "arm-none-eabi-gcc".into(),
        None => "cc".into(),
    });
    let cpu = r.attribute("Tag_CPU_name").filter(|c| c.starts_with("cortex"));
    let (triple, march, default_cpu) = match r.arch {
        Some("ARMv6-M") => ("armv6m-none-eabi", "armv6s-m", None),
        Some("ARMv8-M Baseline") => ("armv8m.base-none-eabi", "armv8-m.base", None),
        Some(a) if a.contains("DSP") => ("armv7em-none-eabi", "armv7e-m", Some("cortex-m4")),
        Some(_) => ("armv7m-none-eabi", "armv7-m", None),
        None => ("arm-none-eabi", "", None),
    };
    // A recorded v8-M architecture is more specific than what the instructions show.
    let decl_arch = r.attribute("Tag_CPU_arch").unwrap_or("");
    let triple = if decl_arch == "v8-M.mainline" && r.arch.is_some_and(|a| a.contains("Mainline")) {
        "armv8m.main-none-eabi"
    } else {
        triple
    };
    if clang {
        parts.push(format!("--target={triple}"));
    }
    match cpu.or(default_cpu) {
        Some(c) => parts.push(format!("-mcpu={c}")),
        None if !clang && !march.is_empty() => parts.push(format!(
            "-march={}",
            if decl_arch == "v8-M.mainline" {
                "armv8-m.main"
            } else {
                march
            }
        )),
        None => {}
    }
    parts.push("-mthumb".into());
    // Levels the code cannot separate are quoted together, narrowed by the recorded goal.
    let tied = r.tied();
    let narrowed: Vec<OptLevel> = tied.iter().copied().filter(|l| r.declared_levels.contains(l)).collect();
    let quoted = if narrowed.is_empty() { tied } else { narrowed };
    if !quoted.is_empty() {
        let q: Vec<String> = quoted.iter().map(|l| l.to_string()).collect();
        parts.push(q.join("|"));
    }
    let level = r.level();
    for x in &r.findings {
        let decl_on = x.declared.as_ref().is_some_and(|d| d.0);
        let yes = x.verdict == Verdict::Yes && x.confidence >= 0.6;
        let no = x.verdict == Verdict::No && x.confidence >= 0.75;
        match x.flag {
            "-fomit-frame-pointer" => {
                // Keeping frame pointers is GCC's default at -O0, so it is only quoted elsewhere.
                if no && (clang || level != Some(OptLevel::O0)) {
                    parts.push("-fno-omit-frame-pointer".into());
                } else if yes && level == Some(OptLevel::O0) && !clang {
                    parts.push(x.flag.into());
                }
            }
            "-fshort-enums" => {
                // Only worth stating where it is not the default (it is for arm-none-eabi GCC).
                if let Some((d, _)) = &x.declared {
                    if *d && clang {
                        parts.push("-fshort-enums".into());
                    } else if !*d && !clang {
                        parts.push("-fno-short-enums".into());
                    }
                }
            }
            "-mno-unaligned-access" => {
                // Meaningless on ARMv6-M; quote it only when the code or the attributes say so on a larger core.
                if (yes || (decl_on && x.verdict == Verdict::Unknown)) && is_thumb2(f) {
                    parts.push(x.flag.into());
                }
            }
            "-fno-inline"
            | "-fstack-protector"
            | "-fpic"
            | "-mlong-calls"
            | "-flto"
            | "-g"
            | "-ffunction-sections"
            | "-fdata-sections"
            | "-fno-jump-tables"
            | "-fropi"
            | "-frwpi"
            | "-momit-leaf-frame-pointer"
            | "-mfloat-abi=soft" => {
                if x.flag == "-fno-inline" {
                    continue;
                }
                if yes || (decl_on && x.verdict == Verdict::Unknown) {
                    parts.push(x.flag.into());
                }
            }
            _ => {}
        }
    }
    parts.join(" ")
}

/// Identify how an image was built: compiler, target and flags, each with its evidence.
pub fn detect(image: &Image) -> FlagReport {
    let f = features(image);
    let mut report = FlagReport {
        compiler: image.comment.clone(),
        attributes: build_attributes(&image.meta.attributes),
        ..Default::default()
    };
    // The recorded command line, or failing that the longest producer string.
    let mut producers: Vec<&String> = image
        .meta
        .producers
        .iter()
        .filter(|p| !p.starts_with("GCC: "))
        .collect();
    producers.extend(image.producer.as_ref());
    producers.sort_by_key(|p| std::cmp::Reverse(p.len()));
    report.declared = image
        .meta
        .command_line
        .clone()
        .or_else(|| producers.first().filter(|p| p.contains(" -")).map(|p| p.to_string()));
    identify_compiler(&f, image, &mut report);
    if let Some(goal) = report.attribute("Tag_ABI_optimization_goals")
        && let Some(levels) = goal_levels(report.family, goal)
    {
        report.declared_levels = levels;
    }
    let declared_flag = report.declared.as_deref().and_then(declared_level);
    if let Some(p) = &report.declared {
        match declared_flag {
            Some(l) => report.evidence.push(format!(
                "the recorded command line declares {l} (a claim by the binary, not used for the guess)"
            )),
            None if p.contains(" -") => report
                .evidence
                .push("the recorded command line has no -O flag (GCC omits it at -O0)".into()),
            None => {}
        }
    }
    if f.funcs == 0 || f.insns == 0 {
        report
            .evidence
            .push("no decodable functions: nothing to base a guess on".into());
        // Section names and symbols still say something (a slim LTO object has no code at all).
        flag_findings(&f, image, &mut report);
        return report;
    }
    identify_target(&f, &mut report);
    guess_level(&f, thumb1_case_helpers(image), &mut report);
    flag_findings(&f, image, &mut report);

    // Declared optimisation against the code.
    let conf = |l: OptLevel| report.candidates.iter().find(|c| c.0 == l).map_or(0.0, |c| c.1);
    if let Some(best) = report.candidates.first().copied() {
        if let Some(decl) = declared_flag {
            // GCC -Og and clang -Og/-O1 etc.: compare within what the code can distinguish.
            let alias = match (decl, report.family) {
                (OptLevel::Og, Some(Compiler::Clang)) => OptLevel::O1,
                (d, _) => d,
            };
            if (alias == OptLevel::O0) != (best.0 == OptLevel::O0) {
                report.contradictions.push(format!(
                    "the recorded command line declares {decl}, but the code is {}",
                    if best.0 == OptLevel::O0 {
                        "unoptimised"
                    } else {
                        "optimised"
                    }
                ));
            } else if conf(alias) < best.1 * 0.2 {
                report.evidence.push(format!(
                    "the code looks more like {} than the declared {decl} ({:.0}% against {:.0}%); optimised levels are hard to separate, so this is not counted as a contradiction",
                    best.0,
                    best.1 * 100.0,
                    conf(alias) * 100.0
                ));
            }
        }
        if !report.declared_levels.is_empty() {
            let unopt_decl = report.declared_levels == [OptLevel::O0];
            if unopt_decl != (best.0 == OptLevel::O0) {
                let d: Vec<String> = report.declared_levels.iter().map(|l| l.to_string()).collect();
                report.contradictions.push(format!(
                    "build attributes record the optimisation goal of {}, but the code is {}",
                    d.join("/"),
                    if best.0 == OptLevel::O0 {
                        "unoptimised"
                    } else {
                        "optimised"
                    }
                ));
            }
        }
    }
    report.command_line = reconstruct(&f, &report);
    report
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn declared_flag_parsing() {
        assert_eq!(
            declared_level("GNU C17 16.2.1 -mthumb -mcpu=cortex-m3 -g -O2"),
            Some(OptLevel::O2)
        );
        assert_eq!(declared_level("GNU C17 -Os -O3"), Some(OptLevel::O3));
        assert_eq!(declared_level("GNU C17 13.2.1 -mthumb -g"), None);
        assert_eq!(OptLevel::Og.to_string(), "-Og");
    }

    #[test]
    fn empty_image_has_no_candidates() {
        let r = detect(&Image::default());
        assert!(r.candidates.is_empty());
        assert_eq!(r.best(), None);
    }
}