vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
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
//! Whether the callers of a function read what it returns. A function
//! leaves a value in the return register whether or not it means one, so
//! its own body cannot tell a `void` function that last computed into that
//! register from one that returns it; its callers can. A call's result is
//! read when some path from the call reads the register before writing it.
//! A path that reaches the caller's own return passes the result on, which
//! reads it only when the caller returns a value in turn. An assignment used
//! only by the return, or a constant, is evidence of a result even when the
//! known callers discard it.

use std::collections::{HashMap, HashSet};

use vlk_arch::arch::RETURN;
use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Expr, Stmt};
use vlk_loader::loader::{Image, NameSource};
use vlk_program::program::Program;

/// Whether the function at `addr` has direct callers, none of them reads
/// its result, and it has no explicit result.
pub(crate) fn ignored_by_callers(program: &Program, addr: u64) -> bool {
    let Some(blocks) = body(program, addr) else {
        return false;
    };
    if returns_value(&blocks) || callers(program, addr).is_empty() {
        return false;
    }
    !reads(program, addr, &mut HashSet::new()).0
}

/// How many integer results past the first the function returns, as its
/// callers read them: the furthest result register some path from a call
/// reads before writing it counts with every one before it. Only for Go,
/// whose functions return several values in registers and whose callers
/// take them at once.
pub(crate) fn further_results(program: &Program, addr: u64) -> usize {
    further(program, addr, PASSED_ON)
}

/// How many callers in a row are followed where each returns the results
/// of the one it calls.
const PASSED_ON: u8 = 2;

/// The integer registers the Go method at `addr` returns in, where the
/// method table of its type tells.
pub(crate) fn method_results(image: &Image, addr: u64) -> Option<usize> {
    if !image.go {
        return None;
    }
    image
        .go_types
        .get_or_init(|| vlk_loader::loader::go::types::read(image))
        .methods
        .get(&addr)
        .copied()
        .flatten()
}

/// `further_results`, following `passes` callers that return the results.
fn further(program: &Program, addr: u64, passes: u8) -> usize {
    let image = &program.image;
    if let Some(results) = method_results(image, addr) {
        return results.saturating_sub(1);
    }
    let known = program
        .further_results
        .lock()
        .expect("result lock")
        .get(&(addr, passes))
        .copied();
    if let Some(known) = known {
        return known;
    }
    let (found, returned) = read_further_results(program, addr, passes);
    let mut cache = program.further_results.lock().expect("result lock");
    cache.insert((addr, passes), found);
    // With no caller returning them, following more of them finds the same.
    if !returned {
        for passes in 0..=PASSED_ON {
            cache.insert((addr, passes), found);
        }
    }
    found
}

/// The values the Go functions `ir` calls directly return, for those that
/// return more than one: a function returns as many as its callers read.
/// The functions `ir` calls directly that return a float, with its type.
/// A function of the image with a known prototype is left to that.
pub(crate) fn callee_float_returns(
    program: &Program,
    ir: &vlk_ir::ir::FunctionIr,
) -> std::collections::BTreeMap<u64, vlk_types::types::CType> {
    let image = &program.image;
    let mut found = std::collections::BTreeMap::new();
    if image.go {
        return found;
    }
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        let vlk_ir::ir::Stmt::Call {
            target: Some(target),
            through: None,
            ..
        } = stmt
        else {
            continue;
        };
        if found.contains_key(target) || !image.functions.contains_key(target) {
            continue;
        }
        let name = match super::summary::summary(program, *target).float_return {
            4 => "float",
            8 => "double",
            _ => continue,
        };
        found.insert(*target, vlk_types::types::CType::Named(name.to_owned()));
    }
    found
}

pub(crate) fn callee_results(
    program: &Program,
    ir: &vlk_ir::ir::FunctionIr,
) -> std::collections::BTreeMap<u64, usize> {
    let image = &program.image;
    let mut found = std::collections::BTreeMap::new();
    if !vlk_types::types::Convention::of(image.isa, image.format, image.go).several_results() {
        return found;
    }
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        if let Stmt::Call {
            target: Some(target),
            through: None,
            ..
        } = stmt
            && !found.contains_key(target)
        {
            let further = further_results(program, *target);
            if further > 0 {
                found.insert(*target, further + 1);
            }
        }
    }
    found
}

