cverif 0.0.2

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
//! Loops whose trip count depends on the input, proved by induction.
//!
//! Path-by-path exploration can only cover a loop up to some number of iterations.  This module
//! instead pairs a loop of the source with a loop of the machine code at a *cut point* (a block
//! of the source, an address of the binary) and proves a simulation relation there:
//!
//! * **base** — on every path from the function entry, when both sides first arrive at the cut
//!   point the relation holds;
//! * **step** — started at the cut point in *any* state satisfying the relation, both sides
//!   either leave the function with equal results or arrive at the cut point again with the
//!   relation holding, having performed the same observable events in between.
//!
//! Together these cover every execution with any number of iterations.  The relation is a
//! conjunction of simple facts guessed from one concrete path through the loop — a location
//! keeps the value it had on arrival, a machine location equals a source variable, or is a
//! linear function of one — and weakened until it is inductive: a fact that fails in the base
//! or the step is dropped and everything is checked again.  Whatever no fact constrains is
//! replaced by a fresh unknown at the start of the step, so the step really covers every state
//! the relation admits.  Any difficulty makes the attempt fail, leaving the function to the
//! bounded exploration; nothing found here is ever reported as a difference.

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

/// Coverage established by a successful proof.
#[derive(Default)]
pub(super) struct Proof {
    pub cov: Vec<u32>,
    pub bytes: Vec<(u32, u8)>,
    pub paths: usize,
}

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

#[derive(Clone, Debug)]
enum Cand {
    /// The location holds this value on every arrival.
    Inv(T),
    /// A machine location holds the value of source location `.0`.
    Rel(usize, View),
    /// A machine location holds `a * view(source location) + b`.
    Lin(usize, View, u64, T),
}

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

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

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

#[derive(Clone)]
struct Cut {
    id: usize,
    c_block: usize,
    m_pc: u32,
    /// Arrivals of the source at its cut block when the machine code first reaches its own
    /// (more than one when the compiler peeled iterations off the front of the loop).
    lead: usize,
    /// Source iterations per machine iteration (more than one for an unrolled loop).
    ratio: usize,
    c_locs: Vec<Loc>,
    m_locs: Vec<Loc>,
    /// Private objects of the source whose every byte is a location.
    c_full: HashSet<T>,
    /// The branch that leads into the cut block, known to have been taken on arrival.
    pred: Option<(usize, bool)>,
    pred_exprs: Vec<(Expr, bool)>,
    /// Comparisons between variables of the source believed to hold on every arrival.
    facts: Vec<(Expr, bool)>,
    fail_facts: BTreeSet<usize>,
    /// World memory is not modified by the loop: both sides keep the write log of the first arrival.
    world_same: bool,
    c_world: Vec<Write>,
    c_epoch: u32,
    m_world: Vec<Write>,
    m_epoch: u32,
    // Facts refuted in the current round.
    fail_c: BTreeSet<usize>,
    fail_m: BTreeSet<usize>,
    fail_pred: bool,
    fail_world: bool,
    grew: bool,
}

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

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

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

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

/// Natural loops of the control-flow graph, by head.
fn c_loops(body: &Body) -> Vec<CLoop> {
    let n = body.blocks.len();
    let succ: Vec<Vec<usize>> = body.blocks.iter().map(|b| successors(&b.term)).collect();
    // Iterative depth-first search; an edge to a block on the current path is a back edge.
    let mut state = vec![0u8; n];
    let mut back: Vec<(usize, usize)> = Vec::new();
    let mut stack: Vec<(usize, usize)> = vec![(0, 0)];
    state[0] = 1;
    while let Some(&mut (b, ref mut i)) = stack.last_mut() {
        if *i < succ[b].len() {
            let s = succ[b][*i];
            *i += 1;
            match state[s] {
                0 => {
                    state[s] = 1;
                    stack.push((s, 0));
                }
                1 => back.push((b, s)),
                _ => {}
            }
        } else {
            state[b] = 2;
            stack.pop();
        }
    }
    let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (b, ss) in succ.iter().enumerate() {
        if state[b] != 0 {
            for &s in ss {
                preds[s].push(b);
            }
        }
    }
    let mut heads: Vec<usize> = back.iter().map(|e| e.1).collect();
    heads.sort_unstable();
    heads.dedup();
    heads
        .into_iter()
        .map(|head| {
            let mut inside: HashSet<usize> = HashSet::from([head]);
            let mut work: Vec<usize> = back.iter().filter(|e| e.1 == head).map(|e| e.0).collect();
            while let Some(b) = work.pop() {
                if inside.insert(b) {
                    work.extend(preds[b].iter().copied());
                }
            }
            let mut cands: Vec<usize> = Vec::new();
            if matches!(body.blocks[head].term, Term::Br(..)) {
                for &s in &succ[head] {
                    if s != head && inside.contains(&s) && !cands.contains(&s) {
                        cands.push(s);
                    }
                }
            }
            cands.push(head);
            CLoop { cands }
        })
        .collect()
}

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

