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
mod checked;
mod i386;
pub use checked::checked_frame_slot;
pub(crate) use i386::settle_i386;

use std::collections::HashMap;
use vlk_arch::arch::stack_pointer;

use crate::passes::{copies, frame};
use vlk_ir::ir::{BinOp, Expr, FunctionIr, Stmt};
use vlk_types::types::EntryAlignment;

/// What a frame displacement is followed with: the stack pointer, what is
/// known of it on entry, and whether addresses are 32 bits wide.
#[derive(Debug, Clone, Copy)]
pub struct Stack {
    pub(crate) sp: u16,
    alignment: Option<EntryAlignment>,
    narrow: bool,
}

/// What a write of the stack pointer does to the frame displacement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
    /// It moves the stack pointer to this displacement.
    Moves(i64),
    /// It moves the stack pointer by an amount the entry alignment does not
    /// fix, such as a mask finer than what is known.
    Unknown,
    /// It sets the stack pointer from something other than itself.
    Other,
}

impl Stack {
    pub(crate) fn of(ir: &FunctionIr) -> Self {
        Self::at(ir, stack_pointer(ir.isa))
    }

    /// The same for a function whose stack pointer is followed as `sp`.
    pub fn at(ir: &FunctionIr, sp: u16) -> Self {
        Self {
            sp,
            alignment: ir.entry_alignment,
            narrow: vlk_arch::arch::pointer_bytes(ir.isa) == 4,
        }
    }

    /// What `sp = value` does at displacement `frame`. Rounding the stack
    /// pointer down to a multiple of 2^k moves it by what the entry
    /// alignment says the multiple is off by, when it says that much.
    pub fn step(self, frame: i64, value: &Expr) -> Step {
        let Expr::Bin { op, lhs, rhs } = value else {
            return Step::Other;
        };
        let (Expr::Reg { index, .. }, Expr::Const(constant)) = (lhs.as_ref(), rhs.as_ref()) else {
            return Step::Other;
        };
        if *index != self.sp {
            return Step::Other;
        }
        match op {
            BinOp::Add => Step::Moves(frame.wrapping_add(*constant as i64)),
            BinOp::Sub => Step::Moves(frame.wrapping_sub(*constant as i64)),
            BinOp::And => {
                // A 32-bit address keeps its value under a mask that clears
                // only the high half.
                let mask = if self.narrow {
                    *constant | 0xffff_ffff_0000_0000
                } else {
                    *constant
                };
                let low = !mask;
                match self.alignment {
                    Some(EntryAlignment { residue, modulus })
                        if low != u64::MAX
                            && (low + 1).is_power_of_two()
                            && modulus.is_multiple_of(low + 1) =>
                    {
                        let off = residue.wrapping_add(frame as u64) & low;
                        Step::Moves(frame.wrapping_sub(off as i64))
                    }
                    _ => Step::Unknown,
                }
            }
            _ => Step::Unknown,
        }
    }
}

/// Rewrites every stack access against the entry frame and drops the
/// adjustments, when the stack pointer is only ever a frame base.
pub fn settle(ir: &mut FunctionIr) {
    crate::passes::checked("passes::frame_slots::settle", ir, settle_unchecked)
}

fn settle_unchecked(ir: &mut FunctionIr) {
    if vlk_arch::arch::pointer_bytes(ir.isa) == 4 {
        settle_i386(ir);
    }
    // A declared call reads the stack pointer as it stands at the call.
    if ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(Stmt::has_declared_call)
    {
        return;
    }
    let frames = block_entry_frame_offsets(ir, stack_pointer(ir.isa));
    if substitute_frame_pointer(ir, &frames) {
        crate::passes::simplify::simplify(ir);
        frame::elide_callee_saves(ir);
    }
    let frames = block_entry_frame_offsets(ir, stack_pointer(ir.isa));
    if !canonical_frame(ir, &frames) {
        return;
    }
    let escapes = address_escapes(ir, &frames);
    rewrite_frame(ir, &frames);
    // Code that has a slot's address may read or write it unseen.
    if !escapes {
        frame::drop_dead_frame_stores(ir);
        copies::inline_local_copies(ir);
    }
    crate::passes::simplify::simplify(ir);
}