/// How many of the first `results` every path from the entry of `blocks`
/// writes before it returns, the first `taken` counting as written from
/// the start. A call writes them all.
fn set_before_returning(blocks: &[Block], results: &[u16], taken: usize) -> usize {
    let all = (1u32 << results.len()) - 1;
    let edges = vlk_ir::ir::cfg::all_edges(blocks, &[]);
    // What each block writes, and what is written where it returns.
    let mut written = vec![0u32; blocks.len()];
    for (index, block) in blocks.iter().enumerate() {
        for stmt in &block.stmts {
            if matches!(stmt, Stmt::Ret { .. }) {
                break;
            }
            if matches!(stmt, Stmt::Call { convention, .. }
                if *convention != vlk_types::types::Convention::GoWriteBarrier)
            {
                written[index] = all;
                continue;
            }
            let registers = vlk_ir::ir::visit::statement_registers(stmt).0;
            for (position, register) in results.iter().enumerate() {
                if registers.contains(register) {
                    written[index] |= 1 << position;
                }
            }
        }
    }
    // What is written on every path to the start of each block.
    let mut entered = vec![all; blocks.len()];
    if let Some(first) = entered.first_mut() {
        *first = all & ((1u32 << taken.min(31)) - 1);
    }
    loop {
        let mut changed = false;
        for index in 0..blocks.len() {
            let left = entered[index] | written[index];
            for &next in &edges[index].normal {
                let met = entered[next] & left;
                if next != 0 && met != entered[next] {
                    entered[next] = met;
                    changed = true;
                }
            }
        }
        if !changed {
            break;
        }
    }
    let mut set = all;
    for (index, block) in blocks.iter().enumerate() {
        if block
            .stmts
            .iter()
            .any(|stmt| matches!(stmt, Stmt::Ret { .. }))
        {
            set &= entered[index] | written[index];
        }
    }
    (!set).trailing_zeros() as usize
}

/// Whether the function is one the Go toolchain names as written for the
/// assembly ABI, which passes nothing in registers.
fn assembly(image: &Image, addr: u64) -> bool {
    image
        .functions
        .get(&addr)
        .and_then(|function| function.name.as_deref())
        .is_some_and(|name| name.ends_with(".abi0"))
}

/// Whether what the function returns is known without its callers: from
/// debug information that gives a type it can name, from the prototype of a library function it is
/// named after, or because it only jumps on to such a function.
fn declared(image: &Image, addr: u64) -> bool {
    let Some(function) = image.functions.get(&addr) else {
        return true;
    };
    function
        .sources
        .contains(&vlk_loader::loader::NameSource::Plt)
        || vlk_loader::loader::dwarf::function_types(image, addr)
            .is_some_and(|types| types.ret.is_some())
        || function
            .name
            .as_deref()
            .is_some_and(|name| vlk_prototypes::prototypes::for_image(name, image).is_some())
}

/// The result registers past the first that the function may return a
/// value in. A register the function returns with unchanged is no result
/// of it, unless it is an argument, which it may return as it got it.
fn further_result_registers(
    convention: vlk_types::types::Convention,
    summary: &vlk_loader::loader::Summary,
) -> Vec<u16> {
    let go = convention.go_registers();
    convention
        .results()
        .iter()
        .copied()
        .take_while(|register| !convention.float_arguments().contains(register))
        .enumerate()
        .take_while(|(position, register)| {
            summary
                .clobbers
                .is_none_or(|clobbers| clobbers.contains(*register))
                || (go && summary.arity.is_some_and(|arity| *position < arity))
        })
        .map(|(_, register)| register)
        .skip(1)
        .collect()
}

/// What the callers of one function read of its results past the first.
struct ResultReads<'a> {
    program: &'a Program,
    /// The result registers past the first, in order.
    results: &'a [u16],
    /// Whether a caller that returns with results unread passes them on
    /// to its own callers.
    passed_on: bool,
    /// How many callers in a row are still followed through such returns.
    passes: u8,
    /// How many of `results` some caller reads.
    furthest: usize,
    /// Whether some caller returns with results still unread.
    returned: bool,
}