/// Both polarities of every comparison between local variables and constants that the
/// function branches on.  Evaluating one reads only local variables and cannot be undefined.
fn simple_facts(p: &Program, body: &Body) -> Vec<(Expr, bool)> {
    fn leaf(p: &Program, e: &Expr) -> bool {
        match &e.kind {
            EK::Const(_) => true,
            EK::Load(x) => matches!(x.kind, EK::Local(_)) && !p.is_volatile(x.ty) && !p.is_float(e.ty),
            EK::Cast(x) => !p.is_float(e.ty) && leaf(p, x),
            _ => false,
        }
    }
    fn atoms<'e>(p: &Program, e: &'e Expr, out: &mut Vec<&'e Expr>) {
        use crate::c::ast::BinOp::*;
        match &e.kind {
            EK::LogNot(x) => atoms(p, x, out),
            EK::LogAnd(a, b) | EK::LogOr(a, b) => {
                atoms(p, a, out);
                atoms(p, b, out);
            }
            EK::Cast(x) if !leaf(p, e) => atoms(p, x, out),
            EK::Bin(Eq | Ne | Lt | Le, a, b) if leaf(p, a) && leaf(p, b) => out.push(e),
            _ if leaf(p, e) && !matches!(e.kind, EK::Const(_)) => out.push(e),
            _ => {}
        }
    }
    let mut found = Vec::new();
    for b in &body.blocks {
        if let Term::Br(e, ..) = &b.term {
            atoms(p, e, &mut found);
        }
    }
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for e in found {
        if seen.insert(format!("{:?}", e.kind)) && out.len() < 40 {
            out.push((e.clone(), true));
            out.push((e.clone(), false));
            // A loop counting up to a bound keeps `i <= n`, though it tests `i < n`.
            if let EK::Bin(op @ (BinOp::Lt | BinOp::Le), a, b) = &e.kind {
                let other = if *op == BinOp::Lt { BinOp::Le } else { BinOp::Lt };
                let mut weak = e.clone();
                weak.kind = EK::Bin(other, a.clone(), b.clone());
                out.push((weak.clone(), true));
                out.push((weak, false));
            }
        }
    }
    out
}

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

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

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

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

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

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

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

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

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

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

struct Explored {
    c: Vec<CutSnap>,
    m: Vec<MachSnap>,
}

/// One complete path of the function on which the loops iterate, with the state of both sides
/// at every arrival at a candidate cut point.
fn explore(
    ctx: &mut Ctx,
    job: &Job,
    pre: &[T],
    loops: &[CLoop],
    range: (u32, u32),
    depths: &[usize],
) -> Option<Explored> {
    let watch: Vec<usize> = loops.iter().flat_map(|l| l.cands.iter().copied()).collect();
    let mut best: Option<(usize, Vec<bool>, Vec<u32>)> = None;
    'search: for &depth in depths {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        for _ in 0..48 {
            ctx.restart(pre);
            let ctl = SegCtl {
                c_cuts: &watch,
                ..Default::default()
            };
            match run_seg(ctx, job, &ctl) {
                Ok(end) => {
                    let twice = loops
                        .iter()
                        .filter(|l| end.cx.cut_snaps.iter().filter(|s| s.block == l.cands[0]).count() >= 2)
                        .count();
                    let targets: Vec<u32> = end
                        .m
                        .back_targets
                        .iter()
                        .copied()
                        .filter(|&a| a >= range.0 && a < range.1)
                        .collect();
                    // Prefer a path on which the machine code looped too.
                    let score = twice * 2 + usize::from(!targets.is_empty());
                    if twice > 0 && best.as_ref().is_none_or(|b| score > b.0) {
                        let done = twice == loops.len() && !targets.is_empty();
                        best = Some((score, ctx.decisions[..ctx.pos].to_vec(), targets));
                        if done {
                            break 'search;
                        }
                    }
                }
                Err(Stop::Truncated(why)) if why != "branch depth limit" => {
                    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
                        eprintln!("explore: {why}");
                    }
                    return None;
                }
                Err(e) => {
                    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
                        eprintln!("explore path: {e:?}");
                    }
                }
            }
            if !ctx.next_path() {
                break 'search;
            }
        }
    }
    if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
        eprintln!("explore: best {best:x?}");
    }
    let (_, decisions, targets) = best?;
    if targets.is_empty() {
        return None;
    }
    // Replay the same path, now watching the targets of the machine's backward jumps.
    ctx.limits.max_depth = decisions.len();
    ctx.decisions = decisions;
    ctx.restart(pre);
    let ctl = SegCtl {
        c_cuts: &watch,
        m_cuts: &targets,
        ..Default::default()
    };
    let end = run_seg(ctx, job, &ctl).ok()?;
    Some(Explored {
        c: end.cx.cut_snaps,
        m: end.m.cut_snaps,
    })
}

