cverif 0.0.6

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
//! Shared symbolic-execution context: path condition, branching through the
//! prover, deterministic path replay and the memory model used by both the C
//! and the machine-code executors.

use crate::bv::{Prover, Verdict};
use crate::term::{Env, Node, T, Terms};
use std::collections::{HashMap, HashSet};

/// Why a path stopped before producing a comparable result.
#[derive(Debug, Clone)]
pub enum Stop {
    /// Exploration limit reached; the path (and its subtree) is not verified.
    Truncated(String),
    /// A construct the tool does not model.
    Unsupported(String),
    /// The two sides provably differ; the environment is a concrete witness.
    Mismatch(String, Option<Box<Env>>),
    /// The prover could not decide an equality.
    Inconclusive(String),
    /// The C program has undefined behaviour on every input of this path.
    Undefined,
    /// The C program stopped by calling a function that does not return.
    Halt,
}

pub type R<V> = Result<V, Stop>;

#[derive(Clone, Debug)]
pub struct Write {
    pub addr: T,
    /// Size in bytes.
    pub size: u8,
    pub val: T,
    /// For a store through a pointer of unknown target recorded in a private log: the exposed
    /// object (base, size) it lands in, if it lands in private memory at all.
    pub guard: Option<(T, u32)>,
    /// Not a store but the replacement of a whole range by unknown contents (`size` and `val`
    /// are unused): the object at `addr` was handed to code that may have written all of it.
    pub havoc: Option<Havoc>,
}

/// Unknown contents of an object of `size` bytes: the byte at offset `o` is the byte at
/// `canon + o` of memory `mem`.  Both sides use the same memory and canonical base for the
/// same object, so they read the same values without knowing them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Havoc {
    pub size: T,
    pub mem: u32,
    pub canon: T,
}

/// First identifier of the memories that stand for havocked objects of dynamic size.
pub const HAVOC_BASE: u32 = 0x4000_0000;

/// Bound of a guard that stands for an object of dynamic size.
pub const DYN_GUARD: u32 = 0x7fff_ffff;

/// A private object whose address is known to the outside world (it was passed to an external
/// function): pointers obtained after `since` may point into it.
#[derive(Clone, Debug)]
pub struct Exposed {
    pub base: T,
    pub size: u32,
    /// Size in bytes of an object whose size is not a constant (`size` is then unused).
    pub dyn_size: Option<T>,
    /// First world-memory snapshot in which the address may be found.
    pub since: u32,
}

/// Memory of one side: a write log for "world" memory (anything reachable by the
/// caller) and one per private object (stack frame, C locals).
#[derive(Clone, Debug, Default)]
pub struct Mem {
    pub world: Vec<Write>,
    pub private: HashMap<T, Vec<Write>>,
    /// Snapshot id of world memory; bumped by every external call.
    pub epoch: u32,
    /// Private objects that pointers of unknown origin may point into.
    pub exposed: Vec<Exposed>,
}

/// Snapshot id used for never-written private memory (uninitialised locals, stack).
pub const UNINIT_EPOCH: u32 = 0x8000_0000;

#[derive(Clone, Copy, Debug)]
pub struct Limits {
    /// Maximum number of undetermined branches on one path.
    pub max_depth: usize,
    /// Maximum number of paths per function.
    pub max_paths: usize,
    /// Maximum number of executed C blocks / instructions per path.
    pub max_steps: u64,
    pub max_call_depth: usize,
    /// An access below the stack pointer is a difference, not a hazard (`--strict-stack`).
    pub strict_stack: bool,
}

/// The binary reads or stores below its stack pointer.  Without interrupts that is as good
/// as any other memory until the next call; with them, an exception taken at that point
/// pushes its frame over the bytes.  Reported next to the verdict, which it does not change.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Hazard {
    /// The instruction.
    pub pc: u32,
    pub size: u8,
    pub write: bool,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            max_depth: 40,
            max_paths: 2000,
            max_steps: 20_000,
            max_call_depth: 48,
            strict_stack: false,
        }
    }
}

/// What one arm of a merged region covered.  It counts as verified only if the path it is
/// part of is proved and some input of that path takes the arm (see `Ctx::feasible_arms`).
#[derive(Clone, Debug)]
pub struct Arm {
    /// Conjunction of the conditions under which the arm is executed.
    pub guard: T,
    /// Coverage points of the source.
    pub cov: Vec<u32>,
    /// Instructions and literal data of the binary: (address, length).
    pub insns: Vec<(u32, u8)>,
    pub data: Vec<(u32, u8)>,
}

/// Most places the arms of a merged region may store to.
pub const MAX_JOIN_STORES: usize = 24;

/// Reason of the stop of an arm that would have had to open a new path.
pub const NO_FORK: &str = "merge: fork inside an arm";

/// What is known about a branch condition on the current path.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Open {
    Known(bool),
    /// Both outcomes have a witness.
    Both,
    /// The prover gave up on one of the two questions.
    Unsure,
}

/// The state of the context an arm starts from.
pub struct ArmMark {
    pc: usize,
    ub: usize,
    arms: usize,
}

/// Kinds of branch that open a new path, for the profile printed under `CVERIF_DEBUG`.
pub const FORK_KINDS: [&str; 12] = [
    "other",
    "src-logical",
    "src-cond",
    "src-if",
    "src-switch",
    "src-callee",
    "src-in-callee",
    "bin-forward",
    "bin-backward",
    "bin-it",
    "bin-table",
    "bin-in-callee",
];