impl ResultReads<'_> {
    /// Follows the paths in `caller` from statement `from` of block
    /// `first`, just after a call, to the reads of the results the call
    /// left.
    fn follow(
        &mut self,
        caller: u64,
        blocks: &[Block],
        edges: &[vlk_ir::ir::cfg::BlockSuccessors],
        first: usize,
        from: usize,
    ) {
        let all = (1u32 << self.results.len()) - 1;
        // Go keeps no value in a register over a call, so what a
        // path from this one reads before anything writes it is
        // what the callee left there.
        let mut reached: HashMap<usize, u32> = HashMap::new();
        let mut work = vec![(first, from, all)];
        while let Some((index, from, mut pending)) = work.pop() {
            for stmt in &blocks[index].stmts[from..] {
                // A write barrier reads none of them and writes
                // only where it leaves its buffer.
                let barrier = matches!(
                    stmt,
                    Stmt::Call {
                        convention: vlk_types::types::Convention::GoWriteBarrier,
                        ..
                    }
                );
                // Another call writes them all; a return passes
                // on the ones the caller returns in turn. What a
                // callee without such a list takes as arguments
                // is not counted: the number is an estimate.
                // A callee whose arguments Go lists takes what it
                // is passed from these registers.
                if let Stmt::Call {
                    target: Some(callee),
                    through: None,
                    convention,
                    ..
                } = stmt
                    && convention.go_registers()
                    && vlk_loader::loader::go::argument_registers(&self.program.image, *callee)
                        .is_some()
                    && let Some(taken) = super::summary::summary(self.program, *callee).arity
                {
                    for (position, register) in self.results.iter().enumerate() {
                        if pending & (1 << position) != 0
                            && convention.arguments()[..taken.min(convention.arguments().len())]
                                .contains(register)
                        {
                            self.furthest = self.furthest.max(position + 1);
                        }
                    }
                }
                let passed = match stmt {
                    Stmt::Call { .. } if barrier => None,
                    Stmt::Call { .. } | Stmt::Unsupported { .. } => Some(0),
                    Stmt::Ret { .. } if !self.passed_on => Some(0),
                    Stmt::Ret { .. } => {
                        self.returned = true;
                        match self.passes.checked_sub(1) {
                            Some(passes) => Some(further(self.program, caller, passes) + 1),
                            None => Some(0),
                        }
                    }
                    _ => None,
                };
                if let Some(passed) = passed {
                    for position in 0..self.results.len() {
                        if pending & (1 << position) != 0 && position + 1 < passed {
                            self.furthest = self.furthest.max(position + 1);
                        }
                    }
                    pending = 0;
                    break;
                }
                let mut read = HashSet::new();
                if !barrier {
                    for operand in stmt.operands() {
                        value_reads(operand, &mut read);
                    }
                }
                // Writing part of a register keeps bits nobody
                // reads; so does a bit scan, which leaves it as
                // it was only where the code makes no use of it.
                if let Stmt::Assign { dest, value, .. } = stmt
                    && (partial_write_of(value, dest.index)
                        || super::signature::scan_source(value, dest.index).is_some())
                {
                    read.remove(&dest.index);
                }
                let written = vlk_ir::ir::visit::statement_registers(stmt).0;
                for (position, register) in self.results.iter().enumerate() {
                    if pending & (1 << position) == 0 {
                        continue;
                    }
                    if read.contains(register) {
                        self.furthest = self.furthest.max(position + 1);
                        pending &= !(1 << position);
                    } else if written.contains(register) {
                        pending &= !(1 << position);
                    }
                }
                if pending == 0 {
                    break;
                }
            }
            // The ones up to the furthest found add nothing.
            pending &= !((1u32 << self.furthest) - 1);
            if pending == 0 {
                continue;
            }
            for &next in &edges[index].normal {
                let seen = reached.entry(next).or_default();
                let fresh = pending & !*seen;
                if fresh != 0 {
                    *seen |= fresh;
                    work.push((next, 0, fresh));
                }
            }
        }
    }
}