/// Build the cut point (block, address) with the facts suggested by the explored path.
fn build_cut(ctx: &mut Ctx, job: &Job, ex: &Explored, id: usize, plan: Pair) -> Option<Cut> {
    let p = job.prog;
    let f = &p.funcs[job.fid as usize];
    let (c_block, m_pc) = (plan.block, plan.pc);
    let all: Vec<&CutSnap> = ex.c.iter().filter(|s| s.block == c_block).collect();
    let cs: Vec<&CutSnap> = [plan.lead - 1, plan.lead - 1 + plan.ratio]
        .into_iter()
        .filter_map(|i| all.get(i).copied())
        .collect();
    let ms: Vec<&MachSnap> = ex.m.iter().filter(|s| s.pc == m_pc).take(2).collect();
    let (c1, m1) = (*cs.first()?, *ms.first()?);
    let second = match (cs.get(1), ms.get(1)) {
        (Some(c), Some(m)) => Some((*c, *m)),
        _ => None,
    };
    // Source locations: every local of the function, the objects of structure arguments, and
    // whatever else is private and written.
    let mut c_locs = Vec::new();
    let mut c_cover = Cover::default();
    let mut c_full = HashSet::new();
    for (i, l) in f.locals.iter().enumerate() {
        let base = ctx.private_base(&format!("&{}.{}#{i}@1", f.name, l.name));
        let size = p.size_of(l.ty).unwrap_or(0);
        if size == 0 {
            continue;
        }
        if size > 256 {
            return None; // too large to track byte by byte
        }
        c_cover.add(&mut c_locs, base, 0, size);
        c_full.insert(base);
    }
    for (base, words) in &job.struct_args {
        c_cover.add(&mut c_locs, *base, 0, 4 * words.len() as u32);
        c_full.insert(*base);
    }
    let mut m_locs: Vec<Loc> = (0..15)
        .map(|r| Loc {
            place: Place::Reg(r),
            cands: Vec::new(),
            active: 0,
            refined: false,
        })
        .collect();
    let mut m_cover = Cover::default();
    let none = HashSet::new();
    for (c, m) in [Some((c1, m1)), second].into_iter().flatten() {
        for (base, off, size) in extents(ctx, &c.mem, &c_full)? {
            c_cover.add(&mut c_locs, base, off, size);
        }
        for (base, off, size) in extents(ctx, &m.mem, &none)? {
            m_cover.add(&mut m_locs, base, off, size);
        }
    }
    // Values at the first and second arrival.
    let cv1: Vec<T> = c_locs.iter().map(|l| c_read(ctx, job, &c1.mem, l.place)).collect();
    let mv1: Vec<T> = m_locs
        .iter()
        .map(|l| m_read(ctx, job, &m1.regs, &m1.mem, l.place))
        .collect();
    let (cv2, mv2) = match second {
        Some((c2, m2)) => (
            Some(
                c_locs
                    .iter()
                    .map(|l| c_read(ctx, job, &c2.mem, l.place))
                    .collect::<Vec<T>>(),
            ),
            Some(
                m_locs
                    .iter()
                    .map(|l| m_read(ctx, job, &m2.regs, &m2.mem, l.place))
                    .collect::<Vec<T>>(),
            ),
        ),
        None => (None, None),
    };
    for i in 0..c_locs.len() {
        if cv2.as_ref().is_none_or(|v| v[i] == cv1[i]) {
            c_locs[i].cands.push(Cand::Inv(cv1[i]));
            continue;
        }
        // Moving in step with an earlier source variable: c_i = a * c_j + b.
        let Some(c2) = &cv2 else { continue };
        let w = c_locs[i].width();
        let Some(di) = ctx.tm.const_diff(c2[i], cv1[i]) else {
            continue;
        };
        for j in 0..i {
            if ctx.tm.width(cv1[j]) != w || c_locs[j].cands.iter().any(|c| matches!(c, Cand::Inv(_))) {
                continue;
            }
            let Some(dj) = ctx.tm.const_diff(c2[j], cv1[j]) else {
                continue;
            };
            let (di, dj) = (crate::term::sext64(di, w), crate::term::sext64(dj, w));
            if dj == 0 || di % dj != 0 {
                continue;
            }
            let a = (di / dj) as u64 & crate::term::mask(w);
            let scaled = ctx.tm.scale(cv1[j], a);
            let b = ctx.tm.sub(cv1[i], scaled);
            c_locs[i].cands.push(Cand::Lin(j, View::Same, a, b));
        }
    }
    for (i, l) in m_locs.iter_mut().enumerate() {
        let w = l.width();
        let steady = mv2.as_ref().is_none_or(|v| v[i] == mv1[i]);
        if steady {
            l.cands.push(Cand::Inv(mv1[i]));
        }
        // Equal to a source variable at every arrival seen.
        for (j, &c) in cv1.iter().enumerate() {
            for view in views(ctx.tm.width(c), w) {
                let Some(t1) = apply_view(ctx, c, view, w) else {
                    continue;
                };
                if t1 != mv1[i] {
                    continue;
                }
                let also = match (&cv2, &mv2) {
                    (Some(c2), Some(m2)) => apply_view(ctx, c2[j], view, w) == Some(m2[i]),
                    _ => true,
                };
                if also {
                    l.cands.push(Cand::Rel(j, view));
                }
            }
        }
        // Moving in step with a source variable: m = a * c + b.
        if let (Some(c2), Some(m2), 32) = (&cv2, &mv2, w)
            && let Some(dm) = ctx.tm.const_diff(m2[i], mv1[i])
            && dm != 0
        {
            for (j, &c) in cv1.iter().enumerate() {
                let cw = ctx.tm.width(c);
                let Some(dc) = ctx.tm.const_diff(c2[j], c) else {
                    continue;
                };
                let view = match cw {
                    32 => View::Same,
                    8 | 16 => View::Zext,
                    _ => continue,
                };
                let (dm, dc) = (dm as u32 as i32 as i64, crate::term::sext64(dc, cw));
                if dc == 0 || dm % dc != 0 {
                    continue;
                }
                let a = (dm / dc) as u64 & 0xffff_ffff;
                let Some(v1) = apply_view(ctx, c, view, 32) else {
                    continue;
                };
                let scaled = ctx.tm.scale(v1, a);
                let b = ctx.tm.sub(mv1[i], scaled);
                if a == 1 && ctx.tm.as_const(b) == Some(0) {
                    continue; // already a plain equality
                }
                l.cands.push(Cand::Lin(j, view, a, b));
            }
        }
    }
    // The branch condition under which the cut block is entered.
    let mut pred = None;
    let mut pred_exprs = Vec::new();
    if let Some((b, taken)) = c1.last_br
        && cs.iter().all(|s| s.last_br == c1.last_br)
        && let Some(body) = &f.body
        && let Term::Br(e, ..) = &body.blocks[b].term
        && pure_conditions(p, e, taken, &mut pred_exprs)
    {
        pred = Some((b, taken));
    } else {
        pred_exprs.clear();
    }
    let world_same = second.is_none_or(|(c2, m2)| {
        same_log(&c1.mem.world, &c2.mem.world)
            && same_log(&m1.mem.world, &m2.mem.world)
            && c1.mem.epoch == c2.mem.epoch
            && m1.mem.epoch == m2.mem.epoch
    });
    Some(Cut {
        id,
        c_block,
        m_pc,
        lead: plan.lead,
        ratio: plan.ratio,
        c_locs,
        m_locs,
        c_full,
        pred,
        pred_exprs,
        facts: simple_facts(p, f.body.as_ref()?),
        fail_facts: BTreeSet::new(),
        world_same,
        c_world: c1.mem.world.clone(),
        c_epoch: c1.mem.epoch,
        m_world: m1.mem.world.clone(),
        m_epoch: m1.mem.epoch,
        fail_c: BTreeSet::new(),
        fail_m: BTreeSet::new(),
        fail_pred: false,
        fail_world: false,
        grew: false,
    })
}