/// Whether a frame slot's address is used as a value, beyond the address of
/// a load or store, so the code may reach the slot through a pointer.
fn address_escapes(ir: &FunctionIr, frames: &[Option<i64>]) -> bool {
    let stack = Stack::of(ir);
    let sp = stack.sp;
    fn escapes(expr: &Expr, frame: i64, sp: u16) -> bool {
        if frame_slot(expr, frame, sp).is_some() {
            return true;
        }
        match expr {
            Expr::Load { addr, .. } if frame_slot(addr, frame, sp).is_some() => false,
            _ => vlk_ir::ir::visit::children(expr)
                .into_iter()
                .any(|child| escapes(child, frame, sp)),
        }
    }
    for (position, block) in ir.blocks.iter().enumerate() {
        let Some(mut frame) = frames[position] else {
            continue;
        };
        for stmt in &block.stmts {
            if let Stmt::Assign { dest, value, .. } = stmt
                && dest.index == sp
            {
                if let Step::Moves(next) = stack.step(frame, value) {
                    frame = next;
                }
                continue;
            }
            let operands: Vec<&Expr> = match stmt {
                // The address a store writes is no escape; what it stores may be.
                Stmt::Store { addr, value, .. } => {
                    if frame_slot(addr, frame, sp).is_some() {
                        vec![value]
                    } else {
                        vec![addr, value]
                    }
                }
                other => other.operands(),
            };
            if operands.into_iter().any(|expr| escapes(expr, frame, sp)) {
                return true;
            }
        }
    }
    false
}