/// The count, and whether some caller returns with results still unread.
fn read_further_results(program: &Program, addr: u64, passes: u8) -> (usize, bool) {
    let image = &program.image;
    let convention = vlk_types::types::Convention::of(image.isa, image.format, image.go);
    if !convention.several_results() {
        return (0, false);
    }
    let go = convention.go_registers();
    let summary = super::summary::summary(program, addr);
    if summary.noreturn || assembly(image, addr) {
        return (0, false);
    }
    let results = further_result_registers(convention, &summary);
    if results.is_empty() {
        return (0, false);
    }
    // No more than it sets itself or takes as arguments, which it may
    // return as it got them: what else it returns with as it was on entry
    // is no result of its own.
    let Some(own) = body(program, addr) else {
        return (0, false);
    };
    // Elsewhere the second register is no argument register of the same
    // position, and a function may leave it unset where the value it
    // returns has no second word, as an absent slice has none: there a
    // caller reading it tells enough.
    let taken = if go {
        summary.arity.map_or(0, |arity| arity.saturating_sub(1))
    } else {
        0
    };
    let set = set_before_returning(&own, &results, taken);
    // A caller that returns without reading it tells less: there the
    // function has to set the register itself, on every path.
    let passed_on = go || set >= results.len();
    let results = if go {
        &results[..set.min(results.len())]
    } else {
        &results[..]
    };
    if results.is_empty() {
        return (0, false);
    }
    let mut search = ResultReads {
        program,
        results,
        passed_on,
        passes,
        furthest: 0,
        returned: false,
    };
    for caller in callers(program, addr) {
        let Some(blocks) = body(program, caller) else {
            continue;
        };
        let edges = vlk_ir::ir::cfg::all_edges(&blocks, &[]);
        for (first, block) in blocks.iter().enumerate() {
            for (at, stmt) in block.stmts.iter().enumerate() {
                if matches!(stmt, Stmt::Call { target: Some(target), convention, .. }
                    if *target == addr && convention.several_results())
                {
                    search.follow(caller, &blocks, &edges, first, at + 1);
                }
            }
        }
    }
    let (furthest, returned) = (search.furthest, search.returned);
    // Looked up last: few functions get this far.
    if furthest > 0 && !go && declared(image, addr) {
        return (0, returned);
    }
    (furthest, returned)
}

/// The registers whose values `expr` depends on: a register compared with
/// or subtracted from itself, as `sbb` of a register and itself does to
/// spread the carry, is none.
fn value_reads(expr: &Expr, into: &mut HashSet<u16>) {
    match expr {
        Expr::Reg { index, .. } => {
            into.insert(*index);
        }
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } if lhs == rhs => {
            value_reads(then, into);
            value_reads(els, into);
        }
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Sub | vlk_ir::ir::BinOp::Xor,
            lhs,
            rhs,
        } if lhs == rhs => {}
        _ => {
            for child in vlk_ir::ir::visit::children(expr) {
                value_reads(child, into);
            }
        }
    }
}

/// Whether `value` is `(register & mask) | x` with `x` free of the register:
/// a write of part of it.
fn partial_write_of(value: &Expr, register: u16) -> bool {
    let Expr::Bin {
        op: vlk_ir::ir::BinOp::Or,
        lhs,
        rhs,
    } = value
    else {
        return false;
    };
    let kept = matches!(lhs.as_ref(), Expr::Bin {
        op: vlk_ir::ir::BinOp::And,
        lhs: inner,
        rhs: mask,
    } if matches!(inner.as_ref(), Expr::Reg { index, .. } if *index == register)
        && matches!(mask.as_ref(), Expr::Const(_)));
    let mut rest = HashSet::new();
    vlk_ir::ir::visit::collect_reads(rhs, &mut rest);
    kept && !rest.contains(&register)
}

