synth-backend 0.65.0

ARM encoder, ELF builder, vector table, linker scripts, and MPU configuration
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
//! #778 phase 2 (v0.47) — statically-evident loop trip counts + the `--wcet-hints`
//! sound-checker seam, over the FINAL Thumb-2 instruction stream.
//!
//! Phase 1 declined EVERY backward branch. This module upgrades exactly the
//! shapes it can PROVE and keeps declining everything else:
//!
//! - A **loop region** is `[head..=closer]` where `closer` is a backward
//!   `BOffset`/`BCondOffset` targeting `head`. Regions must nest properly.
//! - A region is **proven** when a tiny symbolic walk over its body shows the
//!   canonical counted-loop induction: a counter living in an SP-relative word
//!   slot, written EXACTLY once per iteration with `old + step` (const step),
//!   and an exit comparison against a CONST bound that provably fires once the
//!   counter reaches it (head-test `cmp; b<cond> → resume` or bottom-test
//!   conditional backward branch). The counter's INIT must be a const store
//!   found on the straight-line path into the head (function prologue for a
//!   top-level loop, the parent body for a nested one).
//! - Every instruction's worst-case cycle cost is then multiplied by its proven
//!   worst-case execution count: `K+1` for a head-test region (the head check
//!   runs once more than the body), `K` for a bottom-test region, multiplied
//!   through nesting. Anything unproven → the function keeps the loud `loop`
//!   decline.
//!
//! ## Soundness argument (why the multiplier is an upper bound)
//!
//! For a proven region entered with counter slot value `v`:
//!
//! 1. **Single entry**: the global branch discipline (below) guarantees control
//!    enters the region only at `head` — every other branch in the function is
//!    either a region closer (targeting its own head) or a region exit
//!    (targeting exactly its innermost region's fall-through resume point).
//! 2. **Monotone counter**: the walk proves the ONLY write to the counter slot
//!    on the straight-line body is `old + step`, and no sub-word/dynamic store
//!    can alias it (any such store taints the slot and fails the proof). SP
//!    itself cannot move inside a region (`push`/`pop`/SP-writes decline), and
//!    non-SP-based stores cannot alias the SP frame: WASM has no address-of-
//!    local, so synth-generated non-SP stores address the linear-memory/global
//!    image, which is layout-disjoint from the native stack frame (a sandbox-
//!    respecting execution — the same precondition the bound already carries).
//! 3. **Guaranteed exit**: the proven exit predicate `(v + a) REL bound` fires
//!    by the K-th head evaluation, where `K` is computed from (init, step,
//!    bound) in exact i64/u64 arithmetic WITH static no-overflow checks over
//!    the whole counter walk (a wrap would break monotonicity, so any possible
//!    wrap fails the proof). Early exits (extra conditional exits, traps) only
//!    REDUCE iteration counts, so ignoring their predicates is conservative.
//! 4. Anything the walk does not precisely model kills the affected symbolic
//!    state (registers → Top, flags → unknown, slots → tainted), which can only
//!    cause a DECLINE, never a smaller bound.
//!
//! **Equality exits are hint-gated**: a `(v + a) == bound` exit is the one shape
//! where an off-by-one (step not dividing the distance) flips terminating into
//! infinite. synth derives the trip count and verifies divisibility, but only
//! CONSUMES it when an explicit `--wcet-hints` entry asserts a bound the derived
//! count respects (`derived ≤ hint`) — the scry-oracle seam: the untrusted hint
//! asserts intent, synth's checker re-derives and cross-checks, and the emitted
//! trip count is always synth's own derived value, never the raw hint. A hint
//! below the derived count, or on a loop whose induction synth cannot verify
//! (data-dependent bound, non-canonical shape), is REJECTED with a machine
//! reason and never trusted into a bound.

use std::collections::BTreeMap;

use synth_core::wcet::{
    WcetFunctionHints, WcetHintReject, WcetHintRejection, WcetLoopBound, WcetLoopBoundSource,
};
use synth_synthesis::{ArmInstruction, ArmOp, Condition, Operand2, Reg};

/// Result of the loop analysis over one function's final instruction stream.
pub(crate) enum LoopAnalysis {
    /// No backward branches — the plain loop-free sum applies (multiplier 1).
    NoLoops {
        hint_rejections: Vec<WcetHintRejection>,
    },
    /// EVERY loop region proved a trip count: per-instruction execution-count
    /// multipliers (product of enclosing region factors, u128 to survive
    /// nesting) plus the per-loop bound records for the sidecar.
    Proven {
        multipliers: Vec<u128>,
        loops: Vec<WcetLoopBound>,
        hint_rejections: Vec<WcetHintRejection>,
    },
    /// At least one region could not be proven — the function keeps the loud
    /// `loop` decline; any offered hints that were rejected are recorded.
    Unproven {
        hint_rejections: Vec<WcetHintRejection>,
    },
}

// ---------------------------------------------------------------------------
// Symbolic domain
// ---------------------------------------------------------------------------

/// Comparison relation of a predicate over the counter, by signedness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Rel {
    Eq,
    Ne,
    LtS,
    LeS,
    GtS,
    GeS,
    LoU,
    LsU,
    HiU,
    HsU,
}

impl Rel {
    pub(crate) fn of(cond: Condition) -> Rel {
        match cond {
            Condition::EQ => Rel::Eq,
            Condition::NE => Rel::Ne,
            Condition::LT => Rel::LtS,
            Condition::LE => Rel::LeS,
            Condition::GT => Rel::GtS,
            Condition::GE => Rel::GeS,
            Condition::LO => Rel::LoU,
            Condition::LS => Rel::LsU,
            Condition::HI => Rel::HiU,
            Condition::HS => Rel::HsU,
        }
    }

    /// Logical negation over the same operands.
    pub(crate) fn negate(self) -> Rel {
        match self {
            Rel::Eq => Rel::Ne,
            Rel::Ne => Rel::Eq,
            Rel::LtS => Rel::GeS,
            Rel::GeS => Rel::LtS,
            Rel::LeS => Rel::GtS,
            Rel::GtS => Rel::LeS,
            Rel::LoU => Rel::HsU,
            Rel::HsU => Rel::LoU,
            Rel::LsU => Rel::HiU,
            Rel::HiU => Rel::LsU,
        }
    }
}

/// A boolean predicate over the counter slot's REGION-ENTRY value `v`:
/// `(v + add) REL rhs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Pred {
    /// SP-relative byte offset of the counter slot this predicate reads.
    pub(crate) off: i64,
    /// Constant added to the entry value before the comparison.
    pub(crate) add: i64,
    pub(crate) rel: Rel,
    pub(crate) rhs: i32,
    /// (#778 phase 5) The DATA-DEPENDENT masked bound: when the compare RHS is a
    /// masked value `x & K` (`K = masked_ceiling ≥ 0`), the real per-iteration
    /// bound lies in `[0, K]` for ANY runtime input (`x & K ∈ [0,K]`). `rhs` is
    /// then the ceiling `K` (the entry-independent worst case). The trip count is
    /// derived as the MAX over both endpoints of the bound domain (`rhs = K` and
    /// `rhs = 0`) — a single endpoint is unsound for count-DOWN shapes — and the
    /// result is always HINT-GATED (opt-in, mirroring the equality-exit gate).
    /// `None` for a normal const bound (unchanged phase-2 behavior).
    pub(crate) masked_ceiling: Option<i32>,
}

impl Pred {
    pub(crate) fn negate(self) -> Pred {
        Pred {
            rel: self.rel.negate(),
            ..self
        }
    }
}

/// Symbolic register/slot value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sym {
    /// Unknown.
    Top,
    /// A compile-time constant (i32 bit pattern).
    Const(i32),
    /// `(value of [sp,#off] at region entry) + add`.
    Slot { off: i64, add: i64 },
    /// A 0/1 boolean holding `pred`.
    Bool(Pred),
    /// (#778 phase 5) A masked value `x & K` (`mask = K ≥ 0`), for ANY `x`. The
    /// value is entry-independently bounded to `[0, K]` — the base identity is
    /// irrelevant (`x & K ≤ K` regardless of what `x` holds), unlike the
    /// recursion module's masked chain which needs the base identity for the
    /// decrement. Used ONLY as a data-dependent loop-bound ceiling (the compare
    /// RHS); the trip count it yields is always hint-gated.
    Masked { mask: i32 },
}

/// Walk state: symbolic registers, slot writes since walk start, tainted slots
/// (unreliable after a sub-word/unaligned store), and the last compare.
#[derive(Clone)]
struct WalkState {
    regs: [Sym; 16],
    /// Word-aligned SP-relative offsets written during THIS walk.
    written: BTreeMap<i64, Sym>,
    /// Offsets whose content is unreliable (sub-word overlap). A later full
    /// word store un-taints (it fully replaces the slot).
    tainted: std::collections::BTreeSet<i64>,
    /// Operands of the last flag-setting compare, when precisely known.
    flags: Option<(Sym, Sym)>,
}

impl WalkState {
    fn fresh() -> Self {
        WalkState {
            regs: [Sym::Top; 16],
            written: BTreeMap::new(),
            tainted: std::collections::BTreeSet::new(),
            flags: None,
        }
    }

    fn reg(&self, r: Reg) -> Sym {
        self.regs[r as usize]
    }

    fn set_reg(&mut self, r: Reg, v: Sym) {
        self.regs[r as usize] = v;
    }

    fn kill_all_regs(&mut self) {
        self.regs = [Sym::Top; 16];
    }

    fn op2(&self, op2: &Operand2) -> Sym {
        match op2 {
            Operand2::Imm(c) => Sym::Const(*c),
            Operand2::Reg(r) => self.reg(*r),
            Operand2::RegShift { .. } => Sym::Top,
        }
    }