pub struct Ctx {
    pub tm: Terms,
    pub prover: Prover,
    /// Path condition: preconditions and branch decisions.
    pub pc: Vec<T>,
    /// Conditions under which the C program has defined behaviour on this path.
    pub ub: Vec<T>,
    /// Those among `ub` that hold in the compiler's model of the language rather than by the
    /// letter of the standard (type-based aliasing as GCC and clang implement it).  They are
    /// the last resort of a proof, and a proof that needed one says so.
    pub model: HashSet<T>,
    /// A proof on this function needed one of the `model` conditions.
    pub model_used: bool,
    /// A plain store the source makes before a loop that never ends is not in the binary.
    pub hang_dropped: bool,
    /// A call to a function the program defines was given the C library's meaning for its
    /// name (a hosted program's `memcpy`, `memmove`, `memset`, `strcmp` of two literals).
    /// Which ones: the function's index, or `u32::MAX` for one evaluated at compile time.
    pub library_used: std::collections::BTreeSet<u32>,
    /// Functions called through a declaration whose type is not the one they are defined
    /// with: the call was given the meaning the calling convention gives it (see
    /// `CExec::through_abi`), which the language leaves undefined.
    pub abi_calls: std::collections::BTreeSet<String>,
    /// Whether the conditions of the current path are satisfiable together with the model
    /// conditions: (length of `pc`, length of `ub`, a checksum of both, answer).
    model_sat: Option<(usize, usize, u64, bool)>,
    /// Deciding on what a call left in a scratch register ends the path (`Stop::Halt`) and
    /// sets `dead_hit`: for a machine compared with another machine, whose callee does not
    /// return if the code after the call does that.
    pub dead_garbage: bool,
    pub dead_hit: bool,
    /// Differences set aside by a comparison of two machines, with the reason.
    pub notes: Vec<String>,
    /// Conditions under which a byte read is one that a store through another address
    /// expression wrote, when `track_overlaps` is set.
    pub track_overlaps: bool,
    pub overlaps: Vec<T>,
    pub decisions: Vec<bool>,
    /// What kind of branch is about to be decided (see `FORK_KINDS`), and how many new
    /// decisions each kind opened: a profile of where the paths of a function come from.
    pub fork_kind: usize,
    pub forks: [u32; FORK_KINDS.len()],
    /// State merging is on: a small conditional region without calls is executed on both
    /// sides of its condition and the results joined into if-then-else terms, instead of
    /// one path per side.
    pub merge: bool,
    /// Inside an arm of such a region (nesting depth): a branch that would open a new path
    /// stops the arm instead (`Stop::Truncated(NO_FORK)`), and the region is then not merged.
    pub no_fork: u32,
    /// Conditions of the arms being executed, outermost first.
    pub guards: Vec<T>,
    /// What the arms of the regions merged on this path covered.
    pub arms: Vec<Arm>,
    /// Regions merged so far in this function, and attempts given up.
    pub merges: (u32, u32),
    /// Join points of conditional regions, found once per function: of the source (keyed by
    /// the address of the body and the block) and of the machine code (keyed by address).
    pub src_joins: HashMap<(usize, usize), Option<usize>>,
    pub bin_joins: HashMap<u32, Option<u32>>,
    /// Conditions of the regions merged so far.
    pub merge_conds: HashSet<T>,
    /// What `Terms::resolve` found for the condition being joined on: (condition, where it
    /// holds, where it does not).
    join_memo: (T, HashMap<T, T>, HashMap<T, T>),
    pub pos: usize,
    pub steps: u64,
    pub limits: Limits,
    /// Accesses below the stack pointer seen on any path so far.
    pub hazards: std::collections::BTreeSet<Hazard>,
    /// Base addresses of private objects.
    pub private_bases: HashSet<T>,
    /// Wall-clock deadline for the current function.
    pub deadline: Option<std::time::Instant>,
    /// Budget in deterministic work units (see `work`), so that results do not depend on
    /// the speed of the machine.
    pub work_limit: u64,
    /// Cap on the number of terms, as a memory guard.
    pub max_terms: usize,
    /// Symbols standing for values the C standard leaves unspecified beyond a constraint (the
    /// magnitude of a `strcmp` result): a proof may rely on the constraint but a refutation that
    /// depends on the symbol is not a real difference.
    pub unspecified: HashSet<T>,
    /// Tag of the proof segment being executed (0: a path from the function entry).  Symbols
    /// that stand for run-time events are named after it, so that the events of an arbitrary
    /// loop iteration are distinct from those that happened before the loop.
    pub seg: u32,
    /// Private objects of the source whose place in the binary's frame is known (see
    /// `verify::match_value`); a counterexample may then mention their addresses.
    pub bound: HashSet<T>,
    /// Symbols that come into existence during execution (results of calls, contents of memory
    /// a callee may have written): the world-memory snapshot from which they exist.
    births: HashMap<T, u32>,
    named: HashMap<String, T>,
}

impl Ctx {
    pub fn new(limits: Limits) -> Ctx {
        Ctx {
            tm: Terms::new(),
            prover: Prover::new(),
            pc: Vec::new(),
            ub: Vec::new(),
            model: HashSet::new(),
            model_used: false,
            library_used: Default::default(),
            abi_calls: Default::default(),
            hang_dropped: false,
            model_sat: None,
            dead_garbage: false,
            dead_hit: false,
            notes: Vec::new(),
            track_overlaps: false,
            overlaps: Vec::new(),
            decisions: Vec::new(),
            fork_kind: 0,
            forks: [0; FORK_KINDS.len()],
            merge: false,
            no_fork: 0,
            guards: Vec::new(),
            arms: Vec::new(),
            merges: (0, 0),
            src_joins: HashMap::new(),
            bin_joins: HashMap::new(),
            merge_conds: HashSet::new(),
            join_memo: (T::MAX, HashMap::new(), HashMap::new()),
            pos: 0,
            steps: 0,
            limits,
            hazards: Default::default(),
            private_bases: HashSet::new(),
            deadline: None,
            work_limit: u64::MAX,
            max_terms: usize::MAX,
            unspecified: HashSet::new(),
            seg: 0,
            bound: HashSet::new(),
            births: HashMap::new(),
            named: HashMap::new(),
        }
    }