/// Whether some path returns with the return register as the caller left
/// it, as a function that returns nothing does when no call or assignment
/// on the way sets it. Only for conventions that pass no argument there.
pub(crate) fn returns_unset(blocks: &[Block], convention: vlk_types::types::Convention) -> bool {
    if convention.arguments().contains(&RETURN) || blocks.is_empty() {
        return false;
    }
    let index: HashMap<u64, usize> = blocks
        .iter()
        .enumerate()
        .map(|(position, block)| (block.start, position))
        .collect();
    // Whether the register may still be unset as each block starts.
    let mut unset = vec![false; blocks.len()];
    unset[0] = true;
    let mut pending = vec![0];
    while let Some(at) = pending.pop() {
        let mut still = true;
        for stmt in &blocks[at].stmts {
            if let Stmt::Ret { .. } = stmt {
                return true;
            }
            if vlk_ir::ir::visit::statement_registers(stmt)
                .0
                .contains(&RETURN)
            {
                still = false;
                break;
            }
        }
        if !still {
            continue;
        }
        let falls = at + 1;
        let next: Vec<usize> = match blocks[at].stmts.last() {
            Some(Stmt::Br {
                target: Some(target),
                ..
            }) => index.get(target).copied().into_iter().collect(),
            Some(Stmt::Brif { target, .. } | Stmt::BrifFlags { target, .. }) => index
                .get(target)
                .copied()
                .into_iter()
                .chain(std::iter::once(falls))
                .collect(),
            Some(Stmt::Switch { cases, default, .. }) => cases
                .iter()
                .map(|(_, target)| target)
                .chain(default)
                .filter_map(|target| index.get(target).copied())
                .collect(),
            Some(Stmt::Trap { .. } | Stmt::BrIndirect { .. } | Stmt::Br { target: None, .. }) => {
                Vec::new()
            }
            _ => vec![falls],
        };
        for successor in next {
            if successor < blocks.len() && !std::mem::replace(&mut unset[successor], true) {
                pending.push(successor);
            }
        }
    }
    false
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Fate {
    /// Every path writes the register first, or ends in a trap.
    Unused,
    /// Some path reaches the caller's return with it.
    Returned,
    Read,
}

/// The body without its callees' summaries, which would take lifting
/// everything they reach: a call then names no arguments.
#[expect(
    clippy::rc_buffer,
    reason = "Shared blocks retain Vec ownership so an unshared lift can be taken without cloning its blocks."
)]
fn body(program: &Program, addr: u64) -> Option<std::sync::Arc<Vec<Block>>> {
    let image = &program.image;
    let Some(value) = image.functions.get(&addr) else {
        return None;
    };
    if value.sources.contains(&NameSource::Plt) {
        return None;
    }
    super::summary::body(program, addr, &|_| vlk_loader::loader::Summary::default())
}

/// Whether some caller of `addr` reads its result, and whether the answer
/// leaned on a function still being decided, which `active` holds; such an
/// answer is not kept.
fn reads(program: &Program, addr: u64, active: &mut HashSet<u64>) -> (bool, bool) {
    if let Some(known) = program.result_reads.lock().expect("result lock").get(&addr) {
        return (*known, false);
    }
    // A cycle of calls passing the result on reads it only if something
    // outside the cycle does.
    if !active.insert(addr) {
        return (false, true);
    }
    let mut provisional = false;
    let mut read = false;
    for caller in callers(program, addr) {
        let Some(blocks) = body(program, caller) else {
            read = true;
            break;
        };
        let mut returned = false;
        for (index, block) in blocks.iter().enumerate() {
            for (position, stmt) in block.stmts.iter().enumerate() {
                if let Stmt::Call {
                    target: Some(target),
                    ..
                } = stmt
                    && *target == addr
                {
                    match fate(&blocks, index, position + 1, &mut HashMap::new()) {
                        Fate::Read => read = true,
                        Fate::Returned => returned = true,
                        Fate::Unused => {}
                    }
                }
            }
        }
        if read {
            break;
        }
        // A result passed on to the caller's return is read when the caller
        // returns a value: an explicit assignment, one its own callers read,
        // or, without callers, any value its body leaves in the register.
        if returned {
            let returns_value = if returns_value(&blocks) {
                true
            } else if callers(program, caller).is_empty() {
                writes_result(&blocks)
            } else {
                let (value, leaned) = reads(program, caller, active);
                provisional |= leaned;
                value
            };
            if returns_value {
                read = true;
                break;
            }
        }
    }
    active.remove(&addr);
    if read || !provisional {
        program
            .result_reads
            .lock()
            .expect("result lock")
            .insert(addr, read);
    }
    (read, provisional && !read)
}