fn expected(ctx: &mut Ctx, cand: &Cand, cvals: &[T], w: u8) -> Option<T> {
    match cand {
        Cand::Inv(v) => Some(*v),
        Cand::Rel(j, view) => apply_view(ctx, cvals[*j], *view, w),
        Cand::Lin(j, view, a, b) => {
            let v = apply_view(ctx, cvals[*j], *view, w)?;
            let s = ctx.tm.scale(v, *a);
            Some(ctx.tm.add(s, *b))
        }
    }
}

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

/// Both sides arrived at the cut point: check every fact of the relation in the state reached.
fn arrive(ctx: &mut Ctx, job: &Job, cut: &mut Cut, end: &mut SegEnd) -> R<()> {
    if end.cx.has_escaped() {
        return Err(fail("a local object is visible to external code at the loop head"));
    }
    // Private memory written anywhere must be a location, so that the step starts from a
    // state in which it is unknown.
    let Some(c_ext) = extents(ctx, &end.cx.mem, &cut.c_full) else {
        return Err(fail("the source writes a local object at a computed offset"));
    };
    let Some(m_ext) = extents(ctx, &end.m.mem, &HashSet::new()) else {
        return Err(fail("the binary writes its stack frame at a computed offset"));
    };
    let mut c_cover = Cover::default();
    let mut m_cover = Cover::default();
    for l in &cut.c_locs {
        if let Place::Mem { base, off, size } = l.place {
            c_cover.0.entry(base).or_default().extend(off..off + size as i64);
        }
    }
    for l in &cut.m_locs {
        if let Place::Mem { base, off, size } = l.place {
            m_cover.0.entry(base).or_default().extend(off..off + size as i64);
        }
    }
    for (base, off, size) in c_ext {
        cut.grew |= c_cover.add(&mut cut.c_locs, base, off, size);
    }
    for (base, off, size) in m_ext {
        cut.grew |= m_cover.add(&mut cut.m_locs, base, off, size);
    }
    if cut.grew {
        return Ok(());
    }
    let cvals: Vec<T> = cut
        .c_locs
        .iter()
        .map(|l| c_read(ctx, job, &end.cx.mem, l.place))
        .collect();
    // Locations thought constant that moved by a constant instead: (location, old value, change).
    let mut c_moved: Vec<(usize, T, i64)> = Vec::new();
    let mut m_moved: Vec<(usize, T, i64)> = Vec::new();
    for (i, l) in cut.c_locs.iter().enumerate() {
        match l.cands.get(l.active) {
            Some(cand) => {
                let ok = match expected(ctx, cand, &cvals, l.width()) {
                    Some(want) => holds(ctx, cvals[i], want),
                    None => false,
                };
                if !ok {
                    cut.fail_c.insert(i);
                    if let Cand::Inv(v) = cand
                        && let Some(d) = ctx.tm.const_diff(cvals[i], *v)
                        && d != 0
                    {
                        c_moved.push((i, *v, crate::term::sext64(d, l.width())));
                    }
                }
            }
            None => {
                if may_point_private(ctx, cvals[i]) {
                    return Err(fail(
                        "a pointer to a local object changes in the loop in a way that is not understood",
                    ));
                }
            }
        }
    }
    for i in 0..cut.m_locs.len() {
        let l = &cut.m_locs[i];
        let got = m_read(ctx, job, &end.m.regs, &end.m.mem, l.place);
        match l.cands.get(l.active) {
            Some(cand) => {
                let ok = match expected(ctx, cand, &cvals, l.width()) {
                    Some(want) => holds(ctx, got, want),
                    None => false,
                };
                if !ok {
                    cut.fail_m.insert(i);
                    if let Cand::Inv(v) = cand
                        && l.width() == 32
                        && let Some(d) = ctx.tm.const_diff(got, *v)
                        && d != 0
                    {
                        m_moved.push((i, *v, d as u32 as i32 as i64));
                    }
                }
            }
            None => {
                if may_point_private(ctx, got) {
                    return Err(fail(
                        "a stack address changes in the loop in a way that is not understood",
                    ));
                }
            }
        }
    }
    // A location that moves in step with a source variable is a linear function of it.
    for &(i, v, d) in &m_moved {
        if cut.m_locs[i].refined {
            continue;
        }
        cut.m_locs[i].refined = true;
        for &(j, cv, dc) in &c_moved {
            let view = match cut.c_locs[j].width() {
                32 => View::Same,
                8 | 16 => View::Zext,
                _ => continue,
            };
            if d % dc != 0 {
                continue;
            }
            let a = (d / dc) as u64 & 0xffff_ffff;
            let Some(c32) = apply_view(ctx, cv, view, 32) else {
                continue;
            };
            let scaled = ctx.tm.scale(c32, a);
            let b = ctx.tm.sub(v, scaled);
            cut.m_locs[i].cands.push(Cand::Lin(j, view, a, b));
        }
    }
    for &(i, v, d) in &c_moved {
        if cut.c_locs[i].refined {
            continue;
        }
        cut.c_locs[i].refined = true;
        let w = cut.c_locs[i].width();
        for &(j, cv, dc) in &c_moved {
            if j >= i || cut.c_locs[j].width() != w || d % dc != 0 {
                continue;
            }
            let a = (d / dc) as u64 & crate::term::mask(w);
            let scaled = ctx.tm.scale(cv, a);
            let b = ctx.tm.sub(v, scaled);
            cut.c_locs[i].cands.push(Cand::Lin(j, View::Same, a, b));
        }
    }
    for (k, (e, want)) in cut.facts.iter().enumerate() {
        let (npc, nub) = (ctx.pc.len(), ctx.ub.len());
        let v = end.cx.eval(ctx, e);
        let clean = ctx.pc.len() == npc && ctx.ub.len() == nub;
        ctx.pc.truncate(npc);
        ctx.ub.truncate(nub);
        let ok = match v {
            Ok(v) if clean => {
                let nz = ctx.tm.nonzero(v);
                let c = if *want { nz } else { ctx.tm.not(nz) };
                ctx.tm.is_true(c) || ctx.implied(c)
            }
            _ => false,
        };
        if !ok {
            cut.fail_facts.insert(k);
        }
    }
    if cut.pred.is_some() && end.cx.last_br != cut.pred {
        cut.fail_pred = true;
    }
    if cut.world_same {
        let same = same_log(&end.cx.mem.world, &cut.c_world)
            && same_log(&end.m.mem.world, &cut.m_world)
            && end.cx.mem.epoch == cut.c_epoch
            && end.m.mem.epoch == cut.m_epoch;
        if !same {
            cut.fail_world = true;
        }
    } else {
        compare_world(
            ctx,
            job,
            &end.cx.mem.world,
            end.cx.mem.epoch,
            &end.cx.mem.exposed,
            &end.m,
            "memory at a loop head",
            &mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
        )?;
    }
    Ok(())
}