    /// A symbol identified by name: the same name gives the same symbol on every path.
    /// Names of the named symbols created so far.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.named.keys().map(|k| k.as_str())
    }

    pub fn named_sym(&mut self, name: &str, w: u8) -> T {
        if let Some(&t) = self.named.get(name) {
            debug_assert_eq!(self.tm.width(t), w);
            return t;
        }
        let t = self.tm.sym(name, w);
        self.named.insert(name.to_string(), t);
        if let Some(b) = Self::birth_of(name) {
            self.births.insert(t, b);
        }
        t
    }

    /// The unknown `t` may hold anything a running path can have computed, the address of an
    /// object exposed to external code included.
    pub fn mark_young(&mut self, t: T) {
        self.births.insert(t, 0);
    }

    /// Symbols created while a path runs are named after the event that produces them:
    /// `ret{k}:…` and `esc{k}:…` exist from snapshot `k + 1`; register garbage after a call
    /// (`clob…`) and values read from volatile objects (`vol…`) are treated as always new.
    fn birth_of(name: &str) -> Option<u32> {
        for prefix in ["ret", "esc"] {
            if let Some(rest) = name.strip_prefix(prefix) {
                let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
                if !digits.is_empty() && rest[digits.len()..].starts_with(':') {
                    return Some(digits.parse::<u32>().unwrap_or(0).saturating_add(1));
                }
            }
        }
        if name.starts_with("clob") || name.starts_with("vol") {
            return Some(0);
        }
        None
    }

    /// Could the value `t` have been computed from something that only became available in
    /// world snapshot `since` or later (so that it may be the address of an object exposed then)?
    pub fn young(&self, t: T, since: u32) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            match self.tm.node(x) {
                crate::term::Node::Load(m, _) if *m >= since => return true,
                _ => {}
            }
            if let Some(&b) = self.births.get(&x)
                && (b == 0 || b >= since)
            {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// May a world address (one that is not syntactically inside a private object) point into
    /// the exposed object `e`?
    pub fn may_point_into(&self, addr: T, e: &Exposed) -> bool {
        self.young(addr, e.since) || self.mentions_private(addr)
    }

    /// `addr` lies inside the exposed object.
    pub fn inside(&mut self, addr: T, e: &Exposed) -> T {
        let off = self.tm.sub(addr, e.base);
        let n = match e.dyn_size {
            Some(n) => n,
            None => self.tm.konst(32, e.size as u64),
        };
        self.tm.ult(off, n)
    }

    /// Replace the `size` bytes of the private object at `base` by the contents of memory `id`
    /// (unknown values, the same for whoever reads the same offset from `canon`).
    pub fn mem_havoc(&mut self, mem: &mut Mem, base: T, size: T, id: u32, canon: T) {
        let Some(r) = self.region(base) else { return };
        mem.private.entry(r).or_default().push(Write {
            addr: base,
            size: 0,
            val: size,
            guard: None,
            havoc: Some(Havoc { size, mem: id, canon }),
        });
    }

    /// How a read of `size` bytes at `addr` relates to a havocked range: (wholly inside,
    /// wholly outside).
    fn havoc_relation(&mut self, addr: T, size: u8, base: T, h: &Havoc) -> (T, T) {
        let off = self.tm.sub(addr, base);
        let n = self.tm.konst(32, size as u64);
        // inside: size <= S and off <= S - size
        let fits = self.tm.ule(n, h.size);
        let room = self.tm.sub(h.size, n);
        let low = self.tm.ule(off, room);
        let inside = self.tm.and(fits, low);
        // outside: at or after the end, or wholly before the start (base - addr >= size)
        let after = self.tm.ule(h.size, off);
        let back = self.tm.sub(base, addr);
        let before = self.tm.ule(n, back);
        let apart = self.tm.and(after, before);
        (inside, apart)
    }

    /// A symbol for a run-time event (a value read or returned), distinct per proof segment.
    pub fn event_sym(&mut self, name: &str, w: u8) -> T {
        if self.seg == 0 {
            self.named_sym(name, w)
        } else {
            let n = format!("{name}~{}", self.seg);
            self.named_sym(&n, w)
        }
    }

    pub fn private_base(&mut self, name: &str) -> T {
        let t = self.named_sym(name, 32);
        self.private_bases.insert(t);
        t
    }

    /// Start replaying from the beginning with the current decision vector.
    pub fn restart(&mut self, pre: &[T]) {
        self.pc.clear();
        self.pc.extend_from_slice(pre);
        self.ub.clear();
        self.model.clear();
        self.model_sat = None;
        self.bound.clear();
        self.pos = 0;
        self.steps = 0;
        self.no_fork = 0;
        self.guards.clear();
        self.arms.clear();
    }

    /// Advance the decision vector to the next unexplored path.  False when done.
    pub fn next_path(&mut self) -> bool {
        while let Some(last) = self.decisions.pop() {
            if last {
                self.decisions.push(false);
                return true;
            }
        }
        false
    }

    pub fn step(&mut self) -> R<()> {
        self.steps += 1;
        if self.steps > self.limits.max_steps {
            return Err(Stop::Truncated("step limit".into()));
        }
        self.check_deadline()
    }

    /// Work done so far: one unit per term created and per thousand solver propagations.
    /// Deterministic for a given input, unlike elapsed time.
    pub fn work(&self) -> u64 {
        self.prover.counters().3 / 1000 + self.tm.len() as u64
    }

    /// Set the effort limits for the current function.
    pub fn set_budget(&mut self, work_limit: u64, max_terms: usize, deadline: Option<std::time::Instant>) {
        self.work_limit = work_limit;
        self.max_terms = max_terms;
        self.deadline = deadline;
        // The solver stops by itself when the whole budget has gone into propagation.
        self.prover.set_limits(work_limit.saturating_mul(1000), deadline);
    }

    pub fn check_deadline(&self) -> R<()> {
        if self.tm.len() > self.max_terms {
            return Err(Stop::Truncated("term limit".into()));
        }
        if self.work_limit != u64::MAX && self.work() > self.work_limit {
            return Err(Stop::Truncated("work limit".into()));
        }
        match self.deadline {
            Some(d) if std::time::Instant::now() > d => Err(Stop::Truncated("time limit".into())),
            _ => Ok(()),
        }
    }

    /// Does the path condition (with the no-undefined-behaviour assumptions if needed) imply `goal`?
    pub fn implied(&mut self, goal: T) -> bool {
        self.check(goal).is_ok()
    }

    /// Prove `goal` on this path.  On failure returns a counterexample if one exists (None = solver gave up).
    pub fn check(&mut self, goal: T) -> Result<(), Option<Box<Env>>> {
        if self.tm.is_true(goal) {
            return Ok(());
        }
        let goal = self.decide(goal);
        if self.tm.is_true(goal) {
            return Ok(());
        }
        // The goal as the path condition makes it (see `under_path_facts`): often true as
        // it stands, and otherwise the question the solver is asked, since a table read at
        // `base` is, where the path says `base == 10`, the read the other side made at 10.
        let goal = self.under_path_facts(goal);
        if self.tm.is_true(goal) {
            return Ok(());
        }
        // (Not first without the assumptions: most questions are answered "no", and a
        // counterexample that ignores them answers nothing.  Only the compilers' model is
        // kept apart, because its use is reported.)
        if self.ub.is_empty() {
            return match self.prover.prove(&mut self.tm, &self.pc, goal) {
                Verdict::Proved => Ok(()),
                Verdict::Refuted(env) => Err(Some(env)),
                Verdict::Unknown => Err(None),
            };
        }
        let mut all = self.pc.clone();
        let has_model = self.ub.iter().any(|u| self.model.contains(u));
        if !has_model {
            all.extend_from_slice(&self.ub);
            return match self.prover.prove(&mut self.tm, &all, goal) {
                Verdict::Proved => Ok(()),
                Verdict::Refuted(env) => Err(Some(env)),
                Verdict::Unknown => self.check_plain(goal),
            };
        }
        // First what the standard itself guarantees, then the compiler's model as well.
        all.extend(self.ub.iter().filter(|u| !self.model.contains(u)));
        let strict = match self.prover.prove(&mut self.tm, &all, goal) {
            Verdict::Proved => return Ok(()),
            Verdict::Refuted(env) => Err(Some(env)),
            Verdict::Unknown => match self.check_plain(goal) {
                Ok(()) => return Ok(()),
                e => e,
            },
        };
        if !self.model_consistent() {
            return strict;
        }
        let mut all = self.pc.clone();
        all.extend_from_slice(&self.ub);
        match self.prover.prove(&mut self.tm, &all, goal) {
            Verdict::Proved => {
                self.model_used = true;
                Ok(())
            }
            Verdict::Refuted(env) => Err(Some(env)),
            Verdict::Unknown => Err(None),
        }
    }

    /// The goal with what the path condition says outright put in: a one-bit term the path
    /// asserts or denies is that constant, and a term it equates with a constant is that
    /// constant.  The result is equivalent to the goal on this path (anything that satisfies
    /// the path condition gives both the same value), and may be far easier: a compiler that
    /// tests a sign with a shift and masks with the result leaves `x & ~sext(y[31])` where
    /// the source, on the path where `y >= 0`, has `x`; no solver should have to compare two
    /// dividers to see that.
    ///
    /// (The solver then meets terms it has not seen while the path was explored, and can
    /// take longer over a goal that is false: the gcd mutant of `tests/loops.rs` is found
    /// with a third more work.  On MicroPython nothing is lost and three functions gained.)
    fn under_path_facts(&mut self, goal: T) -> T {
        if self.pc.is_empty() {
            return goal;
        }
        let mut facts: HashMap<T, T> = HashMap::new();
        for i in 0..self.pc.len() {
            let h = self.pc[i];
            if self.tm.width(h) != 1 || self.tm.as_const(h).is_some() {
                continue;
            }
            let (t, v) = match *self.tm.node(h) {
                crate::term::Node::Not(t) => (t, 0),
                _ => (h, 1),
            };
            if let crate::term::Node::Eq(a, b) = *self.tm.node(h) {
                if self.tm.as_const(b).is_some() && self.tm.as_const(a).is_none() {
                    facts.insert(a, b);
                } else if self.tm.as_const(a).is_some() && self.tm.as_const(b).is_none() {
                    facts.insert(b, a);
                }
            }
            let k = self.tm.konst(1, v);
            facts.insert(t, k);
        }
        if facts.is_empty() {
            return goal;
        }
        self.tm.subst(goal, &facts, &mut HashMap::new())
    }

    /// The solver gave up with the assumptions: they can be in its way, and what follows from
    /// the path alone follows with them.  (A counterexample found here would ignore them.)
    fn check_plain(&mut self, goal: T) -> Result<(), Option<Box<Env>>> {
        match self.prover.prove(&mut self.tm, &self.pc, goal) {
            Verdict::Proved => Ok(()),
            _ => Err(None),
        }
    }

    /// The model conditions are only used on a path they do not contradict: where the source
    /// certainly accesses one object with two types, compilers see it too, and assuming the
    /// opposite would prove anything.
    fn model_consistent(&mut self) -> bool {
        let sum =
            (self.pc.iter().chain(&self.ub)).fold(0u64, |h, &t| h.wrapping_mul(0x100_0000_01b3).wrapping_add(t as u64));
        let key = (self.pc.len(), self.ub.len(), sum);
        if let Some((a, b, c, ok)) = self.model_sat
            && (a, b, c) == key
        {
            return ok;
        }
        let mut all = self.pc.clone();
        all.extend_from_slice(&self.ub);
        let f = self.tm.fals();
        let ok = matches!(self.prover.prove(&mut self.tm, &all, f), Verdict::Refuted(_));
        self.model_sat = Some((key.0, key.1, key.2, ok));
        ok
    }

    /// Record a condition that holds in the compiler's model of the language (see `model`).
    pub fn assume_model(&mut self, cond: T) -> R<()> {
        if self.tm.is_true(cond) || self.tm.is_false(cond) {
            // Certain overlap is not undefined by this rule: it is simply not assumed away.
            return Ok(());
        }
        if !self.ub.contains(&cond) {
            self.ub.push(cond);
            self.model.insert(cond);
        }
        Ok(())
    }

    /// What the path says about a condition, without deciding it.
    pub fn probe(&mut self, cond: T) -> Open {
        if let Some(c) = self.tm.as_const(cond) {
            return Open::Known(c == 1);
        }
        let n = self.tm.not(cond);
        if self.pc.contains(&cond) {
            return Open::Known(true);
        }
        if self.pc.contains(&n) {
            return Open::Known(false);
        }
        if self.dead_garbage && self.mentions_garbage(cond) {
            return Open::Unsure;
        }
        match self.check(cond) {
            Ok(()) => return Open::Known(true),
            Err(None) => return Open::Unsure,
            Err(Some(_)) => {}
        }
        match self.check(n) {
            Ok(()) => Open::Known(false),
            Err(None) => Open::Unsure,
            Err(Some(_)) => Open::Both,
        }
    }

    /// Start executing an arm of a region to be merged, under the condition `g`.
    pub fn arm_begin(&mut self, g: T) -> ArmMark {
        let mark = ArmMark {
            pc: self.pc.len(),
            ub: self.ub.len(),
            arms: self.arms.len(),
        };
        self.pc.push(g);
        self.guards.push(g);
        self.no_fork += 1;
        mark
    }

    /// Leave the arm: the path condition is what it was, and the conditions for defined
    /// behaviour the arm added are handed back (with whether each is a model condition)
    /// to be kept, guarded, if the region is merged.
    pub fn arm_end(&mut self, mark: &ArmMark) -> Vec<(T, bool)> {
        self.pc.truncate(mark.pc);
        self.guards.pop();
        self.no_fork -= 1;
        self.model_sat = None;
        let added = self.ub.split_off(mark.ub);
        added
            .into_iter()
            .map(|u| {
                let model = self.model.contains(&u) && !self.ub.contains(&u);
                if model {
                    self.model.remove(&u);
                }
                (u, model)
            })
            .collect()
    }

    /// Forget what the arms executed since `mark` covered: the region is not merged.
    pub fn arm_discard(&mut self, mark: &ArmMark) {
        self.arms.truncate(mark.arms);
        self.merges.1 += 1;
    }

    /// The source is defined on the arm taken under `g` only if `conds` hold.
    pub fn arm_commit(&mut self, g: T, conds: Vec<(T, bool)>) {
        let ng = self.tm.not(g);
        for (u, model) in conds {
            let c = self.tm.or(ng, u);
            if self.tm.is_true(c) || self.ub.contains(&c) {
                continue;
            }
            self.ub.push(c);
            if model {
                self.model.insert(c);
            }
        }
        self.model_sat = None;
    }

    /// The address `t` free of choices made by merged regions: which object an access
    /// touches is read off the address, so the path is split there after all, on the
    /// condition of the region (or the condition is already settled, and the choice goes).
    pub fn settle(&mut self, mut t: T) -> R<T> {
        if self.merge_conds.is_empty() {
            return Ok(t);
        }
        while let Some(c) = self.merged_choice(t) {
            let d = self.branch(c)?;
            let r = self.tm.resolve(t, c, d, &mut HashMap::new());
            if r == t {
                // (A choice where `resolve` does not look: left as it is.)
                break;
            }
            t = r;
        }
        Ok(t)
    }

    /// `goal` with the choices of merged regions resolved whose condition the path has
    /// decided since (by a later branch on it, or because one side turned out undefined):
    /// the same under what the path assumes, and without the side that is not taken.
    fn decide(&mut self, goal: T) -> T {
        if self.merge_conds.is_empty() {
            return goal;
        }
        let mut stack: Vec<T> = self.pc.iter().chain(self.ub.iter()).copied().collect();
        let mut decided = Vec::new();
        let mut steps = 0;
        while let Some(x) = stack.pop() {
            steps += 1;
            if steps > 4096 {
                break;
            }
            if self.merge_conds.contains(&x) {
                decided.push(x);
            } else if let Node::And(a, b) = *self.tm.node(x) {
                stack.extend([a, b]);
            } else if let Node::Not(o) = *self.tm.node(x)
                && let Node::Or(a, b) = *self.tm.node(o)
            {
                let (na, nb) = (self.tm.not(a), self.tm.not(b));
                stack.extend([na, nb]);
            }
        }
        let mut goal = goal;
        for c in decided {
            let (c, v) = match *self.tm.node(c) {
                Node::Not(a) => (a, false),
                _ => (c, true),
            };
            goal = self.tm.resolve(goal, c, v, &mut HashMap::new());
        }
        goal
    }

    /// The condition of a merged region that a choice inside `t` is made on.
    fn merged_choice(&self, t: T) -> Option<T> {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) || seen.len() > 4096 {
                continue;
            }
            let n = self.tm.node(x);
            if let Node::Ite(c, ..) = n {
                // The condition itself, or a combination of conditions.
                let mut inner = vec![*c];
                let mut steps = 0;
                while let Some(y) = inner.pop() {
                    if self.merge_conds.contains(&y) {
                        return Some(y);
                    }
                    steps += 1;
                    if steps < 16
                        && let Node::Not(a) | Node::And(a, _) | Node::Or(a, _) = self.tm.node(y)
                    {
                        inner.push(*a);
                        if let Node::And(_, b) | Node::Or(_, b) = self.tm.node(y) {
                            inner.push(*b);
                        }
                    }
                }
            }
            if matches!(n, Node::Load(..)) {
                // (What a load yields does not depend on how its address is written.)
                continue;
            }
            stack.extend(Prover::children_of(n));
        }
        None
    }

    /// Debugging aid (`CVERIF_DEBUG_MERGE=1`): say what became of a region.
    pub fn merge_note(&self, what: impl FnOnce() -> String) {
        thread_local! {
            static ON: bool = std::env::var_os("CVERIF_DEBUG_MERGE").is_some();
        }
        if ON.with(|x| *x) {
            eprintln!("merge[{}]: {}", self.no_fork, what());
        }
    }

    /// The condition under which the code being executed runs: all enclosing arms.
    pub fn guard(&mut self) -> T {
        let mut g = self.tm.tru();
        for i in 0..self.guards.len() {
            g = self.tm.and(g, self.guards[i]);
        }
        g
    }

    /// The arms merged on this path that some input of the path takes, now that the path is
    /// complete: what a later condition for defined behaviour excludes is not covered.
    pub fn feasible_arms(&mut self) -> Vec<Arm> {
        let mut left = std::mem::take(&mut self.arms);
        let mut out = Vec::new();
        if left.is_empty() {
            return out;
        }
        // One input of the path shows many arms at once: all those it takes.
        let never = self.tm.fals();
        let mut witness = match self.check(never) {
            Err(w) => w,
            // No input takes the path at all.
            Ok(()) => return out,
        };
        while !left.is_empty() {
            if let Some(env) = witness.take() {
                let mut memo = HashMap::new();
                let (taken, rest): (Vec<Arm>, Vec<Arm>) = left
                    .into_iter()
                    .partition(|a| self.tm.eval(a.guard, &env, &mut memo) == 1);
                out.extend(taken);
                left = rest;
            }
            let Some(a) = left.pop() else { break };
            let n = self.tm.not(a.guard);
            match self.check(n) {
                Ok(()) => {}
                Err(w) => {
                    // (Taken by some input, or the prover cannot say: counted, as a
                    // branch it cannot decide is followed.)
                    witness = w;
                    out.push(a);
                }
            }
        }
        out
    }

    /// Decide a branch condition, forking the path if it is not determined.
    pub fn branch(&mut self, cond: T) -> R<bool> {
        let kind = std::mem::take(&mut self.fork_kind);
        if let Some(c) = self.tm.as_const(cond) {
            return Ok(c == 1);
        }
        self.check_deadline()?;
        let n = self.tm.not(cond);
        if self.pc.contains(&cond) {
            return Ok(true);
        }
        if self.pc.contains(&n) {
            return Ok(false);
        }
        if self.dead_garbage && self.mentions_garbage(cond) {
            self.dead_hit = true;
            return Err(Stop::Halt);
        }
        if self.implied(cond) {
            return Ok(true);
        }
        if self.implied(n) {
            return Ok(false);
        }
        if self.no_fork > 0 {
            return Err(Stop::Truncated(NO_FORK.into()));
        }
        let d = if self.pos < self.decisions.len() {
            self.decisions[self.pos]
        } else {
            if self.decisions.len() >= self.limits.max_depth {
                return Err(Stop::Truncated("branch depth limit".into()));
            }
            self.decisions.push(true);
            self.forks[kind] += 1;
            true
        };
        self.pos += 1;
        self.pc.push(if d { cond } else { n });
        Ok(d)
    }

    /// Does the term depend on what a call left in a register it may clobber?
    pub fn mentions_garbage(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) || seen.len() > 2000 {
                continue;
            }
            let n = self.tm.node(x);
            if let Node::Sym(id) = n
                && self.tm.sym_name(*id).starts_with("clob")
            {
                return true;
            }
            stack.extend(Prover::children_of(n));
        }
        false
    }

    /// Record that the C program is only defined when `cond` holds.
    pub fn assume(&mut self, cond: T) -> R<()> {
        if self.tm.is_true(cond) {
            return Ok(());
        }
        if self.tm.is_false(cond) {
            return Err(Stop::Undefined);
        }
        if !self.ub.contains(&cond) {
            self.ub.push(cond);
        } else if self.model.remove(&cond) {
            // What was so far only the compilers' reading is now also what the standard says.
            self.model_sat = None;
        }
        Ok(())
    }

    /// If the path condition pins `t` to a single value, return it.
    pub fn unique_value(&mut self, t: T) -> Option<u64> {
        if let Some(v) = self.tm.as_const(t) {
            return Some(v);
        }
        let f = self.tm.fals();
        let Err(Some(env)) = self.check(f) else { return None };
        let v = self.tm.eval(t, &env, &mut HashMap::new());
        let k = self.tm.konst(self.tm.width(t), v);
        let e = self.tm.eq(t, k);
        if self.implied(e) { Some(v) } else { None }
    }

    // ----- memory -------------------------------------------------------------

    /// The private object an address belongs to, if any.
    pub fn region(&self, addr: T) -> Option<T> {
        if self.private_bases.contains(&addr) {
            return Some(addr);
        }
        let (ts, _) = self.tm.linear(addr);
        ts.iter().map(|x| x.0).find(|t| self.private_bases.contains(t))
    }

    #[track_caller]
    pub fn mem_write(&mut self, mem: &mut Mem, addr: T, size: u8, val: T) {
        // (In every build: a store whose value is narrower than its size is only found out
        // by a later load, far from here.)
        assert!(
            (1..=8).contains(&size) && self.tm.width(val) == size * 8,
            "ill-formed store: a {}-bit value stored in {size} bytes",
            self.tm.width(val)
        );
        let region = self.region(addr);
        if region.is_none() {
            // A store through a pointer of unknown target may land in an exposed private object.
            for i in 0..mem.exposed.len() {
                let e = mem.exposed[i].clone();
                if !self.may_point_into(addr, &e) {
                    continue;
                }
                if let Some(r) = self.region(e.base) {
                    mem.private.entry(r).or_default().push(Write {
                        addr,
                        size,
                        val,
                        guard: Some((e.base, if e.dyn_size.is_some() { DYN_GUARD } else { e.size })),
                        havoc: None,
                    });
                }
            }
        }
        let log = match region {
            Some(r) => mem.private.entry(r).or_default(),
            None => &mut mem.world,
        };
        // Drop older writes that this one fully covers.
        let tm = &mut self.tm;
        log.retain(|e| {
            e.havoc.is_some()
                || match tm.const_diff(e.addr, addr) {
                    Some(d) => {
                        let d = d as u32 as i32 as i64;
                        !(d >= 0 && d + e.size as i64 <= size as i64)
                    }
                    None => true,
                }
        });
        log.push(Write {
            addr,
            size,
            val,
            guard: None,
            havoc: None,
        });
    }

    /// The value that is `a` where `cond` holds and `b` elsewhere.  None when either may be
    /// the address of a private object: which object an address belongs to is read off its
    /// term, and a choice between two addresses would hide it.
    pub fn join_value(&mut self, cond: T, a: T, b: T) -> Option<T> {
        if a == b {
            return Some(a);
        }
        if self.private_address(a) || self.private_address(b) {
            return None;
        }
        self.merge_conds.insert(cond);
        let n = self.tm.not(cond);
        self.merge_conds.insert(n);
        // Inside each side the condition is decided: earlier choices on it go, so that
        // the two executors arrive at the same term for the same value.
        if self.join_memo.0 != cond {
            self.join_memo = (cond, HashMap::new(), HashMap::new());
        }
        let a = self.tm.resolve(a, cond, true, &mut self.join_memo.1);
        let b = self.tm.resolve(b, cond, false, &mut self.join_memo.2);
        Some(self.tm.ite(cond, a, b))
    }

    /// May the value be (derived from) the address of a private object?  What was loaded
    /// from never-written private memory is not.
    fn private_address(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.private_bases.contains(&x) {
                return true;
            }
            let n = self.tm.node(x);
            if matches!(n, Node::Load(m, ..) if *m == UNINIT_EPOCH) {
                continue;
            }
            stack.extend(Prover::children_of(n));
        }
        false
    }

    /// The memory after a conditional region whose arms, both starting from `base`, left
    /// `a` (where `cond` holds) and `b` (where it does not): every place either arm stored
    /// to holds the one or the other arm's final value.  None when the arms did more than a
    /// few plain stores.  `read` reads a memory as its side does.
    ///
    /// `source`: the memories are the C program's.  A local that only one arm has given a
    /// value then has that value after the region: on the other side it is indeterminate,
    /// and whatever the binary does with it there is as good as this choice.
    pub fn join_mem(
        &mut self,
        cond: T,
        base: &Mem,
        a: &Mem,
        b: &Mem,
        source: bool,
        read: &mut dyn FnMut(&mut Ctx, &Mem, T, u8) -> T,
    ) -> Option<Mem> {
        if a.epoch != base.epoch
            || b.epoch != base.epoch
            || a.exposed.len() != base.exposed.len()
            || b.exposed.len() != base.exposed.len()
        {
            return None;
        }
        static EMPTY: Vec<Write> = Vec::new();
        let mut places: Vec<(T, u8)> = Vec::new();
        Self::stored(&base.world, &a.world, &mut places)?;
        Self::stored(&base.world, &b.world, &mut places)?;
        let mut keys: Vec<T> = a.private.keys().chain(b.private.keys()).copied().collect();
        keys.sort_unstable();
        keys.dedup();
        for k in keys {
            let old = base.private.get(&k).unwrap_or(&EMPTY);
            Self::stored(old, a.private.get(&k).unwrap_or(&EMPTY), &mut places)?;
            Self::stored(old, b.private.get(&k).unwrap_or(&EMPTY), &mut places)?;
        }
        if places.len() > MAX_JOIN_STORES {
            return None;
        }
        let mut out = base.clone();
        for (addr, size) in places {
            let va = read(self, a, addr, size);
            let vb = read(self, b, addr, size);
            let fresh = |tm: &Terms, v: T| matches!(tm.node(v), Node::Load(m, at) if *m == UNINIT_EPOCH && *at == addr);
            let v = if source && fresh(&self.tm, vb) {
                va
            } else if source && fresh(&self.tm, va) {
                vb
            } else {
                self.join_value(cond, va, vb)?
            };
            self.mem_write(&mut out, addr, size, v);
        }
        Some(out)
    }

    /// The places whose contents may differ between a write log and the log `old` it was
    /// derived from: what was stored since, and what such a store replaced.
    fn stored(old: &[Write], new: &[Write], places: &mut Vec<(T, u8)>) -> Option<()> {
        let same = |x: &Write, y: &Write| {
            x.addr == y.addr && x.size == y.size && x.val == y.val && x.guard == y.guard && x.havoc == y.havoc
        };
        let mut kept = vec![false; old.len()];
        let mut j = 0;
        let mut fresh = Vec::new();
        for w in new {
            match (j..old.len()).find(|&k| same(&old[k], w)) {
                Some(k) if fresh.is_empty() => {
                    kept[k] = true;
                    j = k + 1;
                }
                _ => fresh.push(w),
            }
        }
        let gone = old.iter().zip(&kept).filter(|x| !*x.1).map(|x| x.0);
        for w in gone.chain(fresh) {
            if w.havoc.is_some() || w.guard.is_some() {
                return None;
            }
            if !places.contains(&(w.addr, w.size)) {
                places.push((w.addr, w.size));
            }
        }
        Some(())
    }

    /// Read `size` bytes at `addr`.  `init` supplies the value of never-written memory.
    #[track_caller]
    pub fn mem_read(&mut self, mem: &Mem, addr: T, size: u8, init: &mut dyn FnMut(&mut Ctx, T, u8) -> T) -> T {
        let v = self.mem_read_unchecked(mem, addr, size, init);
        // (What a load yields has the width of the load, whoever supplied it: a stored value,
        // unknown contents, or `init`.)
        assert!(
            self.tm.width(v) == size.wrapping_mul(8),
            "ill-formed load: {size} bytes read as a {}-bit value",
            self.tm.width(v)
        );
        v
    }

    fn mem_read_unchecked(&mut self, mem: &Mem, addr: T, size: u8, init: &mut dyn FnMut(&mut Ctx, T, u8) -> T) -> T {
        static EMPTY: Vec<Write> = Vec::new();
        let Some(r) = self.region(addr) else {
            let mut v = self.read_log(&mem.world, mem.world.len(), addr, size, init);
            // A load through a pointer of unknown target may read an exposed private object.
            for e in &mem.exposed {
                if !self.may_point_into(addr, e) {
                    continue;
                }
                let Some(r) = self.region(e.base) else { continue };
                let inside = self.inside(addr, e);
                // Settled by the path (or by what the language guarantees about it): the
                // access does not touch this object.
                let outside = self.tm.not(inside);
                if self.implied(outside) {
                    continue;
                }
                // Only what was stored in the object itself matters: the region may hold
                // much else (the whole stack frame, on the machine side).
                let log: Vec<Write> = (mem.private.get(&r).unwrap_or(&EMPTY).iter())
                    .filter(|w| match self.tm.const_diff(w.addr, e.base) {
                        Some(d) => {
                            let d = d as u32 as i32 as i64;
                            d < e.size as i64 + size as i64 - 1 && d + w.size as i64 > 0
                        }
                        None => true,
                    })
                    .cloned()
                    .collect();
                let inner = self.read_log(&log, log.len(), addr, size, init);
                v = self.tm.ite(inside, inner, v);
            }
            return v;
        };
        let log = mem.private.get(&r).unwrap_or(&EMPTY);
        self.read_log(log, log.len(), addr, size, init)
    }

    /// Read from an explicit write log (newest entry last).
    pub fn read_world(&mut self, log: &[Write], addr: T, size: u8, init: &mut dyn FnMut(&mut Ctx, T, u8) -> T) -> T {
        self.read_log(log, log.len(), addr, size, init)
    }

    fn read_log(
        &mut self,
        log: &[Write],
        n: usize,
        addr: T,
        size: u8,
        init: &mut dyn FnMut(&mut Ctx, T, u8) -> T,
    ) -> T {
        let mut slow_at = None;
        for i in (0..n).rev() {
            let e = &log[i];
            if let Some(h) = e.havoc {
                let base = e.addr;
                if let Some(d) = self.tm.const_diff(addr, base)
                    && (d as u32 as i32 as i64) + size as i64 <= 0
                {
                    continue;
                }
                let (inside, apart) = self.havoc_relation(addr, size, base, &h);
                if self.implied(apart) {
                    continue;
                }
                let off = self.tm.sub(addr, base);
                let ca = self.tm.add(h.canon, off);
                if self.implied(inside) {
                    return self.tm.load(h.mem, ca, size);
                }
                if size > 1 {
                    // Straddles the boundary, or cannot be placed: byte by byte.
                    slow_at = Some(i);
                    break;
                }
                let fresh = self.tm.load(h.mem, ca, 1);
                let rest = self.read_log(log, i, addr, 1, init);
                return self.tm.ite(inside, fresh, rest);
            }
            // A store that can only have landed in another object.
            if let Some((gbase, gsize)) = e.guard
                && let Some(d) = self.tm.const_diff(addr, gbase)
            {
                let d = d as u32 as i32 as i64;
                if d >= gsize as i64 || d + size as i64 <= 0 {
                    continue;
                }
            }
            match self.tm.const_diff(addr, e.addr) {
                Some(d) => {
                    let d = d as u32 as i32 as i64;
                    if d >= e.size as i64 || d + size as i64 <= 0 {
                        continue;
                    }
                    if d >= 0 && d + size as i64 <= e.size as i64 {
                        return self.tm.extract(e.val, d as u8 * 8, size * 8);
                    }
                    slow_at = Some(i);
                    break;
                }
                None => {
                    if e.size == size {
                        let same = self.tm.eq(addr, e.addr);
                        if self.implied(same) {
                            return e.val;
                        }
                    }
                    let dis = self.disjoint(addr, size, e);
                    if self.implied(dis) {
                        continue;
                    }
                    // Two accesses of the same size, both aligned to it, are to the same
                    // bytes or to disjoint ones: no need to assemble the value from pieces.
                    if e.size == size && size > 1 && self.aligned(addr, size) && self.aligned(e.addr, size) {
                        let same = self.tm.eq(addr, e.addr);
                        let val = e.val;
                        let rest = self.read_log(log, i, addr, size, init);
                        return self.tm.ite(same, val, rest);
                    }
                    slow_at = Some(i);
                    break;
                }
            }
        }
        let Some(i) = slow_at else {
            return init(self, addr, size);
        };
        if size > 1 {
            // Assemble from single bytes.
            let mut acc: Option<T> = None;
            for k in 0..size {
                let a = self.tm.add_const(addr, k as u64);
                let b = self.read_log(log, i + 1, a, 1, init);
                acc = Some(match acc {
                    None => b,
                    Some(lo) => self.tm.concat(b, lo),
                });
            }
            return acc.unwrap();
        }
        // One byte against an entry whose relation is unknown.
        let e = &log[i];

        let w = self.tm.width(addr);
        let d = self.tm.sub(addr, e.addr);
        let sz = self.tm.konst(w, e.size as u64);
        let inside = self.tm.ult(d, sz);
        if self.track_overlaps
            && self.overlaps.len() < 256
            && !self.tm.is_true(inside)
            && !self.tm.is_false(inside)
            && !self.overlaps.contains(&inside)
        {
            self.overlaps.push(inside);
        }
        let sel = if e.size == 1 {
            e.val
        } else {
            let vw = self.tm.width(e.val);
            let d8 = self.tm.scale(d, 8);
            let amt = self.tm.resize(d8, vw, false);
            let sh = self.tm.lshr(e.val, amt);
            self.tm.trunc(sh, 8)
        };
        if self.implied(inside) {
            return sel;
        }
        let rest = self.read_log(log, i, addr, 1, init);
        self.tm.ite(inside, sel, rest)
    }

    /// Is the address known to be a multiple of `size` (a power of two) on this path?
    fn aligned(&mut self, addr: T, size: u8) -> bool {
        if !size.is_power_of_two() {
            return false;
        }
        let bits = size.trailing_zeros() as u8;
        let low = self.tm.extract(addr, 0, bits);
        let zero = self.tm.konst(bits, 0);
        let ok = self.tm.eq(low, zero);
        self.tm.is_true(ok) || self.pc.contains(&ok) || self.ub.contains(&ok) || self.implied(ok)
    }

    fn disjoint(&mut self, addr: T, size: u8, e: &Write) -> T {
        let w = self.tm.width(addr);
        let d1 = self.tm.sub(addr, e.addr);
        let d2 = self.tm.sub(e.addr, addr);
        let s1 = self.tm.konst(w, e.size as u64);
        let s2 = self.tm.konst(w, size as u64);
        let a = self.tm.ule(s1, d1);
        let b = self.tm.ule(s2, d2);
        self.tm.and(a, b)
    }

    /// Split a pointer into a private object's base and the offset from it.  None if `t` is not
    /// exactly one private base plus a term free of private addresses.
    pub fn private_split(&mut self, t: T) -> Option<(T, T)> {
        let base = if self.private_bases.contains(&t) {
            t
        } else {
            let (ts, _) = self.tm.linear(t);
            let mut it = ts.iter().filter(|x| self.private_bases.contains(&x.0));
            match (it.next(), it.next()) {
                (Some(&(b, 1)), None) => b,
                _ => return None,
            }
        };
        let off = self.tm.sub(t, base);
        if self.mentions_private(off) {
            None
        } else {
            Some((base, off))
        }
    }

    /// Does `t` depend on the contents of never-written private memory (an indeterminate value)?
    pub fn mentions_uninit(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if let crate::term::Node::Load(m, _) = self.tm.node(x)
                && *m >= UNINIT_EPOCH
            {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// Does `t` depend on a value the C standard leaves unspecified?
    pub fn mentions_unspecified(&self, t: T) -> bool {
        if self.unspecified.is_empty() {
            return false;
        }
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.unspecified.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// Is `x` a subterm of `t`?
    pub fn mentions(&self, t: T, x: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(y) = stack.pop() {
            if y == x {
                return true;
            }
            if !seen.insert(y) {
                continue;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(y)));
        }
        false
    }

    /// Is `t` computed only from the function's inputs: no value read from memory, returned by
    /// a call or otherwise created while the path ran?
    pub fn pristine(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(y) = stack.pop() {
            if !seen.insert(y) {
                continue;
            }
            if matches!(self.tm.node(y), crate::term::Node::Load(..)) || self.births.contains_key(&y) {
                return false;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(y)));
        }
        true
    }

    /// Does `t` mention the address of a private object whose place in the binary is unknown?
    pub fn mentions_unbound_private(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.private_bases.contains(&x) && !self.bound.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// Does `t` mention the address of a private object?
    pub fn mentions_private(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.private_bases.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }
}

/// 64-bit product in the shape 32-bit code computes it: from the halves of the operands.  Both
/// executors build products through this function so that they arrive at the same term.
pub fn mul64(tm: &mut Terms, a: T, b: T) -> T {
    use crate::term::Node;
    let widened = |tm: &Terms, t: T| matches!(tm.node(t), Node::ZExt(_) | Node::SExt(_) | Node::Const(_));
    if tm.width(a) != 64 || (widened(tm, a) && widened(tm, b)) {
        return tm.mul(a, b);
    }
    let (al, ah) = (tm.extract(a, 0, 32), tm.extract(a, 32, 32));
    let (bl, bh) = (tm.extract(b, 0, 32), tm.extract(b, 32, 32));
    let (za, zb) = (tm.zext(al, 64), tm.zext(bl, 64));
    let full = tm.mul(za, zb);
    let lo = tm.extract(full, 0, 32);
    let carry = tm.extract(full, 32, 32);
    let x1 = tm.mul(ah, bl);
    let x2 = tm.mul(al, bh);
    let hi = tm.add(x1, x2);
    let hi = tm.add(hi, carry);
    tm.concat(hi, lo)
}

/// Where the AAPCS places an argument.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArgLoc {
    Reg(u8),
    /// 64-bit value in registers n (low) and n + 1 (high).
    RegPair(u8),
    /// Offset from the stack pointer at the call.
    Stack(u32),
    Stack64(u32),
}