/// The functions with a direct call or jump to `addr`.
pub fn callers(program: &Program, addr: u64) -> Vec<u64> {
    let image = &program.image;
    let index = program.branches_to.get_or_init(|| branches(image));
    let mut out: Vec<u64> = index
        .get(&addr)
        .into_iter()
        .flatten()
        .filter_map(|site| {
            let Some((start, function)) = image.functions.range(..=*site).next_back() else {
                return None;
            };
            let size = function.size.unwrap_or(super::UNKNOWN_SIZE);
            (*site < start.saturating_add(size)).then_some(*start)
        })
        .filter(|caller| *caller != addr)
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

/// Every direct call and jump in the executable sections, by target, and
/// those the object's relocations name.
fn branches(image: &Image) -> HashMap<u64, Vec<u64>> {
    let mut out: HashMap<u64, Vec<u64>> = HashMap::new();
    for section in image.sections.iter().filter(|section| section.executable) {
        let Some(bytes) = image.read_vaddr(section.vaddr, section.size) else {
            continue;
        };
        match image.isa {
            Isa::I386 | Isa::X86_64 => {
                for at in 0..bytes.len().saturating_sub(4) {
                    // A call or jump through a slot the linker fills
                    // with the address of a function.
                    if image.isa == Isa::X86_64
                        && bytes[at] == 0xff
                        && matches!(bytes[at + 1], 0x15 | 0x25)
                        && let Some(displacement) = bytes.get(at + 2..at + 6)
                    {
                        let displacement =
                            i32::from_le_bytes(displacement.try_into().expect("four bytes"));
                        let site = section.vaddr + at as u64;
                        let slot = site
                            .wrapping_add(6)
                            .wrapping_add(displacement as i64 as u64);
                        if let Some(vlk_loader::loader::Pointer::Address(target)) =
                            image.read_pointer(slot)
                            && image.functions.contains_key(&target)
                        {
                            out.entry(target).or_default().push(site);
                        }
                        continue;
                    }
                    if !matches!(bytes[at], 0xe8 | 0xe9) {
                        continue;
                    }
                    let displacement =
                        i32::from_le_bytes(bytes[at + 1..at + 5].try_into().expect("four bytes"));
                    let site = section.vaddr + at as u64;
                    let target = site
                        .wrapping_add(5)
                        .wrapping_add(displacement as i64 as u64);
                    out.entry(target).or_default().push(site);
                }
            }
            Isa::AArch64 => {
                for (word, chunk) in bytes.as_chunks::<4>().0.iter().enumerate() {
                    let instruction = u32::from_le_bytes(*chunk);
                    // B and BL.
                    if instruction & 0x7c00_0000 != 0x1400_0000 {
                        continue;
                    }
                    let offset = ((instruction << 6) as i32 >> 4) as i64;
                    let site = section.vaddr + word as u64 * 4;
                    out.entry(site.wrapping_add(offset as u64))
                        .or_default()
                        .push(site);
                }
            }
            Isa::RiscV64 => {
                for (site, target) in crate::lift::riscv64::direct_transfers(bytes, section.vaddr) {
                    out.entry(target).or_default().push(site);
                }
            }
            Isa::Mips32 => {
                for (site, target) in crate::lift::mips32::direct_transfers(
                    bytes,
                    section.vaddr,
                    image.byte_order() == Some(object::Endianness::Big),
                ) {
                    out.entry(target).or_default().push(site);
                }
            }
            Isa::Arm32 | Isa::Unsupported => {}
        }
    }
    for (site, target) in &image.relocations {
        out.entry(*target).or_default().push(*site);
    }
    out
}

/// Whether some path writes the return register, as any value-returning
/// body does.
fn writes_result(blocks: &[Block]) -> bool {
    blocks.iter().flat_map(|block| &block.stmts).any(|stmt| {
        matches!(stmt, Stmt::Assign { dest, .. } if dest.index == RETURN)
            || matches!(stmt, Stmt::Call { .. })
    })
}

/// Whether a path returns a constant or assigns a value used only by its
/// return. Known callers may discard a result even though others can use it.
fn returns_value(blocks: &[Block]) -> bool {
    let mut predecessors = vec![Vec::new(); blocks.len()];
    let mut pending = Vec::new();
    for (index, block) in blocks.iter().enumerate() {
        if matches!(block.stmts.last(), Some(Stmt::Ret { .. })) {
            pending.push((index, false));
        }
        for next in vlk_ir::ir::cfg::block_successors(blocks, index) {
            predecessors[next].push(index);
        }
    }
    let mut seen = HashSet::new();
    while let Some((index, mut used)) = pending.pop() {
        if !seen.insert((index, used)) {
            continue;
        }
        let mut defined = false;
        for stmt in blocks[index].stmts.iter().rev() {
            if matches!(stmt, Stmt::Ret { .. }) {
                continue;
            }
            let (written, read) = vlk_ir::ir::visit::statement_registers(stmt);
            if written.contains(&RETURN) {
                if matches!(stmt, Stmt::Assign { value, .. }
                    if !used || matches!(value, Expr::Const(_)))
                {
                    return true;
                }
                defined = true;
                break;
            }
            used |= read.contains(&RETURN);
        }
        if !defined {
            for previous in &predecessors[index] {
                pending.push((*previous, used));
            }
        }
    }
    false
}

/// What becomes of the return register from statement `position` of block
/// `index` on.
fn fate(blocks: &[Block], index: usize, position: usize, memo: &mut HashMap<usize, Fate>) -> Fate {
    for stmt in &blocks[index].stmts[position..] {
        if let Some(fate) = event(stmt) {
            return fate;
        }
    }
    let mut worst = Fate::Unused;
    for next in vlk_ir::ir::cfg::block_successors(blocks, index) {
        let fate = match memo.get(&next) {
            Some(fate) => *fate,
            None => {
                // A loop back to a block under way adds nothing new.
                memo.insert(next, Fate::Unused);
                let fate = fate(blocks, next, 0, memo);
                memo.insert(next, fate);
                fate
            }
        };
        worst = worst.max(fate);
    }
    // A block that ends without a successor runs into unknown code.
    if vlk_ir::ir::cfg::block_successors(blocks, index).is_empty()
        && !matches!(
            blocks[index].stmts.last(),
            Some(Stmt::Trap { .. } | Stmt::Ret { .. })
        )
    {
        return Fate::Read;
    }
    worst
}

/// The register a call passes its first integer argument in.
fn first_argument(stmt: &Stmt) -> u16 {
    match stmt {
        Stmt::Call { convention, .. } => {
            convention.arguments().first().copied().unwrap_or(u16::MAX)
        }
        _ => u16::MAX,
    }
}

/// What `stmt` does with the return register, if it decides its fate.
fn event(stmt: &Stmt) -> Option<Fate> {
    let reads = |expr: &Expr| {
        let mut read = std::collections::HashSet::new();
        vlk_ir::ir::visit::collect_reads(expr, &mut read);
        read.contains(&RETURN)
    };
    match stmt {
        Stmt::Assign { dest, value, .. } if dest.index == RETURN => {
            // A write of the low bits keeps the rest without reading it.
            if let Expr::Bin { lhs, rhs, .. } = value
                && let Expr::Bin { lhs: kept, .. } = lhs.as_ref()
                && matches!(kept.as_ref(), Expr::Reg { index, .. } if *index == RETURN)
            {
                return reads(rhs).then_some(Fate::Read);
            }
            Some(if reads(value) {
                Fate::Read
            } else {
                Fate::Unused
            })
        }
        Stmt::Ret { .. } => Some(Fate::Returned),
        Stmt::Trap { .. } => Some(Fate::Unused),
        Stmt::Unsupported { .. } => Some(Fate::Read),
        // A call whose arguments are unknown may take the result as one,
        // where the return register is also the first argument.
        Stmt::Call { args: None, .. } if RETURN == first_argument(stmt) => Some(Fate::Read),
        Stmt::Call { .. } => {
            let (written, read) = vlk_ir::ir::visit::statement_registers(stmt);
            if read.contains(&RETURN) {
                Some(Fate::Read)
            } else if written.contains(&RETURN) {
                Some(Fate::Unused)
            } else {
                None
            }
        }
        other => other
            .operands()
            .into_iter()
            .any(reads)
            .then_some(Fate::Read),
    }
}

#[cfg(test)]
mod tests;