    /// Read a word slot `[sp,#off]`: the value written during this walk, else
    /// the symbolic entry value `Slot{off,0}`.
    ///
    /// (#946) A NEGATIVE offset is never tracked. Everything at or above SP is
    /// the function's own live frame; everything below is scratch that any
    /// interrupt, or any multi-instruction encoder expansion that transiently
    /// pushes, may overwrite. Refusing to mint a `Slot` identity below SP is
    /// what lets `may_move_sp` answer `false` for the priced expansions that
    /// wrap a fixed-register core in `PUSH`/`POP` (`I64Popcnt`, `I64Rotl`,
    /// `I64Rotr`): their transient writes land strictly BELOW the incoming SP,
    /// so they provably cannot alias any slot this walk tracks. Conservative in
    /// one direction only — `Top` can cost a bound, never invent one.
    fn read_slot(&self, off: i64) -> Sym {
        if off < 0 || off % 4 != 0 || self.tainted.contains(&off) {
            return Sym::Top;
        }
        self.written
            .get(&off)
            .copied()
            .unwrap_or(Sym::Slot { off, add: 0 })
    }

    fn write_slot_word(&mut self, off: i64, v: Sym) {
        if off < 0 {
            // Below SP — see `read_slot`. Record nothing; taint so a later
            // re-base cannot resurrect a value written into scratch space.
            self.taint_range(off, 4);
        } else if off % 4 == 0 {
            // A full word store replaces the slot entirely — un-taint.
            self.tainted.remove(&off);
            self.written.insert(off, v);
        } else {
            // Unaligned word store touches two words: taint both.
            self.taint_range(off, 4);
        }
    }

    /// Mark every word overlapping `[off, off+width)` unreliable.
    fn taint_range(&mut self, off: i64, width: i64) {
        let first = off & !3;
        let last = (off + width - 1) & !3;
        let mut w = first;
        while w <= last {
            self.written.remove(&w);
            self.tainted.insert(w);
            w += 4;
        }
    }
}