/// Rewrites the reads of a frame pointer that the entry block sets once from
/// the stack pointer as the stack addresses they are, so the frame settles
/// like one addressed through the stack pointer. Other writes may only
/// restore the caller's value on the way out. Returns whether it rewrote.
fn substitute_frame_pointer(ir: &mut FunctionIr, frames: &[Option<i64>]) -> bool {
    let stack = Stack::of(ir);
    let sp = stack.sp;
    let fp = if ir.isa == vlk_base::target::Isa::Arm32
        && ir.blocks.iter().flat_map(|block| &block.stmts).any(|stmt| {
            matches!(stmt, Stmt::Assign { dest, value, .. } if dest.index == 7 && frame_slot(value, 0, sp).is_some())
        }) {
        7
    } else {
        vlk_arch::arch::frame_pointer(ir.isa)
    };
    fn adjustment(stmt: &Stmt, fp: u16) -> Option<i64> {
        let Stmt::Assign { dest, value, .. } = stmt else {
            return None;
        };
        if dest.index != fp {
            return None;
        }
        let value = match value {
            Expr::Bin {
                op: BinOp::And,
                lhs,
                rhs,
            } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => lhs.as_ref(),
            other => other,
        };
        let Expr::Bin { op, lhs, rhs } = value else {
            return None;
        };
        let (Expr::Reg { index, .. }, Expr::Const(delta)) = (lhs.as_ref(), rhs.as_ref()) else {
            return None;
        };
        if *index != fp {
            return None;
        }
        match op {
            BinOp::Add => Some(*delta as i64),
            BinOp::Sub => (*delta as i64).checked_neg(),
            _ => None,
        }
    }
    // The setup, its block, and the entry-frame offset it gives the frame
    // pointer: in the entry block, or later where the prologue waits past
    // an early return.
    let mut setup = None;
    'find: for (index, block) in ir.blocks.iter().enumerate() {
        let Some(mut frame) = frames[index] else {
            continue;
        };
        for (position, stmt) in block.stmts.iter().enumerate() {
            match stmt {
                Stmt::Assign { dest, value, .. } if dest.index == fp => {
                    if let Some(base) = frame_slot(value, frame, sp) {
                        setup = Some((index, position, base));
                        break 'find;
                    }
                }
                Stmt::Assign { dest, value, .. } if dest.index == sp => {
                    match stack.step(frame, value) {
                        Step::Moves(next) => frame = next,
                        Step::Unknown => continue 'find,
                        Step::Other => {}
                    }
                }
                _ => {}
            }
        }
    }
    let Some((setup_block, setup_position, base)) = setup else {
        return false;
    };
    // The frame pointer means the frame only in the blocks the setup
    // dominates; elsewhere it still holds the caller's. A landing pad holds
    // the frame pointer of the calls that unwind into it, which the unwinder
    // restores as it does every register the callee saves, so each call's
    // block leads to its landing pad here.
    let mut successors: Vec<Vec<usize>> = (0..ir.blocks.len())
        .map(|index| vlk_ir::ir::cfg::block_successors(&ir.blocks, index))
        .collect();
    let starts: HashMap<u64, usize> = ir
        .blocks
        .iter()
        .enumerate()
        .map(|(position, block)| (block.start, position))
        .collect();
    for (pad, sites) in &ir.landing_pads {
        let Some(&pad) = starts.get(pad) else {
            continue;
        };
        for (site, end) in sites {
            let call_block = ir
                .blocks
                .iter()
                .enumerate()
                .filter(|(_, block)| block.start <= *site)
                .max_by_key(|(_, block)| block.start);
            if let Some((call_block, _)) = call_block {
                successors[call_block].push(pad);
            }
            for (block_index, block) in ir.blocks.iter().enumerate() {
                if block.start > *site && block.start < *end {
                    successors[block_index].push(pad);
                }
            }
        }
    }
    let idom = crate::ssa::dom::dominators(&successors).idom;
    let count = ir.blocks.len();
    let dominated = |mut block: usize| {
        for _ in 0..=count {
            if block == setup_block {
                return true;
            }
            match idom[block] {
                Some(parent) if parent != block => block = parent,
                _ => return false,
            }
        }
        false
    };
    // Any other write restores the caller's frame pointer before a return.
    for (index, block) in ir.blocks.iter().enumerate() {
        for (position, stmt) in block.stmts.iter().enumerate() {
            if (index, position) == (setup_block, setup_position)
                || !vlk_ir::ir::visit::statement_registers(stmt).0.contains(&fp)
            {
                continue;
            }
            if matches!(block.stmts.last(), Some(Stmt::Ret { .. }))
                && adjustment(stmt, fp).is_some()
            {
                continue;
            }
            let restores = matches!(
                stmt,
                Stmt::Assign {
                    value: Expr::Load { .. },
                    ..
                }
            ) || matches!(stmt, Stmt::Assign { value: Expr::Bin { op: BinOp::And, lhs, rhs }, .. }
                if vlk_arch::arch::pointer_bytes(ir.isa) == 4
                    && matches!(lhs.as_ref(), Expr::Load { width: 4, signed: false, .. })
                    && matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
            );
            let restores = restores
                && matches!(block.stmts.last(), Some(Stmt::Ret { .. }))
                && block.stmts[position + 1..]
                    .iter()
                    .all(|later| !vlk_ir::ir::visit::statement_reads(later).contains(&fp));
            if !restores {
                return false;
            }
        }
    }
    if (0..ir.blocks.len()).any(|index| dominated(index) && frames[index].is_none()) {
        return false;
    }
    // The rewrite follows the displacement through each block it changes.
    for (index, block) in ir.blocks.iter().enumerate() {
        let Some(mut frame) = frames[index].filter(|_| dominated(index)) else {
            continue;
        };
        for stmt in &block.stmts {
            if let Stmt::Assign { dest, value, .. } = stmt
                && dest.index == sp
            {
                match stack.step(frame, value) {
                    Step::Moves(next) => frame = next,
                    Step::Unknown => return false,
                    Step::Other => {}
                }
            }
        }
    }
    for (index, block) in ir.blocks.iter_mut().enumerate() {
        if !dominated(index) {
            continue;
        }
        let Some(mut frame) = frames[index] else {
            return false;
        };
        let mut base = base;
        for (position, stmt) in block.stmts.iter_mut().enumerate() {
            let delta = adjustment(stmt, fp);
            // The save before the setup reads the caller's frame pointer.
            if index != setup_block || position > setup_position {
                let address = Expr::bin(
                    BinOp::Add,
                    Expr::reg(sp, 64),
                    Expr::Const(base.wrapping_sub(frame) as u64),
                );
                vlk_ir::ir::visit::replace_reads(stmt, &[(fp, address)]);
            }
            if let Some(delta) = delta {
                let Some(next) = base.checked_add(delta) else {
                    return false;
                };
                base = next;
            }
            if let Stmt::Assign { dest, value, .. } = stmt
                && dest.index == sp
                && let Step::Moves(next) = stack.step(frame, value)
            {
                frame = next;
            }
        }
    }
    ir.blocks[setup_block].stmts.remove(setup_position);
    true
}