/// An arbitrary state satisfying the relation of `cut`.
fn start_state(ctx: &mut Ctx, cut: &Cut) -> Option<SegInit> {
    let tag = format!("hv{}", cut.id);
    let fresh_epoch = 0x4000_0000 + ((cut.id as u32) << 16);
    let mut c_mem = Mem::default();
    let mut m_mem = Mem::default();
    if cut.world_same {
        c_mem.world = cut.c_world.clone();
        c_mem.epoch = cut.c_epoch;
        m_mem.world = cut.m_world.clone();
        m_mem.epoch = cut.m_epoch;
    } else {
        c_mem.epoch = fresh_epoch;
        m_mem.epoch = fresh_epoch;
    }
    let mut cvals = Vec::with_capacity(cut.c_locs.len());
    for (i, l) in cut.c_locs.iter().enumerate() {
        let Place::Mem { base, off, size } = l.place else {
            unreachable!()
        };
        let v = match l.cands.get(l.active) {
            Some(cand) => expected(ctx, cand, &cvals, size * 8)?,
            None => ctx.named_sym(&format!("{tag}.c{i}.{}", size * 8), size * 8),
        };
        let a = ctx.tm.add_const(base, off as u64);
        ctx.mem_write(&mut c_mem, a, size, v);
        cvals.push(v);
    }
    let mut regs = [ctx.tm.konst(32, 0); 16];
    for (i, l) in cut.m_locs.iter().enumerate() {
        let w = l.width();
        let v = match l.cands.get(l.active) {
            Some(cand) => expected(ctx, cand, &cvals, w)?,
            None => ctx.named_sym(&format!("{tag}.m{i}.{w}"), w),
        };
        match l.place {
            Place::Reg(r) => regs[r as usize] = v,
            Place::Mem { base, off, size } => {
                let a = ctx.tm.add_const(base, off as u64);
                ctx.mem_write(&mut m_mem, a, size, v);
            }
        }
    }
    Some(SegInit {
        c_block: cut.c_block,
        c_mem,
        m_pc: cut.m_pc,
        m_regs: regs,
        m_mem,
        tag,
    })
}