/// Assign AAPCS32 locations to integer arguments of the given bit widths (<= 32 or 64).
pub fn arg_locs(widths: &[u8]) -> Vec<ArgLoc> {
    let mut ncrn = 0u8;
    let mut nsaa = 0u32;
    widths
        .iter()
        .map(|&w| {
            if w <= 32 {
                if ncrn < 4 {
                    ncrn += 1;
                    ArgLoc::Reg(ncrn - 1)
                } else {
                    nsaa += 4;
                    ArgLoc::Stack(nsaa - 4)
                }
            } else {
                ncrn = ncrn.next_multiple_of(2);
                if ncrn <= 2 {
                    ncrn += 2;
                    ArgLoc::RegPair(ncrn - 2)
                } else {
                    ncrn = 4;
                    nsaa = nsaa.next_multiple_of(8) + 8;
                    ArgLoc::Stack64(nsaa - 8)
                }
            }
        })
        .collect()
}

/// A local object of the C program whose address has been handed to an external function.
/// From then on every external call may read and modify it.
#[derive(Clone, Debug)]
pub struct Escaped {
    /// The object's private base address on the C side.
    pub base: T,
    pub size: u32,
    /// The alignment the object's type requires: the callee may rely on it.
    pub align: u32,
    /// For an object whose size is not a constant (a variable-length array, an `alloca` block):
    /// its size in bytes, the source's writes to it up to the call (`pre` is unused) and the
    /// memory that stands for its contents after the call (`post` is unused).
    pub dynamic: Option<Box<DynEscaped>>,
    pub name: String,
    /// Contents at the call: (offset, size in bytes, value).  The value is None where the C
    /// program left the bytes indeterminate (never written, padding): the binary may hold anything there.
    pub pre: Vec<(u32, u8, Option<T>)>,
    /// Contents after the call: fresh symbols shared by both sides.  Empty if the call does not return.
    pub post: Vec<(u32, u8, T)>,
}