/// True when every block has a known frame and the stack pointer is used only
/// as a frame-slot address and written only by adjustments.
pub(crate) fn canonical_frame(ir: &FunctionIr, frames: &[Option<i64>]) -> bool {
    let stack = Stack::of(ir);
    let sp = stack.sp;
    for (position, block) in ir.blocks.iter().enumerate() {
        let Some(mut frame) = frames[position] else {
            // Code no path reaches, such as padding, may stay as it is
            // unless it uses the stack pointer.
            let uses_sp = block.stmts.iter().any(|stmt| {
                let (writes, reads) = vlk_ir::ir::visit::statement_registers(stmt);
                writes.contains(&sp) || reads.contains(&sp)
            });
            if uses_sp {
                return false;
            }
            continue;
        };
        for stmt in &block.stmts {
            match stmt {
                // A store through any other pointer leaves the frame alone.
                Stmt::Store { addr, value, .. } => {
                    if !uses_stack_pointer_only_in_frame_addresses(addr, frame, sp)
                        || !uses_stack_pointer_only_in_frame_addresses(value, frame, sp)
                    {
                        return false;
                    }
                }
                Stmt::Assign { dest, value, .. } => {
                    if dest.index == sp {
                        match stack.step(frame, value) {
                            Step::Moves(next) => frame = next,
                            Step::Unknown | Step::Other => return false,
                        }
                        continue;
                    }
                    if !uses_stack_pointer_only_in_frame_addresses(value, frame, sp) {
                        return false;
                    }
                }
                Stmt::Brif { lhs, rhs, .. } => {
                    if !uses_stack_pointer_only_in_frame_addresses(lhs, frame, sp)
                        || !uses_stack_pointer_only_in_frame_addresses(rhs, frame, sp)
                    {
                        return false;
                    }
                }
                Stmt::Switch { index, .. } => {
                    if !uses_stack_pointer_only_in_frame_addresses(index, frame, sp) {
                        return false;
                    }
                }
                Stmt::BrIndirect { target, .. } => {
                    if !uses_stack_pointer_only_in_frame_addresses(target, frame, sp) {
                        return false;
                    }
                }
                Stmt::Ret { value, .. }
                    if !uses_stack_pointer_only_in_frame_addresses(value, frame, sp) =>
                {
                    return false;
                }
                Stmt::Machine { inputs, .. }
                    if inputs.iter().any(|expr| {
                        !uses_stack_pointer_only_in_frame_addresses(expr, frame, sp)
                    }) =>
                {
                    return false;
                }
                Stmt::Call { through, args, .. }
                    if through.iter().chain(args.iter().flatten()).any(|expr| {
                        !uses_stack_pointer_only_in_frame_addresses(expr, frame, sp)
                    }) =>
                {
                    return false;
                }
                _ => {}
            }
        }
    }
    true
}

/// True when the stack pointer appears only in frame-slot addresses or loads.
fn uses_stack_pointer_only_in_frame_addresses(expr: &Expr, frame: i64, sp: u16) -> bool {
    // A slot's address, such as a local array's, settles like its loads.
    if frame_slot(expr, frame, sp).is_some() {
        return true;
    }
    match expr {
        Expr::Reg { index, .. } => *index != sp,
        Expr::Const(_) => true,
        Expr::Bin { lhs, rhs, .. } => {
            uses_stack_pointer_only_in_frame_addresses(lhs, frame, sp)
                && uses_stack_pointer_only_in_frame_addresses(rhs, frame, sp)
        }
        Expr::Load { addr, .. } => match frame_slot(addr, frame, sp) {
            Some(_) => true,
            None => uses_stack_pointer_only_in_frame_addresses(addr, frame, sp),
        },
        Expr::SignExtend { value, .. } => {
            uses_stack_pointer_only_in_frame_addresses(value, frame, sp)
        }
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } => {
            uses_stack_pointer_only_in_frame_addresses(lhs, frame, sp)
                && uses_stack_pointer_only_in_frame_addresses(rhs, frame, sp)
                && uses_stack_pointer_only_in_frame_addresses(then, frame, sp)
                && uses_stack_pointer_only_in_frame_addresses(els, frame, sp)
        }
        Expr::Apply { args, .. } => args
            .iter()
            .all(|arg| uses_stack_pointer_only_in_frame_addresses(arg, frame, sp)),
    }
}