/// Try to prove the function with the given cut points.  Err: the attempt failed.
fn attempt(ctx: &mut Ctx, job: &Job, pre: &[T], cuts: &mut [Cut], depth: usize) -> R<Proof> {
    let blocks: Vec<usize> = cuts.iter().map(|c| c.c_block).collect();
    let pcs: Vec<u32> = cuts.iter().map(|c| c.m_pc).collect();
    ctx.limits.max_depth = depth;
    for _round in 0..60 {
        let mut proof = Proof::default();
        for start in std::iter::once(None).chain((0..cuts.len()).map(Some)) {
            ctx.seg = start.map_or(0, |j| j as u32 + 1);
            let init = match start {
                Some(j) => Some(start_state(ctx, &cuts[j]).ok_or_else(|| fail("no start state"))?),
                None => None,
            };
            let mut exprs: Vec<(Expr, bool)> = Vec::new();
            if let Some(j) = start {
                // Once the base case has refuted something, the step would start from a
                // relation already known to be wrong.
                if cuts.iter().any(|c| c.refuted()) {
                    break;
                }
                if cuts[j].pred.is_some() {
                    exprs.extend(cuts[j].pred_exprs.iter().cloned());
                }
                exprs.extend(cuts[j].facts.iter().cloned());
            }
            ctx.decisions.clear();
            let mut n = 0;
            loop {
                ctx.restart(pre);
                let ctl = SegCtl {
                    init: init.as_ref(),
                    assume: exprs.iter().map(|(e, w)| (e, *w)).collect(),
                    c_cuts: &blocks,
                    m_cuts: &pcs,
                    stop: match start {
                        None => cuts[0].lead,
                        Some(j) => cuts[j].ratio,
                    },
                    m_stop: 1,
                };
                match run_seg(ctx, job, &ctl) {
                    Ok(mut end) => {
                        if let Some((b, pc)) = end.cut {
                            let j = blocks.iter().position(|&x| x == b).expect("a cut block");
                            if cuts[j].m_pc != pc {
                                return Err(fail("the two sides arrive at different loops"));
                            }
                            arrive(ctx, job, &mut cuts[j], &mut end)?;
                        }
                        proof.paths += 1;
                        proof.cov.extend(end.res.cov);
                        proof.bytes.extend(end.res.insns);
                        proof.bytes.extend(end.res.data);
                    }
                    Err(Stop::Undefined) => {}
                    Err(e) => return Err(e),
                }
                n += 1;
                if n > 400 {
                    return Err(Stop::Truncated("too many paths through a loop body".into()));
                }
                if !ctx.next_path() {
                    break;
                }
            }
        }
        // Drop what was refuted; done when nothing was.
        let mut changed = false;
        if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
            for cut in cuts.iter() {
                eprintln!(
                    "  round {_round} cut ({}, {:#x}): refuted source {:?} machine {:?} facts {:?} pred {} world {} grew {}",
                    cut.c_block,
                    cut.m_pc,
                    cut.fail_c,
                    cut.fail_m,
                    cut.fail_facts,
                    cut.fail_pred,
                    cut.fail_world,
                    cut.grew
                );
            }
        }
        for cut in cuts.iter_mut() {
            for i in std::mem::take(&mut cut.fail_c) {
                cut.c_locs[i].active += 1;
                changed = true;
            }
            for i in std::mem::take(&mut cut.fail_m) {
                cut.m_locs[i].active += 1;
                changed = true;
            }
            let dead = std::mem::take(&mut cut.fail_facts);
            if !dead.is_empty() {
                let mut k = 0;
                cut.facts.retain(|_| {
                    k += 1;
                    !dead.contains(&(k - 1))
                });
                changed = true;
            }
            if std::mem::take(&mut cut.fail_pred) {
                cut.pred = None;
                changed = true;
            }
            if std::mem::take(&mut cut.fail_world) {
                cut.world_same = false;
                changed = true;
            }
            changed |= std::mem::take(&mut cut.grew);
        }
        if !changed {
            return Ok(proof);
        }
    }
    Err(Stop::Truncated("the loop relation did not stabilise".into()))
}