#[derive(Clone, Debug)]
pub struct DynEscaped {
    pub size: T,
    pub log: Vec<Write>,
    /// None if the call does not return.
    pub havoc: Option<u32>,
}

/// Where one 32-bit word of an argument is passed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WordLoc {
    Reg(u8),
    /// Offset from the stack pointer at the call.
    Stack(u32),
}

/// AAPCS32 locations of the words of each argument, given (size in bytes, needs 8-byte
/// alignment) per argument.  Covers integers and composites passed by value, which may be
/// split between registers and the stack.  `first_reg` is 1 when r0 holds the address of the
/// result (functions returning a composite larger than four bytes).
pub fn arg_words(args: &[(u32, bool)], first_reg: u8) -> Vec<Vec<WordLoc>> {
    let mut ncrn = first_reg as u32;
    let mut nsaa = 0u32;
    args.iter()
        .map(|&(size, align8)| {
            let words = size.div_ceil(4).max(1);
            if align8 {
                ncrn = ncrn.next_multiple_of(2);
            }
            let mut locs = Vec::with_capacity(words as usize);
            if ncrn < 4 && (ncrn + words <= 4 || nsaa == 0) {
                for _ in 0..words {
                    if ncrn < 4 {
                        locs.push(WordLoc::Reg(ncrn as u8));
                        ncrn += 1;
                    } else {
                        locs.push(WordLoc::Stack(nsaa));
                        nsaa += 4;
                    }
                }
            } else {
                ncrn = 4;
                if align8 {
                    nsaa = nsaa.next_multiple_of(8);
                }
                for _ in 0..words {
                    locs.push(WordLoc::Stack(nsaa));
                    nsaa += 4;
                }
            }
            locs
        })
        .collect()
}

/// An externally observable call made by the C side, to be matched by the binary.
#[derive(Clone, Debug)]
pub struct Event {
    pub name: String,
    /// Argument values and whether each is signed (for extension to register width).
    pub args: Vec<(T, bool)>,
    /// Arguments of which only some bits carry a value (words of a structure with padding):
    /// (argument index, mask of the value bits).
    pub arg_masks: Vec<(usize, u64)>,
    /// World memory at the time of the call.
    pub writes: Vec<Write>,
    pub epoch: u32,
    /// Symbol standing for the returned value, and its signedness.
    pub ret: Option<(T, bool)>,
    pub noreturn: bool,
    /// Local objects reachable by the callee, in discovery order.
    pub escaped: Vec<Escaped>,
    /// The source's exposed objects once the call has been made.
    pub exposed: Vec<Exposed>,
    /// The event is an inline assembly instruction rather than a call (the name starts with
    /// `asm:`); the flag tells whether the statement clobbers memory.  Without that, world
    /// memory is neither compared nor considered changed at the event: the compiler may move
    /// ordinary stores across the statement.
    pub asm: Option<bool>,
    /// The callee may return a second time (`setjmp`): see `verify::RtLog`.
    pub returns_twice: bool,
}