/// Rewrites frame-relative addresses against the entry frame and drops the
/// adjustments, so each slot has one address everywhere.
pub(crate) fn rewrite_frame(ir: &mut FunctionIr, frames: &[Option<i64>]) {
    let stack = Stack::of(ir);
    let sp = stack.sp;
    let mut bottom = ir.frame_bottom;
    for (position, block) in ir.blocks.iter_mut().enumerate() {
        let Some(mut frame) = frames[position] else {
            continue;
        };
        for stmt in &mut block.stmts {
            match stmt {
                Stmt::Store { addr, value, .. } => {
                    // Either a slot, or an address whose parts read slots.
                    rewrite_expr_frame(addr, frame, sp);
                    rewrite_expr_frame(value, frame, sp);
                }
                Stmt::Assign { dest, value, .. } => {
                    if dest.index == sp {
                        if let Step::Moves(next) = stack.step(frame, value) {
                            frame = next;
                            bottom = bottom.min(frame);
                        }
                        continue;
                    }
                    rewrite_expr_frame(value, frame, sp);
                }
                Stmt::Brif { lhs, rhs, .. } => {
                    rewrite_expr_frame(lhs, frame, sp);
                    rewrite_expr_frame(rhs, frame, sp);
                }
                Stmt::Switch { index: value, .. }
                | Stmt::BrIndirect { target: value, .. }
                | Stmt::Ret { value, .. } => rewrite_expr_frame(value, frame, sp),
                Stmt::Machine { inputs, .. } => {
                    for value in inputs {
                        rewrite_expr_frame(value, frame, sp);
                    }
                }
                Stmt::Call { through, args, .. } => {
                    for value in through.iter_mut().chain(args.iter_mut().flatten()) {
                        rewrite_expr_frame(value, frame, sp);
                    }
                }
                _ => {}
            }
        }
        // Drop the adjustments now that every access names its slot.
        block
            .stmts
            .retain(|stmt| !matches!(stmt, Stmt::Assign { dest, value, .. } if dest.index == sp && stack.step(0, value) != Step::Other));
    }
    ir.frame_bottom = bottom;
}

fn rewrite_expr_frame(expr: &mut Expr, frame: i64, sp: u16) {
    if !matches!(expr, Expr::Load { .. })
        && let Some(slot) = frame_slot(expr, frame, sp)
    {
        *expr = frame_address(sp, slot);
        return;
    }
    match expr {
        Expr::Load { addr, .. } => {
            if let Some(slot) = frame_slot(addr, frame, sp) {
                **addr = frame_address(sp, slot);
            } else {
                rewrite_expr_frame(addr, frame, sp);
            }
        }
        Expr::Bin { lhs, rhs, .. } => {
            rewrite_expr_frame(lhs, frame, sp);
            rewrite_expr_frame(rhs, frame, sp);
        }
        Expr::SignExtend { value, .. } => rewrite_expr_frame(value, frame, sp),
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } => {
            rewrite_expr_frame(lhs, frame, sp);
            rewrite_expr_frame(rhs, frame, sp);
            rewrite_expr_frame(then, frame, sp);
            rewrite_expr_frame(els, frame, sp);
        }
        Expr::Apply { args, .. } => {
            for arg in args {
                rewrite_expr_frame(arg, frame, sp);
            }
        }
        _ => {}
    }
}

fn frame_address(sp: u16, slot: i64) -> Expr {
    Expr::bin(
        BinOp::Add,
        Expr::Reg {
            index: sp,
            width: 64,
        },
        Expr::Const(slot as u64),
    )
}

/// The entry-frame offset of an address that is exactly `sp + k`, given the
/// frame displacement at that point.
pub fn frame_slot(expr: &Expr, frame: i64, sp: u16) -> Option<i64> {
    match expr {
        Expr::Bin {
            op: BinOp::Or,
            lhs,
            rhs,
        } if sp == vlk_arch::arch::aarch64::SP => {
            let (base, mask) = match (lhs.as_ref(), rhs.as_ref()) {
                (base, Expr::Const(mask)) | (Expr::Const(mask), base) if *mask < 16 => {
                    (base, *mask)
                }
                _ => return None,
            };
            // AAPCS64 aligns the entry stack pointer to sixteen bytes.
            frame_slot(base, frame, sp).map(|offset| offset | mask as i64)
        }
        Expr::Reg { index, .. } if *index == sp => Some(frame),
        Expr::Bin {
            op: BinOp::Add,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (base, Expr::Const(delta)) | (Expr::Const(delta), base) => {
                frame_slot(base, frame, sp).and_then(|offset| offset.checked_add(*delta as i64))
            }
            _ => None,
        },
        Expr::Bin {
            op: BinOp::Sub,
            lhs,
            rhs,
        } => match rhs.as_ref() {
            Expr::Const(delta) => {
                frame_slot(lhs, frame, sp).and_then(|offset| offset.checked_sub(*delta as i64))
            }
            _ => None,
        },
        _ => None,
    }
}