/// Prove the whole function by induction over its loops.  None if no proof was found.
pub(super) fn prove(ctx: &mut Ctx, job: &Job, pre: &[T], range: (u32, u32)) -> Option<Proof> {
    let debug = std::env::var_os("CVERIF_DEBUG").is_some();
    let body = job.prog.funcs[job.fid as usize].body.as_ref()?;
    let loops = c_loops(body);
    if loops.is_empty() {
        return None;
    }
    let saved = (ctx.limits, ctx.seg);
    let result = (|| {
        // A short path through the loops first; a long one if that is not enough (unrolled
        // loops only show their period after several iterations).
        let mut short = false;
        for (stage, depths) in [&[3usize, 5, 8][..], &[12, 20][..]].into_iter().enumerate() {
            let Some(ex) = explore(ctx, job, pre, &loops, range, depths) else {
                continue;
            };
            let plain = !short;
            short = true;
            // Candidate pairings per loop: a cut block of the source with a machine address that
            // was reached about as often on the explored path.
            let mut per_loop: Vec<Vec<Pair>> = Vec::new();
            for l in &loops {
                let mut pairs: Vec<(usize, Pair)> = Vec::new();
                for (order, &block) in l.cands.iter().enumerate() {
                    let nc = ex.c.iter().filter(|s| s.block == block).count();
                    if nc == 0 {
                        continue;
                    }
                    let mut counts: BTreeMap<u32, usize> = BTreeMap::new();
                    for s in &ex.m {
                        *counts.entry(s.pc).or_default() += 1;
                    }
                    for (pc, nm) in counts {
                        if plain {
                            let pair = Pair {
                                block,
                                pc,
                                lead: 1,
                                ratio: 1,
                            };
                            pairs.push((nc.abs_diff(nm) * 4 + order, pair));
                        }
                        if stage == 1 && nm >= 2 && nc > nm {
                            // `ratio` source iterations per machine iteration, after `lead` of them.
                            let (low, high) = (nc.div_ceil(nm + 1).max(2), (nc - 1) / (nm - 1));
                            for ratio in (low..=high).rev().take(4) {
                                let span = (nm - 1) * ratio;
                                for lead in 1..=ratio {
                                    if lead + span <= nc {
                                        let pair = Pair { block, pc, lead, ratio };
                                        pairs.push((100 + order + 2 * lead, pair));
                                    }
                                }
                            }
                        }
                    }
                }
                pairs.sort_by_key(|p| (p.0, p.1.pc, p.1.ratio, p.1.lead));
                pairs.truncate(if stage == 0 { 6 } else { 30 });
                if !pairs.is_empty() {
                    per_loop.push(pairs.into_iter().map(|p| p.1).collect());
                }
            }
            // One loop at a time first, then all loops together.
            let mut plans: Vec<Vec<Pair>> = per_loop.iter().flatten().map(|&p| vec![p]).collect();
            if per_loop.len() >= 2 && plain {
                let mut combos: Vec<Vec<Pair>> = vec![Vec::new()];
                for pairs in &per_loop {
                    let mut next = Vec::new();
                    for c in &combos {
                        for &p in pairs.iter().take(4) {
                            if c.iter().any(|q: &Pair| q.pc == p.pc) {
                                continue;
                            }
                            let mut c = c.clone();
                            c.push(p);
                            next.push(c);
                        }
                    }
                    combos = next;
                    combos.truncate(24);
                }
                plans.extend(combos);
            }
            for plan in plans.into_iter().take(64) {
                if ctx.check_deadline().is_err() {
                    return None;
                }
                let mut cuts = Vec::new();
                for (id, &pair) in plan.iter().enumerate() {
                    let Some(cut) = build_cut(ctx, job, &ex, id, pair) else {
                        break;
                    };
                    cuts.push(cut);
                }
                if cuts.len() != plan.len() {
                    continue;
                }
                if std::env::var_os("CVERIF_DEBUG_LOOPS").is_some() {
                    for cut in &cuts {
                        eprintln!(
                            "cut ({}, {:#x}) lead {} ratio {} pred {:?} world_same {}",
                            cut.c_block, cut.m_pc, cut.lead, cut.ratio, cut.pred, cut.world_same
                        );
                        for (side, locs) in [("source", &cut.c_locs), ("machine", &cut.m_locs)] {
                            for (i, l) in locs.iter().enumerate() {
                                let cands: Vec<String> = l
                                    .cands
                                    .iter()
                                    .map(|c| match c {
                                        Cand::Inv(v) => format!("= {}", ctx.tm.show(*v)),
                                        Cand::Rel(j, view) => format!("= {view:?}(source {j})"),
                                        Cand::Lin(j, _, a, b) => {
                                            format!("= {}*source {j} + {}", *a as u32 as i32, ctx.tm.show(*b))
                                        }
                                    })
                                    .collect();
                                eprintln!("  {side} {i} {:?}: {}", l.place, cands.join(" | "));
                            }
                        }
                    }
                }
                match attempt(ctx, job, pre, &mut cuts, 16) {
                    Ok(proof) => return Some(proof),
                    Err(e) => {
                        if debug {
                            eprintln!("loop proof with cuts {plan:x?} failed: {e:?}");
                        }
                    }
                }
            }
        }
        None
    })();
    ctx.limits = saved.0;
    ctx.seg = saved.1;
    ctx.decisions.clear();
    result
}