/// Evaluate the predicate a condition computes over the last compare.
fn eval_pred(cond: Condition, flags: &Option<(Sym, Sym)>) -> Option<Pred> {
    let (a, b) = flags.as_ref()?;
    match (a, b) {
        (Sym::Slot { off, add }, Sym::Const(c)) => Some(Pred {
            off: *off,
            add: *add,
            rel: Rel::of(cond),
            rhs: *c,
            masked_ceiling: None,
        }),
        // (#778 phase 5) `cmp <counter slot>, <masked value>` — the counter is
        // compared against a DATA-DEPENDENT masked bound `x & K ∈ [0, K]`. The
        // ceiling `K` is the entry-independent worst case (`rhs = K`); the trip
        // this yields is derived at BOTH endpoints of `[0, K]` and hint-gated.
        (Sym::Slot { off, add }, Sym::Masked { mask }) => Some(Pred {
            off: *off,
            add: *add,
            rel: Rel::of(cond),
            rhs: *mask,
            masked_ceiling: Some(*mask),
        }),
        // `cmp <bool>, #0` — the eqz / br_if lowering shape. The bool carries the
        // ORIGINAL predicate (including any masked_ceiling), so a masked bound
        // survives the SetCond→cmp#0 indirection.
        (Sym::Bool(p), Sym::Const(0)) => match cond {
            Condition::EQ => Some(p.negate()),
            Condition::NE => Some(*p),
            _ => None,
        },
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Regions
// ---------------------------------------------------------------------------

/// The exit shape a region's trip count is derived from.
#[derive(Debug, Clone, Copy)]
enum ExitShape {
    /// Head-test: unconditional backward closer; `pred` (on some forward exit
    /// branch) is TRUE ⇒ control leaves the region. Factor = K + 1.
    HeadTest(Pred),
    /// Bottom-test: conditional backward closer; `pred` TRUE ⇒ another
    /// iteration. Factor = K.
    BottomTest(Pred),
}

struct Region {
    /// Instruction index of the loop head (backward-branch target).
    head: usize,
    /// Instruction index of the closing backward branch.
    closer: usize,
    /// `Some(cond)` when the closer is a conditional (bottom-test) branch.
    closer_cond: Option<Condition>,
    /// Immediate children (indices into the region vec), ascending head.
    children: Vec<usize>,
    /// Whether some other region directly contains this one.
    has_parent: bool,
    // --- proof results ---
    /// Counter slot offset, step, and exit shape (from the structure walk).
    proof: Option<(i64, i64, ExitShape)>,
    /// Constant initial counter value (resolved by the enclosing walk).
    init: Option<i32>,
    /// Proven trip count (body executions) + whether it is hint-gated.
    trip: Option<(u64, bool)>,
    /// (#778 phase 5) True when the exit bound is a DATA-DEPENDENT masked ceiling
    /// (`x & K`) rather than a literal const — the accepted bound then carries
    /// the `MaskCeiling` source so the sidecar states the extra assumption.
    masked_bound: bool,
    /// Per-iteration execution-count factor for instructions in this region.
    factor: u128,
}

/// Analyze the loop structure of `instrs`. `hints` is the (already
/// name-matched) UNTRUSTED per-function hint entry, if any.
pub(crate) fn analyze_loops(
    instrs: &[ArmInstruction],
    hints: Option<&WcetFunctionHints>,
) -> LoopAnalysis {
    // Byte positions from the REAL encoder — the SAME source of truth
    // `resolve_label_branches` computed the `BOffset`/`BCondOffset` halfword
    // displacements against. (The `estimate_arm_byte_size` estimator is NOT
    // exact for every op — e.g. a high-register `SetCond` widens its IT-block
    // MOVs to 10 bytes where the estimate is 6 — and a drifted layout would
    // reconstruct branch targets off-by-N, so the estimator must not be used
    // here.) Any op the encoder refuses → conservatively unproven.
    let n = instrs.len();
    let encoder = crate::arm_encoder::ArmEncoder::new_thumb2();
    let mut sizes: Vec<i64> = Vec::with_capacity(n);
    for instr in instrs {
        match encoder.encode(&instr.op) {
            Ok(bytes) => sizes.push(bytes.len() as i64),
            Err(_) => return unproven(hints, &[]),
        }
    }
    let mut positions = Vec::with_capacity(n);
    let mut pos: i64 = 0;
    for &sz in &sizes {
        positions.push(pos);
        pos += sz;
    }
    // Byte offset → FIRST instruction index at that offset (labels are 0-size).
    let mut idx_at: BTreeMap<i64, usize> = BTreeMap::new();
    for (i, &p) in positions.iter().enumerate() {
        idx_at.entry(p).or_insert(i);
    }
    let target_byte = |i: usize, offset: i32| positions[i] + 4 + (offset as i64) * 2;

    // ---- collect regions from backward branches ----
    let mut regions: Vec<Region> = Vec::new();
    for (i, instr) in instrs.iter().enumerate() {
        let (offset, cond) = match &instr.op {
            ArmOp::BOffset { offset } => (*offset, None),
            ArmOp::BCondOffset { cond, offset } => (*offset, Some(*cond)),
            _ => continue,
        };
        let tgt = target_byte(i, offset);
        if tgt > positions[i] {
            continue; // forward — validated by the branch discipline below
        }
        let Some(&head) = idx_at.get(&tgt) else {
            return unproven(hints, &[]); // target not at an instruction start
        };
        if head > i {
            return unproven(hints, &[]);
        }
        regions.push(Region {
            head,
            closer: i,
            closer_cond: cond,
            children: Vec::new(),
            has_parent: false,
            proof: None,
            init: None,
            trip: None,
            masked_bound: false,
            factor: 1,
        });
    }
    if regions.is_empty() {
        // Loop-free: any hints offered for this function address nonexistent
        // loops — reject them loudly rather than silently ignoring them.
        return LoopAnalysis::NoLoops {
            hint_rejections: reject_extra_hints(hints, 0, &[]),
        };
    }

    // Loop order for hint indexing + the sidecar: ascending head byte offset.
    regions.sort_by_key(|r| (positions[r.head], r.closer));
    let head_offsets: Vec<i64> = regions.iter().map(|r| positions[r.head]).collect();

    // ---- structural sanity: distinct heads, proper nesting ----
    for w in regions.windows(2) {
        if w[0].head == w[1].head {
            return unproven(hints, &head_offsets);
        }
    }
    for a in 0..regions.len() {
        for b in 0..regions.len() {
            if a == b {
                continue;
            }
            let (ra, rb) = (&regions[a], &regions[b]);
            let disjoint = ra.closer < rb.head || rb.closer < ra.head;
            let a_in_b = rb.head < ra.head && ra.closer < rb.closer;
            let b_in_a = ra.head < rb.head && rb.closer < ra.closer;
            if !(disjoint || a_in_b || b_in_a) {
                return unproven(hints, &head_offsets);
            }
        }
    }
    // Parent/child links (immediate containment).
    for a in 0..regions.len() {
        let mut parent: Option<usize> = None;
        for b in 0..regions.len() {
            if b == a {
                continue;
            }
            if regions[b].head < regions[a].head && regions[a].closer < regions[b].closer {
                // b contains a; keep the tightest.
                if parent.is_none_or(|p| {
                    regions[b].closer - regions[b].head < regions[p].closer - regions[p].head
                }) {
                    parent = Some(b);
                }
            }
        }
        if let Some(p) = parent {
            regions[a].has_parent = true;
            regions[p].children.push(a);
        }
    }
    for r in &mut regions {
        r.children.sort_by_key(|&c| c); // regions vec is head-sorted already
    }

    // ---- global branch discipline ----
    // Every branch must be (a) a region closer, or (b) a forward conditional
    // branch inside a region targeting EXACTLY its innermost region's resume
    // point (the byte after the closer). Anything else → unproven.
    let innermost_of = |i: usize| -> Option<usize> {
        regions
            .iter()
            .enumerate()
            .filter(|(_, r)| r.head <= i && i <= r.closer)
            .min_by_key(|(_, r)| r.closer - r.head)
            .map(|(k, _)| k)
    };
    for (i, instr) in instrs.iter().enumerate() {
        let (offset, is_cond) = match &instr.op {
            ArmOp::BOffset { offset } => (*offset, false),
            ArmOp::BCondOffset { offset, .. } => (*offset, true),
            _ => continue,
        };
        if regions.iter().any(|r| r.closer == i) {
            continue; // a closer — backward to its own head by construction
        }
        let tgt = target_byte(i, offset);
        if tgt <= positions[i] {
            return unproven(hints, &head_offsets); // backward non-closer (unreachable)
        }
        if !is_cond {
            return unproven(hints, &head_offsets); // forward unconditional (if/else) — non-canonical
        }
        let Some(rid) = innermost_of(i) else {
            return unproven(hints, &head_offsets); // conditional CF outside any loop
        };
        let resume = positions[regions[rid].closer] + sizes[regions[rid].closer];
        if tgt != resume {
            return unproven(hints, &head_offsets); // mid-region or multi-level exit
        }
    }

    // ---- per-region hard checks: nothing may move SP inside a region ----
    for r in &regions {
        for instr in &instrs[r.head..=r.closer] {
            match &instr.op {
                ArmOp::Push { .. } | ArmOp::Pop { .. } | ArmOp::Bx { .. } => {
                    return unproven(hints, &head_offsets);
                }
                op => {
                    if may_move_sp(op) {
                        return unproven(hints, &head_offsets);
                    }
                    // A dynamic or non-word-offset SP store inside a region is
                    // handled by the walk (it taints), but a dynamic SP STORE
                    // could alias ANY slot — refuse outright.
                    if let ArmOp::Str { addr, .. }
                    | ArmOp::Strb { addr, .. }
                    | ArmOp::Strh { addr, .. } = op
                        && addr.base == Reg::SP
                        && addr.offset_reg.is_some()
                    {
                        return unproven(hints, &head_offsets);
                    }
                }
            }
        }
    }

    // ---- structure walks, innermost first ----
    let mut order: Vec<usize> = (0..regions.len()).collect();
    order.sort_by_key(|&k| regions[k].closer - regions[k].head);
    for k in order {
        if !prove_region_structure(&mut regions, k, instrs) {
            return unproven(hints, &head_offsets);
        }
    }

    // ---- function-level walk: resolve top-level regions' inits ----
    if !resolve_toplevel_inits(&mut regions, instrs) {
        return unproven(hints, &head_offsets);
    }

    // ---- trip counts ----
    for r in &mut regions {
        let (Some((_, step, shape)), Some(init)) = (r.proof, r.init) else {
            r.trip = None;
            continue;
        };
        r.masked_bound = match shape {
            ExitShape::HeadTest(p) | ExitShape::BottomTest(p) => p.masked_ceiling.is_some(),
        };
        r.trip = match shape {
            ExitShape::HeadTest(p) => masked_exit_index(init, step, &p),
            ExitShape::BottomTest(p) => {
                // Body n (n ≥ 1) enters with v = init + (n−1)·step and repeats
                // while `pred` holds. K = 1 + (first m ≥ 0 where ¬pred fires).
                masked_exit_index(init, step, &p.negate())
                    .and_then(|(m, h)| m.checked_add(1).map(|k| (k, h)))
            }
        };
    }

    // ---- hints: verify / reject (the scry seam) ----
    let mut rejections: Vec<WcetHintRejection> = Vec::new();
    let empty = Vec::new();
    let hint_list: &Vec<Option<u64>> = hints.map_or(&empty, |h| &h.loop_bounds);
    let mut loops_out: Vec<WcetLoopBound> = Vec::new();
    let mut all_proven = true;
    for (idx, r) in regions.iter_mut().enumerate() {
        let hint = hint_list.get(idx).copied().flatten();
        let head_off = positions[r.head] as u64;
        let (accepted, source): (Option<u64>, WcetLoopBoundSource) = match (r.trip, hint) {
            // Fully static proof; no hint offered.
            (Some((k, false)), None) => (Some(k), WcetLoopBoundSource::Static),
            // Static proof + hint: the hint is cross-checked. A hint BELOW the
            // derived trip is a wrong oracle claim — reject it loudly (the
            // static bound stands on synth's own proof).
            (Some((k, false)), Some(h)) => {
                if h < k {
                    rejections.push(rejection(
                        idx,
                        Some(head_off),
                        h,
                        WcetHintReject::HintBelowDerivedTrip,
                    ));
                }
                (Some(k), WcetLoopBoundSource::Static)
            }
            // Hint-gated shape (equality-exit OR data-dependent masked ceiling,
            // #778 phase 5): unhinted → keep the `loop` decline. A bound resting
            // on either assumption is opt-in.
            (Some((_, true)), None) => (None, WcetLoopBoundSource::Static),
            // Hint-gated shape WITH a hint: consume ONLY if derived ≤ hint. The
            // accepted source distinguishes a masked ceiling from an equality
            // exit so the sidecar states which assumption the bound rests on. The
            // emitted trip is always synth's DERIVED value, never the raw hint.
            (Some((k, true)), Some(h)) => {
                if k <= h {
                    let source = if r.masked_bound {
                        WcetLoopBoundSource::MaskCeiling
                    } else {
                        WcetLoopBoundSource::HintVerified
                    };
                    (Some(k), source)
                } else {
                    rejections.push(rejection(
                        idx,
                        Some(head_off),
                        h,
                        WcetHintReject::HintBelowDerivedTrip,
                    ));
                    (None, WcetLoopBoundSource::Static)
                }
            }
            // Unproven induction: any hint is unverifiable — never trusted.
            (None, Some(h)) => {
                rejections.push(rejection(
                    idx,
                    Some(head_off),
                    h,
                    WcetHintReject::HintUnverifiableInduction,
                ));
                (None, WcetLoopBoundSource::Static)
            }
            (None, None) => (None, WcetLoopBoundSource::Static),
        };
        match accepted {
            Some(k) => {
                r.factor = match r.closer_cond {
                    // Head-test: the head check runs K+1 times.
                    None => k as u128 + 1,
                    // Bottom-test: every region instruction runs exactly K times.
                    Some(_) => (k as u128).max(1),
                };
                loops_out.push(WcetLoopBound {
                    head_offset: head_off,
                    trip_count: k,
                    region_instr_count: r.closer - r.head + 1,
                    source,
                    hint: match source {
                        WcetLoopBoundSource::HintVerified | WcetLoopBoundSource::MaskCeiling => {
                            hint
                        }
                        WcetLoopBoundSource::Static => None,
                    },
                });
            }
            None => all_proven = false,
        }
    }
    rejections.extend(reject_extra_hints(hints, regions.len(), &head_offsets));

    if !all_proven {
        return LoopAnalysis::Unproven {
            hint_rejections: rejections,
        };
    }

    // ---- per-instruction multipliers ----
    let mut multipliers = vec![1u128; n];
    for r in &regions {
        for m in multipliers.iter_mut().take(r.closer + 1).skip(r.head) {
            *m = m.saturating_mul(r.factor);
        }
    }
    LoopAnalysis::Proven {
        multipliers,
        loops: loops_out,
        hint_rejections: rejections,
    }
}

fn rejection(
    loop_index: usize,
    head_offset: Option<u64>,
    hint: u64,
    reason: WcetHintReject,
) -> WcetHintRejection {
    let note = reason.note().to_string();
    WcetHintRejection {
        loop_index,
        head_offset,
        hint,
        reason,
        note,
    }
}

/// Reject hint entries beyond the function's real loop count.
fn reject_extra_hints(
    hints: Option<&WcetFunctionHints>,
    loop_count: usize,
    _head_offsets: &[i64],
) -> Vec<WcetHintRejection> {
    let Some(h) = hints else {
        return Vec::new();
    };
    h.loop_bounds
        .iter()
        .enumerate()
        .skip(loop_count)
        .filter_map(|(i, b)| b.map(|v| rejection(i, None, v, WcetHintReject::HintUnknownLoop)))
        .collect()
}

/// Unproven WITHOUT any structure info: every offered hint is unverifiable.
fn unproven(hints: Option<&WcetFunctionHints>, head_offsets: &[i64]) -> LoopAnalysis {
    let rejections = hints
        .map(|h| {
            h.loop_bounds
                .iter()
                .enumerate()
                .filter_map(|(i, b)| {
                    b.map(|v| {
                        rejection(
                            i,
                            head_offsets.get(i).map(|&o| o as u64),
                            v,
                            WcetHintReject::HintUnverifiableInduction,
                        )
                    })
                })
                .collect()
        })
        .unwrap_or_default();
    LoopAnalysis::Unproven {
        hint_rejections: rejections,
    }
}

// ---------------------------------------------------------------------------
// Structure walk
// ---------------------------------------------------------------------------

/// Prove region `k`'s induction structure: counter slot, const step, exit
/// predicate. Children must already be proven (innermost-first order); their
/// inits are resolved here (a child's init store lives in THIS region's body).
fn prove_region_structure(regions: &mut [Region], k: usize, instrs: &[ArmInstruction]) -> bool {
    let (head, closer) = (regions[k].head, regions[k].closer);
    let mut st = WalkState::fresh();
    // (off, sym, order) of every word SP store on the region's own body.
    let mut store_events: Vec<(i64, Sym)> = Vec::new();
    // Exit predicates from forward conditional exits (branch TAKEN ⇒ leave).
    let mut exits: Vec<Option<Pred>> = Vec::new();

    let mut i = head;
    while i <= closer {
        // Child region: resolve its init from the current state, then skip it.
        if let Some(&c) = regions[k].children.iter().find(|&&c| regions[c].head == i) {
            let c_off = match regions[c].proof {
                Some((off, _, _)) => off,
                None => return false, // child unproven → parent unprovable
            };
            match st.read_slot(c_off) {
                Sym::Const(init) => {
                    // The same const init is stored on the straight-line path
                    // before the child head on EVERY parent iteration.
                    regions[c].init = Some(init);
                }
                _ => return false,
            }
            // Kill everything the child may change: registers (its body uses
            // scratch freely), flags, and every slot it stores to.
            st.kill_all_regs();
            st.flags = None;
            for instr in &instrs[regions[c].head..=regions[c].closer] {
                match &instr.op {
                    ArmOp::Str { addr, .. } if addr.base == Reg::SP => {
                        st.taint_range(addr.offset as i64, 4);
                    }
                    ArmOp::Strb { addr, .. } if addr.base == Reg::SP => {
                        st.taint_range(addr.offset as i64, 1);
                    }
                    ArmOp::Strh { addr, .. } if addr.base == Reg::SP => {
                        st.taint_range(addr.offset as i64, 2);
                    }
                    _ => {}
                }
            }
            i = regions[c].closer + 1;
            continue;
        }

        let instr = &instrs[i];
        match &instr.op {
            ArmOp::BOffset { .. } if i == closer => break, // head-test closer
            ArmOp::BCondOffset { cond, .. } if i == closer => {
                // Bottom-test closer: TAKEN ⇒ another iteration.
                let Some(p) = eval_pred(*cond, &st.flags) else {
                    return false;
                };
                let Some((off, step, _)) = counter_candidate(&st, &store_events, &[Some(p)]) else {
                    return false;
                };
                if p.off != off {
                    return false;
                }
                regions[k].proof = Some((off, step, ExitShape::BottomTest(p)));
                return true;
            }
            ArmOp::BCondOffset { cond, .. } => {
                // Forward exit (global discipline verified the target). TAKEN ⇒
                // leave the region; fall through otherwise. Unknown predicates
                // are early exits — sound to ignore.
                exits.push(eval_pred(*cond, &st.flags));
            }
            ArmOp::BOffset { .. } => return false, // forward BOffset inside region
            op => sym_step(op, &mut st, &mut store_events),
        }
        i += 1;
    }

    // Head-test: pick the counter/exit pair.
    let Some((off, step, pred)) = counter_candidate(&st, &store_events, &exits) else {
        return false;
    };
    regions[k].proof = Some((off, step, ExitShape::HeadTest(pred)));
    true
}

/// Find the counter slot: a word slot written EXACTLY once on the body with
/// `entry + step` (step ≠ 0), still holding that value at the end of the walk
/// (no child kill, no taint), that some usable exit predicate reads.
fn counter_candidate(
    st: &WalkState,
    store_events: &[(i64, Sym)],
    exits: &[Option<Pred>],
) -> Option<(i64, i64, Pred)> {
    for p in exits.iter().flatten() {
        let off = p.off;
        if st.tainted.contains(&off) {
            continue;
        }
        let events: Vec<&Sym> = store_events
            .iter()
            .filter(|(o, _)| *o == off)
            .map(|(_, s)| s)
            .collect();
        if events.len() != 1 {
            continue;
        }
        let Sym::Slot { off: so, add: step } = *events[0] else {
            continue;
        };
        if so != off || step == 0 {
            continue;
        }
        // The final state must still show the increment (nothing killed it).
        if st.written.get(&off) != Some(&Sym::Slot { off, add: step }) {
            continue;
        }
        return Some((off, step, *p));
    }
    None
}

/// One symbolic step for a non-control op. Precisely models the ops the
/// canonical counted-loop chain is built from; everything else conservatively
/// kills exactly what it can define (or all registers for multi-instruction
/// encoder expansions with scratch clobbers).
fn sym_step(op: &ArmOp, st: &mut WalkState, store_events: &mut Vec<(i64, Sym)>) {
    use ArmOp::*;
    match op {
        Mov { rd, op2 } => {
            let v = st.op2(op2);
            st.set_reg(*rd, v);
            st.flags = None; // 16-bit MOVS immediate sets flags
        }
        Movw { rd, imm16 } => {
            st.set_reg(*rd, Sym::Const(*imm16 as i32));
            st.flags = None;
        }
        Add { rd, rn, op2 } | Adds { rd, rn, op2 } => {
            let v = sym_add(st.reg(*rn), st.op2(op2), 1);
            st.set_reg(*rd, v);
            st.flags = None; // ADDS sets flags; we don't model add-flags
        }
        Sub { rd, rn, op2 } | Subs { rd, rn, op2 } => {
            let v = sym_add(st.reg(*rn), st.op2(op2), -1);
            st.set_reg(*rd, v);
            st.flags = None;
        }
        Ldr { rd, addr } => {
            let v = if addr.base == Reg::SP && addr.offset_reg.is_none() {
                st.read_slot(addr.offset as i64)
            } else {
                Sym::Top
            };
            st.set_reg(*rd, v);
            // Loads never set flags.
        }
        Ldrb { rd, addr } | Ldrh { rd, addr } | Ldrsb { rd, addr } | Ldrsh { rd, addr } => {
            let _ = addr;
            st.set_reg(*rd, Sym::Top);
        }
        LdrSym { rd, .. } => st.set_reg(*rd, Sym::Top),
        Str { rd, addr } => {
            if addr.base == Reg::SP {
                if addr.offset_reg.is_none() {
                    let off = addr.offset as i64;
                    let v = st.reg(*rd);
                    st.write_slot_word(off, v);
                    if off % 4 == 0 {
                        store_events.push((off, v));
                    }
                } else {
                    // Dynamic SP store (pre-declined inside regions; harden
                    // anyway): could alias anything.
                    let offs: Vec<i64> = st.written.keys().copied().collect();
                    for o in offs {
                        st.taint_range(o, 4);
                    }
                }
            }
            // Non-SP stores address the linear-memory/global image — layout-
            // disjoint from the SP frame (see module doc, soundness point 2).
        }
        Strb { rd: _, addr } => {
            if addr.base == Reg::SP && addr.offset_reg.is_none() {
                st.taint_range(addr.offset as i64, 1);
            }
        }
        Strh { rd: _, addr } => {
            if addr.base == Reg::SP && addr.offset_reg.is_none() {
                st.taint_range(addr.offset as i64, 2);
            }
        }
        Cmp { rn, op2 } => {
            st.flags = Some((st.reg(*rn), st.op2(op2)));
        }
        Cmn { .. } => st.flags = None,
        SetCond { rd, cond } => {
            // IT + MOV + MOV: writes rd, PRESERVES the compare's flags.
            let v = eval_pred(*cond, &st.flags).map_or(Sym::Top, Sym::Bool);
            st.set_reg(*rd, v);
        }
        SelectMove { rd, .. } => {
            st.set_reg(*rd, Sym::Top); // conditional write — value unknown
        }
        Label { .. } | Nop => {}
        Udf { .. } => {
            // Execution faults and never continues — over-approximating as a
            // state kill is sound.
            st.kill_all_regs();
            st.flags = None;
        }
        // (#778 phase 5) `And rd, _, #K` with a NON-NEGATIVE const mask yields a
        // value in `[0, K]` for ANY input (`x & K ≤ K`, and `≥ 0` because K's
        // sign bit is clear). A masked value with K's sign bit SET (`K < 0`,
        // e.g. 0xFFFFFFFF) can be negative — the ceiling reasoning collapses —
        // so only a non-negative mask is tracked; everything else kills rd.
        And { rd, op2, .. } => {
            let v = match st.op2(op2) {
                Sym::Const(mask) if mask >= 0 => Sym::Masked { mask },
                _ => Sym::Top,
            };
            st.set_reg(*rd, v);
            st.flags = None;
        }
        // Single-register-destination ALU ops: kill exactly rd.
        Orr { rd, .. }
        | Eor { rd, .. }
        | Rsb { rd, .. }
        | Mvn { rd, .. }
        | Adc { rd, .. }
        | Sbc { rd, .. }
        | Movt { rd, .. }
        | MovwSym { rd, .. }
        | MovtSym { rd, .. }
        | Clz { rd, .. }
        | Rbit { rd, .. }
        | Sxtb { rd, .. }
        | Sxth { rd, .. }
        | Uxtb { rd, .. }
        | Uxth { rd, .. }
        | Lsl { rd, .. }
        | Lsr { rd, .. }
        | Asr { rd, .. }
        | Ror { rd, .. }
        | LslReg { rd, .. }
        | LsrReg { rd, .. }
        | AsrReg { rd, .. }
        | RorReg { rd, .. }
        | Mul { rd, .. }
        | Mla { rd, .. }
        | Mls { rd, .. }
        | Sdiv { rd, .. }
        | Udiv { rd, .. } => {
            st.set_reg(*rd, Sym::Top);
            st.flags = None;
        }
        Umull { rdlo, rdhi, .. } => {
            st.set_reg(*rdlo, Sym::Top);
            st.set_reg(*rdhi, Sym::Top);
            st.flags = None;
        }
        // Everything else (multi-instruction encoder expansions clobber scratch
        // registers not named in the op; off-path pseudos never reach here):
        // kill all registers and flags. Slots survive — only Str*/Push write
        // the SP frame, and Push/Pop are pre-declined inside regions.
        _ => {
            st.kill_all_regs();
            st.flags = None;
        }
    }
}

/// Symbolic add/sub: `a + sign·b` when it stays exactly representable.
fn sym_add(a: Sym, b: Sym, sign: i64) -> Sym {
    match (a, b) {
        (Sym::Const(x), Sym::Const(y)) => {
            let r = x as i64 + sign * y as i64;
            i32::try_from(r).map_or(Sym::Top, Sym::Const)
        }
        (Sym::Slot { off, add }, Sym::Const(y)) => {
            match add.checked_add(sign * y as i64) {
                // Keep the affine offset well inside i64 so later trip math in
                // i128 cannot overflow.
                Some(na) if na.abs() <= 1 << 33 => Sym::Slot { off, add: na },
                _ => Sym::Top,
            }
        }
        (Sym::Const(x), Sym::Slot { off, add }) if sign == 1 => match add.checked_add(x as i64) {
            Some(na) if na.abs() <= 1 << 33 => Sym::Slot { off, add: na },
            _ => Sym::Top,
        },
        _ => Sym::Top,
    }
}

/// `may_move_sp` — may executing this op change SP, or is its SP effect
/// UNAUDITED? Either way the answer is `true` and the caller gives up.
///
/// Both call sites use this as a *give-up* predicate: loop regions refuse any SP
/// motion, and the function-level walk re-bases only on the immediate
/// push/pop/add/sub forms. So `true` is the SOUND direction — it can only cost a
/// bound, never invent one — and `false` is the direction that must be EARNED.
///
/// (#946) EXHAUSTIVE — no wildcard, no bare-identifier catch-all. It previously
/// named 47 of `ArmOp`'s 222 variants and let a `_ => false` absorb the other
/// 175, i.e. it *claimed* exhaustiveness over the priced instruction set while
/// silently answering "does not touch SP" for 79 % of the enum — the same shape
/// as the #615 A32 silent-NOP class. Three of those 175 (`I64Popcnt`,
/// `I64Rotl`, `I64Rotr`) are PRICED by `op_cost`, so they really do reach here,
/// and their encoder expansions really do emit `PUSH`/`POP` — the wildcard's
/// `false` was an UNJUSTIFIED answer, not merely an absent one. It happened to
/// be the right answer, but only because of a property nothing enforced; that
/// property is now a `WalkState` invariant (see the net-zero group below), so
/// the same `false` is now EARNED and the bounds are kept. The wildcard's own
/// doc comment excused `I64Popcnt` as "a whole-function `LoopedExpansion`
/// decline anyway", which was FALSE: `op_cost` prices it `Cycles`.
/// Structurally pinned by `tests/wcet_sp_no_wildcard_946.rs`.
///
/// REACHABILITY (why the `true` bucket below is behaviourally free): the sole
/// caller of [`analyze_loops`] is `wcet::function_wcet_intermediate`, which runs
/// `scan_for_decline` FIRST. That scan declines every op `op_cost` classifies
/// `Unmodeled` or `LoopedExpansion`, plus indirect/external calls and residual
/// label branches. So a stream that reaches this predicate contains ONLY
/// `OpCost::Cycles` ops and direct calls. The one variant NOT covered by that
/// argument is `ArmOp::Call`: `classify_call` returns `Direct` for it and
/// `continue`s, so it never reaches the `op_cost` check at all. It is
/// unreachable for a different reason — `encode_thumb` REFUSES it with a typed
/// `Err` (#615), so a compile carrying one has already failed.
#[allow(clippy::match_same_arms)] // grouped by REASON, not by answer
fn may_move_sp(op: &ArmOp) -> bool {
    use ArmOp::*;
    match op {
        // ---- Defines a named destination register: SP iff that register is SP ----
        Add { rd, .. }
        | Sub { rd, .. }
        | Adds { rd, .. }
        | Subs { rd, .. }
        | Adc { rd, .. }
        | Sbc { rd, .. }
        | Mov { rd, .. }
        | Mvn { rd, .. }
        | Movw { rd, .. }
        | Movt { rd, .. }
        | MovwSym { rd, .. }
        | MovtSym { rd, .. }
        | And { rd, .. }
        | Orr { rd, .. }
        | Eor { rd, .. }
        | Rsb { rd, .. }
        | Clz { rd, .. }
        | Rbit { rd, .. }
        | Sxtb { rd, .. }
        | Sxth { rd, .. }
        | Uxtb { rd, .. }
        | Uxth { rd, .. }
        | Lsl { rd, .. }
        | Lsr { rd, .. }
        | Asr { rd, .. }
        | Ror { rd, .. }
        | LslReg { rd, .. }
        | LsrReg { rd, .. }
        | AsrReg { rd, .. }
        | RorReg { rd, .. }
        | Mul { rd, .. }
        | Mla { rd, .. }
        | Mls { rd, .. }
        | Sdiv { rd, .. }
        | Udiv { rd, .. }
        | Popcnt { rd, .. }
        | Ldr { rd, .. }
        | Ldrb { rd, .. }
        | Ldrh { rd, .. }
        | Ldrsb { rd, .. }
        | Ldrsh { rd, .. }
        | LdrSym { rd, .. }
        | SetCond { rd, .. }
        | SelectMove { rd, .. } => *rd == Reg::SP,
        Umull { rdlo, rdhi, .. } => *rdlo == Reg::SP || *rdhi == Reg::SP,

        // ---- PRICED i64 expansions with a register destination (#946) ----
        // Reachable (`op_cost` → `Cycles(straightline_expansion(..))`), so these
        // get the SAME precise `rd == SP` test as their i32 counterparts above
        // rather than the wildcard's unconditional `false`. `I64Const`/`I64Ldr`
        // are the #936 ops: pricing them made them reachable here, where they
        // silently inherited the wildcard.
        I64SetCond { rd, .. } | I64SetCondZ { rd, .. } | I64Clz { rd, .. } | I64Ctz { rd, .. } => {
            *rd == Reg::SP
        }
        I64Const { rdlo, rdhi, .. }
        | I64Ldr { rdlo, rdhi, .. }
        | I64Extend8S { rdlo, rdhi, .. }
        | I64Extend16S { rdlo, rdhi, .. }
        | I64Extend32S { rdlo, rdhi, .. } => *rdlo == Reg::SP || *rdhi == Reg::SP,
        I64Mul { rd_lo, rd_hi, .. }
        | I64Shl { rd_lo, rd_hi, .. }
        | I64ShrU { rd_lo, rd_hi, .. }
        | I64ShrS { rd_lo, rd_hi, .. } => *rd_lo == Reg::SP || *rd_hi == Reg::SP,

        // ---- Moves SP outright ----
        Push { .. } | Pop { .. } => true,

        // ---- Expansions that transiently PUSH/POP, net-zero — EARNED `false` ----
        // Each of these expands (arm_encoder.rs) to a fixed-register core
        // wrapped in a `PUSH`/`POP` pair: `I64Popcnt`'s `0xB438`/`0xBC38`, and
        // `I64Rotl`/`I64Rotr`/`I64Div*`/`I64Rem*` via
        // `emit_i64_fixed_abi_entry`/`_exit` (`PUSH {R0-R3}` + `STR src,[SP,#-4]!`
        // marshalling, then a matching pop/`ADD SP,#4` for all four words).
        //
        // TWO facts make `false` sound, both checked rather than assumed:
        //  1. NET-ZERO: SP is restored exactly before the next op, so no
        //     tracked offset needs re-basing (verified by reading each arm:
        //     entry −16−12+12 = −16, exit +16).
        //  2. NO ALIASING: the transient writes land strictly BELOW the
        //     incoming SP, and `read_slot`/`write_slot_word`/`shift_slots`
        //     refuse to track ANY slot at a negative offset (#946), so nothing
        //     the walk believes can live in the region these ops scribble on.
        //
        // Fact 2 used to be an unenforced premise — the walk took `addr.offset`
        // raw and signed. It is now an invariant of `WalkState`, which is why
        // this arm answers `false` (keeping the bound) instead of declining.
        // Weaken those three guards and this answer stops being earned.
        I64Popcnt { .. }
        | I64Rotl { .. }
        | I64Rotr { .. }
        | I64DivS { .. }
        | I64DivU { .. }
        | I64RemS { .. }
        | I64RemU { .. } => false,

        // ---- Reachable and provably NOT an SP definition ----
        // Each of these is PRICED, so it really does reach here, and `true`
        // would be a live regression: the proven counter lives in an SP-relative
        // slot written by `Str`, the exit predicate is `Cmp`, and the region
        // closers/exits are `BOffset`/`BCondOffset` — declining any of them
        // would decline EVERY proven loop.
        //
        //  - `Cmp`/`Cmn` write flags only, no register.
        //  - `Str`/`Strb`/`Strh`/`I64Str`: `rd` (`rdlo`/`rdhi`) is the stored
        //    VALUE, a SOURCE. `MemAddr` has base/offset/offset_reg and NO
        //    writeback field, so the base register is never updated either.
        //  - `Label`/`Nop` have no register effect (`op_cost` prices both 0).
        //  - `Udf` traps.
        //  - `Bx`/`Bl`/`BOffset`/`BCondOffset` write PC (and `Bl` also LR); an
        //    AAPCS callee restores SP before returning. NOTE: `Bx` MUST stay
        //    `false` — `resolve_toplevel_inits` matches its `may_move_sp` guard
        //    arm BEFORE its `ArmOp::Bx` arm, so a `true` here would silently
        //    shadow the return handling (no unreachable-pattern warning).
        Cmp { .. }
        | Cmn { .. }
        | Str { .. }
        | Strb { .. }
        | Strh { .. }
        | I64Str { .. }
        | Label { .. }
        | Nop
        | Udf { .. }
        | Bx { .. }
        | Bl { .. }
        | BOffset { .. }
        | BCondOffset { .. } => false,

        // ---- Not reachable here — answered `true` (give up), not `false` ----
        // `op_cost` classifies every variant below `Unmodeled` (VFP scalar, MVE
        // vector, the i64 pseudo binops/compares/extends, and the off-path
        // pseudo-ops `encode_thumb` REFUSES with a typed `Err`) or, for the
        // indirect calls and residual label branches, `scan_for_decline`
        // declines them outright. `Call` is the one exception to that chain —
        // `classify_call` calls it `Direct` and skips the `op_cost` check — but
        // `encode_thumb` refuses it too, so it is equally unreachable. Per the
        // REACHABILITY note on this function, none can appear in a stream that
        // reaches here. They answer `true` rather than `false` deliberately:
        //
        //  1. SOUNDNESS: `true` is the give-up direction at both call sites, so
        //     an unaudited op can only cost a bound, never fabricate one.
        //  2. FUTURE-PROOFING: #936 priced `I64Const`/`I64Ldr`/`I64Str` and they
        //     instantly became reachable here, inheriting the wildcard's
        //     unaudited `false` with nobody revisiting this function. With
        //     `true` as the default, pricing an op produces a LOUD decline until
        //     its SP behaviour is consciously audited and moved to a group above.
        //  3. TRIPWIRE POTENCY: a re-added `_ => false` flips all 142 of these
        //     answers, so the #946 behavioural pins can actually fail. A bucket
        //     of `false`s would make the wildcard behaviourally identical and
        //     the tripwire vacuous.
        MemorySize { .. }
        | MemoryGrow { .. }
        | B { .. }
        | Bhs { .. }
        | Blo { .. }
        | Bcc { .. }
        | Blx { .. }
        | Select { .. }
        | LocalGet { .. }
        | LocalSet { .. }
        | LocalTee { .. }
        | GlobalGet { .. }
        | GlobalSet { .. }
        | BrTable { .. }
        | Call { .. }
        | CallIndirect { .. }
        | I64Add { .. }
        | I64Sub { .. }
        | I64And { .. }
        | I64Or { .. }
        | I64Xor { .. }
        | I64Eqz { .. }
        | I64Eq { .. }
        | I64Ne { .. }
        | I64LtS { .. }
        | I64LtU { .. }
        | I64LeS { .. }
        | I64LeU { .. }
        | I64GtS { .. }
        | I64GtU { .. }
        | I64GeS { .. }
        | I64GeU { .. }
        | I64ExtendI32S { .. }
        | I64ExtendI32U { .. }
        | I32WrapI64 { .. }
        | F32Add { .. }
        | F32Sub { .. }
        | F32Mul { .. }
        | F32Div { .. }
        | F32Abs { .. }
        | F32Neg { .. }
        | F32Sqrt { .. }
        | F32Ceil { .. }
        | F32Floor { .. }
        | F32Trunc { .. }
        | F32Nearest { .. }
        | F32Min { .. }
        | F32Max { .. }
        | F32Copysign { .. }
        | F32Eq { .. }
        | F32Ne { .. }
        | F32Lt { .. }
        | F32Le { .. }
        | F32Gt { .. }
        | F32Ge { .. }
        | F32Const { .. }
        | F32Load { .. }
        | F32Store { .. }
        | F32ConvertI32S { .. }
        | F32ConvertI32U { .. }
        | F32ConvertI64S { .. }
        | F32ConvertI64U { .. }
        | F32ReinterpretI32 { .. }
        | I32ReinterpretF32 { .. }
        | I32TruncF32S { .. }
        | I32TruncF32U { .. }
        | F64Add { .. }
        | F64Sub { .. }
        | F64Mul { .. }
        | F64Div { .. }
        | F64Abs { .. }
        | F64Neg { .. }
        | F64Sqrt { .. }
        | F64Ceil { .. }
        | F64Floor { .. }
        | F64Trunc { .. }
        | F64Nearest { .. }
        | F64Min { .. }
        | F64Max { .. }
        | F64Copysign { .. }
        | F64Eq { .. }
        | F64Ne { .. }
        | F64Lt { .. }
        | F64Le { .. }
        | F64Gt { .. }
        | F64Ge { .. }
        | F64Const { .. }
        | F64Load { .. }
        | F64Store { .. }
        | F64ConvertI32S { .. }
        | F64ConvertI32U { .. }
        | F64ConvertI64S { .. }
        | F64ConvertI64U { .. }
        | F64PromoteF32 { .. }
        | F32DemoteF64 { .. }
        | F64ReinterpretI64 { .. }
        | I64ReinterpretF64 { .. }
        | I64TruncF64S { .. }
        | I64TruncF64U { .. }
        | I32TruncF64S { .. }
        | I32TruncF64U { .. }
        | MveLoad { .. }
        | MveStore { .. }
        | MveConst { .. }
        | MveAnd { .. }
        | MveOrr { .. }
        | MveEor { .. }
        | MveMvn { .. }
        | MveBic { .. }
        | MveAddI { .. }
        | MveSubI { .. }
        | MveMulI { .. }
        | MveNegI { .. }
        | MveCmpEqI { .. }
        | MveCmpNeI { .. }
        | MveCmpLtS { .. }
        | MveCmpLtU { .. }
        | MveCmpGtS { .. }
        | MveCmpGtU { .. }
        | MveCmpLeS { .. }
        | MveCmpLeU { .. }
        | MveCmpGeS { .. }
        | MveCmpGeU { .. }
        | MveDup { .. }
        | MveExtractLane { .. }
        | MveInsertLane { .. }
        | MveAddF32 { .. }
        | MveSubF32 { .. }
        | MveMulF32 { .. }
        | MveNegF32 { .. }
        | MveAbsF32 { .. }
        | MveCmpEqF32 { .. }
        | MveCmpNeF32 { .. }
        | MveCmpLtF32 { .. }
        | MveCmpLeF32 { .. }
        | MveCmpGtF32 { .. }
        | MveCmpGeF32 { .. }
        | MveDupF32 { .. }
        | MveExtractLaneF32 { .. }
        | MveReplaceLaneF32 { .. }
        | MveDivF32 { .. }
        | MveSqrtF32 { .. } => true,
    }
}

// ---------------------------------------------------------------------------
// Function-level walk (init resolution for top-level regions)
// ---------------------------------------------------------------------------

/// Walk the function linearly from index 0, tracking const stores into the SP
/// frame, to resolve each TOP-LEVEL region's counter init; regions are skipped
/// opaquely (their effects killed). SP motion outside regions (prologue
/// push/sub) re-bases the tracked offsets. Returns false when an init cannot
/// be proven const.
fn resolve_toplevel_inits(regions: &mut [Region], instrs: &[ArmInstruction]) -> bool {
    let mut st = WalkState::fresh();
    let mut events: Vec<(i64, Sym)> = Vec::new();
    let mut i = 0usize;
    while i < instrs.len() {
        // Top-level region head?
        if let Some(k) =
            (0..regions.len()).find(|&k| !regions[k].has_parent && regions[k].head == i)
        {
            let off = match regions[k].proof {
                Some((off, _, _)) => off,
                None => return false,
            };
            match st.read_slot(off) {
                Sym::Const(init) => regions[k].init = Some(init),
                _ => return false,
            }
            // Skip the region opaquely.
            st.kill_all_regs();
            st.flags = None;
            for instr in &instrs[regions[k].head..=regions[k].closer] {
                match &instr.op {
                    ArmOp::Str { addr, .. } if addr.base == Reg::SP => {
                        st.taint_range(addr.offset as i64, 4);
                    }
                    ArmOp::Strb { addr, .. } if addr.base == Reg::SP => {
                        st.taint_range(addr.offset as i64, 1);
                    }
                    ArmOp::Strh { addr, .. } if addr.base == Reg::SP => {
                        st.taint_range(addr.offset as i64, 2);
                    }
                    _ => {}
                }
            }
            i = regions[k].closer + 1;
            continue;
        }

        let instr = &instrs[i];
        match &instr.op {
            // SP motion outside regions: re-base tracked slot offsets. After
            // `sub sp,#k` an address SP_old+off is SP_new+(off+k).
            ArmOp::Push { regs } => shift_slots(&mut st, 4 * regs.len() as i64),
            ArmOp::Pop { regs } => shift_slots(&mut st, -4 * (regs.len() as i64)),
            ArmOp::Sub { rd, rn, op2 } | ArmOp::Subs { rd, rn, op2 }
                if *rd == Reg::SP && *rn == Reg::SP =>
            {
                match op2 {
                    Operand2::Imm(k) => shift_slots(&mut st, *k as i64),
                    _ => return false, // dynamic SP adjust — give up
                }
            }
            ArmOp::Add { rd, rn, op2 } | ArmOp::Adds { rd, rn, op2 }
                if *rd == Reg::SP && *rn == Reg::SP =>
            {
                match op2 {
                    Operand2::Imm(k) => shift_slots(&mut st, -(*k as i64)),
                    _ => return false,
                }
            }
            // NOTE: this guard arm is matched BEFORE the `ArmOp::Bx` arm below,
            // so `may_move_sp(Bx) == false` is load-bearing — a `true` there
            // would shadow the return handling with no compiler warning (#946).
            op if may_move_sp(op) => return false, // any other SP motion — give up
            ArmOp::Bx { .. } => {
                // A return: nothing after it can be reached by fallthrough, and
                // all remaining region heads (if any) would be unreachable —
                // their init can't be resolved.
                if (0..regions.len()).any(|k| !regions[k].has_parent && regions[k].head > i) {
                    return false;
                }
                break;
            }
            // Branches outside regions were rejected by the global discipline;
            // region closers/exits are inside regions (skipped above).
            op => sym_step(op, &mut st, &mut events),
        }
        i += 1;
    }
    true
}

/// Re-base every tracked slot offset by `delta` (SP moved down by `delta`).
fn shift_slots(st: &mut WalkState, delta: i64) {
    if delta == 0 {
        return;
    }
    st.written = st
        .written
        .iter()
        .map(|(&off, &v)| (off + delta, v))
        .collect();
    st.tainted = st.tainted.iter().map(|&off| off + delta).collect();
    // (#946) A re-base can push a tracked offset BELOW the new SP — an epilogue
    // `pop {r4-r7}` shifts by −16. Those words are scratch from here on, so
    // drop the remembered value and taint the slot rather than keep believing
    // it. This is what makes `read_slot`'s "nothing below SP is ever tracked"
    // invariant hold for the WHOLE walk, not just at the moment of the store —
    // and it is the invariant `may_move_sp` relies on to answer `false` for the
    // priced PUSH/POP-wrapping expansions. Conservative in one direction only.
    let below: Vec<i64> = st.written.keys().copied().filter(|&o| o < 0).collect();
    for off in below {
        st.written.remove(&off);
        st.tainted.insert(off);
    }
    // Symbolic Slot{off} identities in registers refer to pre-shift offsets —
    // drop them (registers holding loaded values stay valid as Const/Top, but a
    // Slot identity is offset-relative).
    for r in st.regs.iter_mut() {
        if matches!(r, Sym::Slot { .. } | Sym::Bool(_)) {
            *r = Sym::Top;
        }
    }
    st.flags = None;
}

// ---------------------------------------------------------------------------
// Trip-count arithmetic
// ---------------------------------------------------------------------------

/// Smallest `n ≥ 0` such that `(init + n·step + p.add) p.rel p.rhs` holds —
/// i.e. the head evaluation index at which the exit predicate first fires —
/// with STATIC no-overflow checks over the whole counter walk in the
/// predicate's signedness domain. Returns `(n, requires_hint)`; equality exits
/// set `requires_hint` (consumed only under a verified `--wcet-hints` entry).
/// (#778 phase 5) Trip count for an exit predicate that may carry a
/// DATA-DEPENDENT masked bound. For a normal const bound (`masked_ceiling ==
/// None`) this is exactly [`exit_index`]. For a masked bound `x & K ∈ [0, K]`
/// the real per-iteration bound is somewhere in `[0, K]` for ANY runtime input,
/// so the sound trip is the MAXIMUM over the whole bound domain:
///
/// - A single endpoint is UNSOUND. For a count-UP loop (`i < bound`) the worst
///   case is the LARGEST bound (`K`); for a count-DOWN loop (`i > bound`) the
///   worst case is the SMALLEST bound (`0`). Seeding only `rhs = K` would emit a
///   bound BELOW a real count-down execution — the fatal class.
/// - We evaluate `exit_index` at BOTH endpoints (`rhs = K` and `rhs = 0`),
///   require BOTH to terminate (else the loop is not guaranteed-terminating for
///   every masked value), and take the MAX trip. Because the trip is monotone in
///   the bound for a threshold relation, the max over the two endpoints bounds
///   the max over the whole `[0, K]` interval (and per-iteration-varying bounds,
///   each `m_j ≤ K`, are covered too: a count-up exits by `counter = K`, a
///   count-down's worst case is the `rhs = 0` endpoint).
/// - For an Eq/Ne exit, an interior bound value can be MISSED by a step that does
///   not divide the distance (the divisibility-divergence trap), so endpoint
///   reasoning holds only when EVERY value in `[0, K]` is reachable — i.e.
///   `|step| == 1`. A larger step with an Eq/Ne masked bound is declined.
///
/// The masked trip is ALWAYS hint-gated (the returned bool is forced true): a
/// bound resting on a data-dependent ceiling is opt-in, mirroring the
/// equality-exit gate. `None` propagates (unproven) whenever either endpoint
/// fails to terminate or wraps.
fn masked_exit_index(init: i32, step: i64, p: &Pred) -> Option<(u64, bool)> {
    let Some(ceiling) = p.masked_ceiling else {
        return exit_index(init, step, p);
    };
    debug_assert!(ceiling >= 0);
    // Eq/Ne masked bound: only |step| == 1 keeps every interior value reachable.
    if matches!(p.rel, Rel::Eq | Rel::Ne) && step.abs() != 1 {
        return None;
    }
    let at = |rhs: i32| -> Option<u64> {
        let pr = Pred {
            rhs,
            masked_ceiling: None,
            ..*p
        };
        exit_index(init, step, &pr).map(|(k, _)| k)
    };
    let (hi, lo) = (at(ceiling)?, at(0)?);
    // Force hint-gated: a data-dependent ceiling is only ever consumed under a
    // verified --wcet-hints entry.
    Some((hi.max(lo), true))
}

/// `None` = exit not statically guaranteed (or a possible wrap) → unproven.
pub(crate) fn exit_index(init: i32, step: i64, p: &Pred) -> Option<(u64, bool)> {
    let s = step;
    debug_assert!(s != 0);
    let signed = matches!(
        p.rel,
        Rel::LtS | Rel::LeS | Rel::GtS | Rel::GeS | Rel::Eq | Rel::Ne
    );
    // Counter values in the comparison domain.
    let (v0, lo, hi): (i128, i128, i128) = if signed {
        (init as i128, i32::MIN as i128, i32::MAX as i128)
    } else {
        (init as u32 as i128, 0, u32::MAX as i128)
    };
    let (rhs, add) = if signed {
        (p.rhs as i128, p.add as i128)
    } else {
        (p.rhs as u32 as i128, p.add as i128)
    };
    let s = s as i128;

    // Exit threshold as "counter value C where (C + add) rel rhs first holds
    // along the walk direction", normalized to v ≥ T (for s > 0) or v ≤ T
    // (for s < 0); equality handled separately.
    let k: i128 = match p.rel {
        Rel::Eq | Rel::Ne => {
            let target = rhs - add;
            if p.rel == Rel::Ne {
                // Exit when v ≠ target: fires at n=0 unless v0 == target, in
                // which case n=1 (one step moves off the target; no-wrap is
                // checked below).
                let n = if v0 == target { 1 } else { 0 };
                return finish(n, v0, s, add, lo, hi, false);
            }
            // Exit when v == target: reachable iff the walk lands exactly on it.
            let d = target - v0;
            if d % s != 0 || d / s < 0 {
                return None; // steps over or walks away — may never terminate
            }
            return finish(d / s, v0, s, add, lo, hi, true);
        }
        Rel::GeS | Rel::HsU => rhs - add,     // exit when v ≥ T
        Rel::GtS | Rel::HiU => rhs - add + 1, // exit when v > T-  ⇔ v ≥ T+1
        Rel::LeS | Rel::LsU => rhs - add,     // exit when v ≤ T
        Rel::LtS | Rel::LoU => rhs - add - 1, // exit when v < T  ⇔ v ≤ T-1
    };
    let upward_exit = matches!(p.rel, Rel::GeS | Rel::GtS | Rel::HsU | Rel::HiU);
    if upward_exit {
        if v0 >= k {
            return finish(0, v0, s, add, lo, hi, false);
        }
        if s <= 0 {
            return None; // walking away from the exit threshold
        }
        let n = ceil_div_pos(k - v0, s);
        finish(n, v0, s, add, lo, hi, false)
    } else {
        if v0 <= k {
            return finish(0, v0, s, add, lo, hi, false);
        }
        if s >= 0 {
            return None;
        }
        let n = ceil_div_pos(v0 - k, -s);
        finish(n, v0, s, add, lo, hi, false)
    }
}

/// `ceil(num / den)` for `num ≥ 0`, `den > 0` (i128 `div_ceil` is unstable).
fn ceil_div_pos(num: i128, den: i128) -> i128 {
    debug_assert!(num >= 0 && den > 0);
    (num + den - 1) / den
}

/// Final static checks for exit index `n`: every counter value touched on the
/// walk (`v0 .. v0+n·s`, monotone) and every compared value (`+add`) must stay
/// exactly representable in the comparison domain — otherwise the hardware
/// would wrap and the affine model would diverge from the machine.
fn finish(
    n: i128,
    v0: i128,
    s: i128,
    add: i128,
    lo: i128,
    hi: i128,
    requires_hint: bool,
) -> Option<(u64, bool)> {
    if n < 0 {
        return None;
    }
    let vn = v0.checked_add(n.checked_mul(s)?)?;
    for v in [v0, vn, v0 + add, vn + add] {
        if v < lo || v > hi {
            return None;
        }
    }
    Some((u64::try_from(n).ok()?, requires_hint))
}

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

    fn pred(rel: Rel, rhs: i32, add: i64) -> Pred {
        Pred {
            off: 0,
            add,
            rel,
            rhs,
            masked_ceiling: None,
        }
    }

    #[test]
    fn head_test_up_count() {
        // for v in 0..10 step 1, exit when v >= 10 → 10 full iterations.
        assert_eq!(exit_index(0, 1, &pred(Rel::GeS, 10, 0)), Some((10, false)));
        // init 3, step 2, exit when v >= 10 → v: 3,5,7,9,11 → n=4.
        assert_eq!(exit_index(3, 2, &pred(Rel::GeS, 10, 0)), Some((4, false)));
        // already at/above the bound → 0 iterations.
        assert_eq!(exit_index(10, 1, &pred(Rel::GeS, 10, 0)), Some((0, false)));
        // compared value is v+1 (bottom-test increment-then-compare shape).
        assert_eq!(exit_index(0, 1, &pred(Rel::GeS, 10, 1)), Some((9, false)));
    }

    #[test]
    fn down_count_and_unsigned() {
        // v from 10 down to 0, exit when v <= 0 → n = 10.
        assert_eq!(exit_index(10, -1, &pred(Rel::LeS, 0, 0)), Some((10, false)));
        // unsigned: exit when v >=u 8, from 0 step 1 → 8.
        assert_eq!(exit_index(0, 1, &pred(Rel::HsU, 8, 0)), Some((8, false)));
        // step walks AWAY from the exit → not guaranteed.
        assert_eq!(exit_index(0, -1, &pred(Rel::GeS, 10, 0)), None);
    }

    #[test]
    fn equality_exit_is_hint_gated() {
        // exact landing: 0,1,..,8 → n=8, requires_hint.
        assert_eq!(exit_index(0, 1, &pred(Rel::Eq, 8, 0)), Some((8, true)));
        // step 2 over an odd distance NEVER lands → None (may not terminate).
        assert_eq!(exit_index(0, 2, &pred(Rel::Eq, 9, 0)), None);
    }

    // -----------------------------------------------------------------------
    // #946 — `may_move_sp` behavioural pins.
    //
    // The STRUCTURAL half of the tripwire (no wildcard may regrow, every one of
    // the 222 `ArmOp` variants must be named) lives in
    // `tests/wcet_sp_no_wildcard_946.rs`. These pins are the BEHAVIOURAL half:
    // they fix the answers a re-added `_ => false` would change, and the
    // reachable answers a careless `_ => true` would change. Both directions
    // matter — `true` is the sound/give-up direction, but on a REACHABLE op it
    // is a live regression (declining `Str`/`Cmp`/`BOffset` would decline every
    // proven loop, since those are what a canonical counted loop is built from).
    // -----------------------------------------------------------------------

    use synth_synthesis::{MemAddr, QReg, VfpReg};

    /// Ops whose answer is `true` but which a `_ => false` wildcard would have
    /// answered `false`. NON-VACUITY: this list must be non-empty, otherwise the
    /// wildcard is behaviourally identical to the explicit arms and the tripwire
    /// cannot fail. (`Push`/`Pop` are excluded — they were already explicit.)
    fn true_but_absorbed_by_a_false_wildcard() -> Vec<ArmOp> {
        vec![
            // Pre-declined families — `true` is the decline-honest default so a
            // future pricing change (cf. #936) gets a loud decline, not a
            // silently inherited `false`.
            ArmOp::I64Add {
                rdlo: Reg::R0,
                rdhi: Reg::R1,
                rnlo: Reg::R2,
                rnhi: Reg::R3,
                rmlo: Reg::R4,
                rmhi: Reg::R5,
            },
            ArmOp::F64Add {
                dd: VfpReg::D0,
                dn: VfpReg::D1,
                dm: VfpReg::D2,
            },
            ArmOp::MveAddF32 {
                qd: QReg::Q0,
                qn: QReg::Q1,
                qm: QReg::Q2,
            },
            ArmOp::Select {
                rd: Reg::R0,
                rval1: Reg::R1,
                rval2: Reg::R2,
                rcond: Reg::R3,
            },
            ArmOp::B {
                label: "L".to_string(),
            },
        ]
    }

    #[test]
    fn may_move_sp_true_answers_are_not_reproducible_by_a_false_wildcard() {
        let ops = true_but_absorbed_by_a_false_wildcard();
        assert!(
            !ops.is_empty(),
            "non-vacuity: with an empty list a re-added `_ => false` would be \
             behaviourally identical and this tripwire could never fail"
        );
        for op in &ops {
            assert!(
                may_move_sp(op),
                "{op:?}: must answer `true`; a `_ => false` wildcard would say `false`"
            );
        }
    }

    #[test]
    fn may_move_sp_true_on_real_sp_definitions() {
        // The unconditional stack ops.
        assert!(may_move_sp(&ArmOp::Push {
            regs: vec![Reg::R4]
        }));
        assert!(may_move_sp(&ArmOp::Pop {
            regs: vec![Reg::R4]
        }));
        // A destination register that IS SP, across every destination shape.
        assert!(may_move_sp(&ArmOp::Add {
            rd: Reg::SP,
            rn: Reg::SP,
            op2: Operand2::Imm(8)
        }));
        assert!(may_move_sp(&ArmOp::Umull {
            rdlo: Reg::SP,
            rdhi: Reg::R1,
            rn: Reg::R2,
            rm: Reg::R3
        }));
        // #946: the i64 destination shapes the wildcard used to absorb.
        assert!(may_move_sp(&ArmOp::I64Const {
            rdlo: Reg::R0,
            rdhi: Reg::SP,
            value: 1
        }));
        assert!(may_move_sp(&ArmOp::I64Mul {
            rd_lo: Reg::SP,
            rd_hi: Reg::R1,
            rn_lo: Reg::R2,
            rn_hi: Reg::R3,
            rm_lo: Reg::R4,
            rm_hi: Reg::R5
        }));
        assert!(may_move_sp(&ArmOp::I64Clz {
            rd: Reg::SP,
            rnlo: Reg::R1,
            rnhi: Reg::R2
        }));
    }

    #[test]
    fn may_move_sp_false_on_the_reachable_counted_loop_vocabulary() {
        // These are exactly the ops a canonical counted loop is built from. A
        // `true` here would decline EVERY proven loop — the regression a
        // blanket "be conservative" sweep would have caused.
        let must_be_false = vec![
            // The counter's slot store (`rd` is the stored VALUE, a source; and
            // `MemAddr` has no writeback so the SP base is never updated).
            ArmOp::Str {
                rd: Reg::R0,
                addr: MemAddr::imm(Reg::SP, 4),
            },
            ArmOp::I64Str {
                rdlo: Reg::R0,
                rdhi: Reg::R1,
                addr: MemAddr::imm(Reg::SP, 8),
            },
            // The exit predicate.
            ArmOp::Cmp {
                rn: Reg::R0,
                op2: Operand2::Imm(10),
            },
            // The region closer and its exit branch.
            ArmOp::BOffset { offset: -6 },
            ArmOp::BCondOffset {
                cond: Condition::GE,
                offset: 4,
            },
            // `Bx` MUST be false: `resolve_toplevel_inits` matches the
            // `may_move_sp` guard arm BEFORE its `ArmOp::Bx` arm, so a `true`
            // would silently shadow the return handling.
            ArmOp::Bx { rm: Reg::LR },
            ArmOp::Bl {
                label: "func_1".to_string(),
            },
            ArmOp::Label {
                name: "L".to_string(),
            },
            ArmOp::Nop,
            ArmOp::Udf { imm: 0 },
            // A non-SP destination still answers false.
            ArmOp::Add {
                rd: Reg::R0,
                rn: Reg::R1,
                op2: Operand2::Imm(1),
            },
            ArmOp::I64Const {
                rdlo: Reg::R0,
                rdhi: Reg::R1,
                value: 1,
            },
            // The net-zero PUSH/POP group. `false` here is EARNED by the
            // `WalkState` non-negative-slot invariant (`read_slot`,
            // `write_slot_word`, `shift_slots`), not assumed — see the arm's
            // comment. Weaken those guards and this answer must go back to
            // `true`, costing the `rot`/`pc` bounds in `wcet_bound_gate.rs`.
            ArmOp::I64Popcnt {
                rd: Reg::R0,
                rnlo: Reg::R1,
                rnhi: Reg::R2,
            },
            ArmOp::I64Rotl {
                rdlo: Reg::R0,
                rdhi: Reg::R1,
                rnlo: Reg::R2,
                rnhi: Reg::R3,
                shift: Reg::R4,
            },
        ];
        for op in &must_be_false {
            assert!(
                !may_move_sp(op),
                "{op:?}: must answer `false` — it is PRICED (so it really reaches \
                 this predicate) and declining it would decline proven loops"
            );
        }
    }

    /// (#946) The invariant that EARNS `may_move_sp(I64Rotl) == false`: nothing
    /// below SP is ever tracked, at store time or after a re-base. Without it,
    /// the transient `PUSH {R0-R3}` inside those expansions could alias a slot
    /// the walk believes it knows.
    #[test]
    fn walk_state_never_tracks_a_slot_below_sp() {
        let mut st = WalkState::fresh();

        // A store below SP is not remembered, and reads there are opaque.
        st.write_slot_word(-4, Sym::Const(7));
        assert_eq!(st.read_slot(-4), Sym::Top, "a slot below SP must not track");
        assert!(!st.written.contains_key(&-4));
        // ...and no `Slot` identity is ever minted below SP, so it can never
        // become a counter candidate.
        assert_eq!(st.read_slot(-8), Sym::Top);

        // A normal frame slot tracks as before.
        st.write_slot_word(8, Sym::Const(3));
        assert_eq!(st.read_slot(8), Sym::Const(3));

        // A re-base that pushes it below SP (an epilogue `pop {r4-r7}`) drops
        // the remembered value rather than carrying it into scratch space.
        shift_slots(&mut st, -16);
        assert!(
            !st.written.contains_key(&-8),
            "a re-based slot that fell below SP must be dropped, not believed"
        );
        assert_eq!(st.read_slot(-8), Sym::Top);
    }

    #[test]
    fn overflow_wraps_decline() {
        // init MAX−1, step 2, exit when v ≥ MAX: the walk goes MAX−1 → MAX+1,
        // i.e. the hardware would wrap past the threshold → None.
        assert_eq!(
            exit_index(i32::MAX - 1, 2, &pred(Rel::GeS, i32::MAX, 0)),
            None
        );
        // Same shape one step earlier lands exactly on MAX → proven, 1 trip.
        assert_eq!(
            exit_index(i32::MAX - 2, 1, &pred(Rel::GeS, i32::MAX, 0)),
            Some((2, false))
        );
    }
}