/// The frame displacement on entry to each block, propagated over the control
/// flow; `None` when unreachable or when paths disagree.
pub fn block_entry_frame_offsets(ir: &FunctionIr, sp: u16) -> Vec<Option<i64>> {
    let stack = Stack::at(ir, sp);
    let index: HashMap<u64, usize> = ir
        .blocks
        .iter()
        .enumerate()
        .map(|(position, block)| (block.start, position))
        .collect();
    let mut frames: Vec<Option<i64>> = vec![None; ir.blocks.len()];
    if frames.is_empty() {
        return frames;
    }
    frames[0] = Some(0);
    // A landing pad starts in the frame of the calls that unwind into it:
    // that of the block holding the first of them.
    let pads: Vec<(usize, usize)> = ir
        .landing_pads
        .iter()
        .filter_map(|(pad, sites)| {
            let Some(pad_index) = index.get(pad) else {
                return None;
            };
            let pad = *pad_index;
            let Some((site, _)) = sites.first() else {
                return None;
            };
            let Some(containing_block) = ir
                .blocks
                .iter()
                .enumerate()
                .filter(|(_, block)| block.start <= *site)
                .max_by_key(|(_, block)| block.start)
            else {
                return None;
            };
            let holder = containing_block.0;
            Some((pad, holder))
        })
        .collect();
    for _ in 0..ir.blocks.len().max(1) * 4 {
        let mut changed = false;
        for (pad, holder) in &pads {
            if frames[*pad].is_none()
                && let Some(frame) = frames[*holder]
            {
                frames[*pad] = Some(frame);
                changed = true;
            }
        }
        for position in 0..ir.blocks.len() {
            let Some(entry) = frames[position] else {
                continue;
            };
            let block = &ir.blocks[position];
            let mut exit = entry;
            for stmt in &block.stmts {
                if exit == i64::MIN {
                    break;
                }
                if let Stmt::Assign { dest, value, .. } = stmt
                    && dest.index == sp
                {
                    match stack.step(exit, value) {
                        Step::Moves(next) => exit = next,
                        Step::Unknown => exit = i64::MIN,
                        Step::Other => {}
                    }
                }
            }
            let mut successors: Vec<usize> = Vec::new();
            match block.stmts.last() {
                Some(Stmt::Brif { target, .. }) | Some(Stmt::BrifFlags { target, .. }) => {
                    if let Some(target) = index.get(target) {
                        successors.push(*target);
                    }
                    if position + 1 < ir.blocks.len() {
                        successors.push(position + 1);
                    }
                }
                Some(Stmt::Switch { cases, default, .. }) => {
                    for (_, target) in cases {
                        if let Some(target) = index.get(target) {
                            successors.push(*target);
                        }
                    }
                    if let Some(target) = default
                        && let Some(target) = index.get(target)
                    {
                        successors.push(*target);
                    }
                }
                Some(Stmt::Br {
                    target: Some(target),
                    ..
                }) => {
                    if let Some(target) = index.get(target) {
                        successors.push(*target);
                    }
                }
                Some(Stmt::Ret { .. })
                | Some(Stmt::BrIndirect { .. })
                | Some(Stmt::Trap { .. }) => {}
                _ => {
                    if position + 1 < ir.blocks.len() {
                        successors.push(position + 1);
                    }
                }
            }
            for successor in successors {
                match frames[successor] {
                    None => {
                        frames[successor] = Some(exit);
                        changed = true;
                    }
                    Some(existing) if existing != exit => {
                        // Paths disagree; `i64::MIN` marks the frame unknown.
                        frames[successor] = Some(i64::MIN);
                    }
                    Some(_) => {}
                }
            }
        }
        if !changed {
            break;
        }
    }
    frames
        .into_iter()
        .map(|frame| (frame != Some(i64::MIN)).then_some(frame).flatten())
        .collect()
}

#[cfg(test)]
mod tests;