analyssa 0.4.1

Target-agnostic SSA IR, analyses, and optimization pipeline
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
//! Block merging pass — eliminates trampoline blocks and coalesces
//! single-edge block pairs in the SSA CFG.
//!
//! # Transformations
//!
//! 1. **Trampoline elimination** — removes blocks containing only an
//!    unconditional jump by redirecting predecessors to the ultimate target.
//!    Phi operands that referenced the trampoline are updated to reference
//!    the correct predecessor.
//! 2. **Block coalescing** — merges a block into its sole predecessor when
//!    the predecessor's only successor is that block. Phi nodes in the
//!    successor are converted to `Copy` instructions because they have
//!    exactly one incoming edge.
//!
//! Entry block (B0) is handled specially: when it's a trampoline, the
//! target block is inlined into B0 (if safe — single predecessor, no phis)
//! or the method is marked for code regeneration.
//!
//! # Algorithm
//!
//! Phase 1 iterates at most `max_iterations` times, each pass identifying
//! trampolines (via [`SsaFunction::find_trampoline_blocks`]), redirecting
//! all predecessors through [`redirect_target`](SsaOp::redirect_target),
//! then clearing the trampolines.
//!
//! Phase 2 handles the entry block specially (it has no predecessor, so
//! phase 1 cannot redirect through it).
//!
//! Phase 3 coalesces blocks: it computes predecessor counts, identifies
//! single-edge (A → B) pairs where B has exactly one predecessor, converts
//! B's phis to copies, appends B's instructions to A, and redirects phi
//! operands from B to A. Exception-handler boundary blocks are excluded
//! from coalescing.
//!
//! # Complexity
//!
//! O(n * max_iterations) where n is the number of blocks.

use std::collections::{BTreeMap, VecDeque};

use crate::{
    bitset::BitSet,
    events::{EventKind, EventListener},
    ir::{
        function::{SsaEditOptions, SsaEditor, SsaFunction},
        ops::SsaOp,
    },
    passes::utils::{loop_canonical_blocks, resolve_chain},
    target::Target,
};

/// Run block merging on `ssa`.
///
/// Executes three phases: trampoline elimination, entry-trampoline
/// simplification, and block coalescing. Each inner loop is capped by
/// `max_iterations`.
///
/// # Arguments
///
/// * `ssa` — The SSA function to simplify in place.
/// * `method` — Opaque method reference recorded in emitted events.
/// * `events` — Event sink for [`EventKind::BranchSimplified`] and
///   [`EventKind::BlockRemoved`] events.
/// * `max_iterations` — Cap on the inner fixpoint loops for both
///   trampoline elimination and block coalescing.
///
/// # Returns
///
/// `true` if any block was merged or any branch redirected.
pub fn run<T, L>(
    ssa: &mut SsaFunction<T>,
    method: &T::MethodRef,
    events: &L,
    max_iterations: usize,
) -> bool
where
    T: Target,
    L: EventListener<T> + ?Sized,
{
    let mut changed = false;

    // Phase 1: eliminate trampoline blocks.
    for _ in 0..max_iterations {
        let iteration_changes = run_trampoline_iteration(ssa, method, events);
        if iteration_changes == 0 {
            break;
        }
        changed = true;
    }

    // Phase 2: handle entry trampoline (B0 has no predecessors so phase 1
    // can't redirect them — instead inline the target if safe, otherwise
    // mark for codegen regeneration).
    if simplify_entry_trampoline(ssa, method, events) {
        changed = true;
    }

    // Phase 3: coalesce non-trivial blocks connected by a single edge.
    if coalesce_blocks(ssa, method, events, max_iterations) > 0 {
        changed = true;
    }

    changed
}

/// Blocks that must not be merged *into* — a region entry absorbing a
/// predecessor from outside would pull non-region code into the region.
///
/// Together with [`exception_region_ends`] these are the exception-region
/// boundaries. Every path that removes or bypasses a block has to respect them:
/// nothing in the crate rewrites `handler_start_block` / `filter_start_block`
/// after a block is emptied, so a boundary block that is silently dropped leaves
/// the exception edge pointing at a block with no terminator, and the real
/// handler body loses its only root.
fn exception_region_starts<T: Target>(ssa: &SsaFunction<T>) -> BitSet {
    let mut starts = BitSet::new(ssa.block_count());
    for handler in ssa.exception_handlers() {
        for block in [handler.try_start_block, handler.handler_start_block]
            .into_iter()
            .chain(std::iter::once(handler.filter_start_block))
            .flatten()
        {
            starts.insert_checked(block);
        }
    }
    starts
}

/// Blocks that must not be merged *from* — a region end absorbing its successor
/// would extend the region past its boundary.
fn exception_region_ends<T: Target>(ssa: &SsaFunction<T>) -> BitSet {
    let mut ends = BitSet::new(ssa.block_count());
    for handler in ssa.exception_handlers() {
        for block in [handler.try_end_block, handler.handler_end_block]
            .into_iter()
            .flatten()
        {
            ends.insert_checked(block);
        }
    }
    ends
}

fn run_trampoline_iteration<T, L>(
    ssa: &mut SsaFunction<T>,
    method: &T::MethodRef,
    events: &L,
) -> usize
where
    T: Target,
    L: EventListener<T> + ?Sized,
{
    let mut trampolines = ssa.find_trampoline_blocks(true);
    // Nothing to filter, so do not pay for the loop forest. This runs once per
    // fixpoint iteration, including the terminating one that finds nothing —
    // and `loop_canonical_blocks` builds the whole loop forest.
    if trampolines.is_empty() {
        return 0;
    }
    // Preserve canonical loop preheaders so this pass does not fight the loop
    // canonicalizer (which re-inserts any preheader merged away here).
    let preheaders = loop_canonical_blocks(ssa);
    // ...and preserve exception-region boundaries, which `coalesce_blocks`
    // already refuses to merge across. `find_trampoline_blocks` only skips the
    // entry block, so without this a handler or filter entry that happens to be
    // a bare forwarding jump has its predecessors redirected past it and is then
    // cleared — leaving `handler_start_block` pointing at an empty block.
    let region_starts = exception_region_starts(ssa);
    let region_ends = exception_region_ends(ssa);
    trampolines.retain(|block, _| {
        !preheaders.contains(block)
            && !region_starts.contains_checked(*block)
            && !region_ends.contains_checked(*block)
    });
    if trampolines.is_empty() {
        return 0;
    }
    let mut redirected = 0usize;
    let mut cleared = 0usize;
    let result = ssa.edit(SsaEditOptions::new(), |editor| {
        redirected = redirect_to_ultimate_targets(editor, &trampolines, method, events);
        cleared = clear_trampolines(editor, &trampolines, method, events);
        Ok(())
    });
    if result.is_err() {
        return 0;
    }
    redirected.saturating_add(cleared)
}

fn redirect_to_ultimate_targets<T, L>(
    editor: &mut SsaEditor<T>,
    trampolines: &BTreeMap<usize, usize>,
    method: &T::MethodRef,
    events: &L,
) -> usize
where
    T: Target,
    L: EventListener<T> + ?Sized,
{
    if trampolines.is_empty() {
        return 0;
    }

    let ultimate_targets: BTreeMap<usize, usize> = trampolines
        .keys()
        .map(|&t| (t, resolve_chain(trampolines, t)))
        .collect();

    // Maps (trampoline, ultimate_target) → predecessors that redirected
    // through it; needed to fix up phi operands at the ultimate target.
    let mut redirected_preds: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
    let mut redirected: usize = 0;

    let block_count = editor.function().block_count();
    for block_idx in 0..block_count {
        let Some(old_targets) = editor
            .function()
            .block(block_idx)
            .and_then(|block| block.terminator_op())
            .map(SsaOp::successors)
        else {
            continue;
        };

        // Only this block's actual successors can be trampolines, so look each
        // one up directly instead of trying every trampoline (which made this
        // O(blocks * trampolines)).
        let mut changed = false;
        for &target in &old_targets {
            let Some(&ultimate) = ultimate_targets.get(&target) else {
                continue;
            };
            if editor
                .redirect_terminator_target(block_idx, target, ultimate)
                .unwrap_or(false)
            {
                redirected_preds
                    .entry((target, ultimate))
                    .or_default()
                    .push(block_idx);
                changed = true;
            }
        }

        if changed {
            let new_targets = editor
                .function()
                .block(block_idx)
                .and_then(|block| block.terminator_op())
                .map(SsaOp::successors)
                .unwrap_or_default();
            let event = crate::events::Event {
                kind: EventKind::BranchSimplified,
                method: Some(method.clone()),
                location: Some(block_idx),
                message: format!(
                    "redirected through trampoline: {old_targets:?} -> {new_targets:?}"
                ),
                pass: None,
            };
            events.push(event);
            redirected = redirected.saturating_add(1);
        }
    }

    // Update phi operands at ultimate target blocks.
    for (&(trampoline, ultimate), preds) in &redirected_preds {
        let _ = editor.expand_phi_predecessor(ultimate, trampoline, preds);
    }

    redirected
}

fn clear_trampolines<T, L>(
    editor: &mut SsaEditor<T>,
    trampolines: &BTreeMap<usize, usize>,
    method: &T::MethodRef,
    events: &L,
) -> usize
where
    T: Target,
    L: EventListener<T> + ?Sized,
{
    let mut cleared: usize = 0;
    for &block_idx in trampolines.keys() {
        if editor.clear_block(block_idx).unwrap_or(false) {
            let event = crate::events::Event {
                kind: EventKind::BlockRemoved,
                method: Some(method.clone()),
                location: Some(block_idx),
                message: format!("cleared trampoline block B{block_idx}"),
                pass: None,
            };
            events.push(event);
            cleared = cleared.saturating_add(1);
        }
    }
    cleared
}

/// Inline B0's target when B0 is a trampoline. Non-entry trampolines are
/// handled by `run_trampoline_iteration`; B0 has no predecessors so that
/// approach can't reach it.
fn simplify_entry_trampoline<T, L>(
    ssa: &mut SsaFunction<T>,
    method: &T::MethodRef,
    events: &L,
) -> bool
where
    T: Target,
    L: EventListener<T> + ?Sized,
{
    let target = match ssa.block(0).and_then(|b| b.is_trampoline()) {
        Some(t) => t,
        None => return false,
    };

    let preds = ssa.block_predecessors(target);
    let target_has_phis = ssa.block(target).is_none_or(|b| !b.phi_nodes().is_empty());

    if preds.len() == 1 && preds.first().copied() == Some(0) && !target_has_phis {
        // Safe to inline: the target's only external predecessor is B0 and it
        // has no phis. Move target's instructions into B0, then redirect any
        // self-references (B_target had a back-edge to itself) to B0.
        let target_instrs = ssa
            .block(target)
            .map(|b| b.instructions().to_vec())
            .unwrap_or_default();

        let result = ssa.edit(SsaEditOptions::new(), |editor| {
            editor.remove_instruction_tail(0, 0)?;
            for (instr_idx, instr) in target_instrs.iter().cloned().enumerate() {
                editor.insert_instruction(0, instr_idx, instr)?;
            }
            let entry_len = editor
                .function()
                .block(0)
                .map(|block| block.instructions().len())
                .unwrap_or(0);
            for instr_idx in 0..entry_len {
                let Some(mut op) = editor
                    .function()
                    .block(0)
                    .and_then(|block| block.instruction(instr_idx))
                    .map(|instr| instr.op().clone())
                else {
                    continue;
                };
                if op.redirect_target(target, 0) {
                    editor.replace_instruction_op(0, instr_idx, op)?;
                }
            }
            editor.clear_block(target)?;
            Ok(())
        });
        if result.is_err() {
            return false;
        }
        let event = crate::events::Event {
            kind: EventKind::BlockRemoved,
            method: Some(method.clone()),
            location: Some(0),
            message: format!("inlined entry trampoline: B0 jump to B{target} merged into B0"),
            pass: None,
        };
        events.push(event);
        true
    } else {
        // Can't inline (multiple predecessors or phis); just mark as modified
        // so codegen regenerates clean IL without original junk bytes.
        let event = crate::events::Event {
            kind: EventKind::BranchSimplified,
            method: Some(method.clone()),
            location: Some(0),
            message: format!("entry block is trampoline to B{target} (regenerating clean IL)"),
            pass: None,
        };
        events.push(event);
        true
    }
}

/// Merge each block A into its sole predecessor when A is the only successor.
fn coalesce_blocks<T, L>(
    ssa: &mut SsaFunction<T>,
    method: &T::MethodRef,
    events: &L,
    max_iterations: usize,
) -> usize
where
    T: Target,
    L: EventListener<T> + ?Sized,
{
    let mut merged: usize = 0;

    // Collect exception-handler boundary blocks.
    //
    // - Region *start* blocks must not be the merge target — absorbing a
    //   predecessor outside the region would pull non-region code in.
    // - Region *end* blocks must not be the merge source — absorbing a
    //   successor outside the region would extend the region.
    let no_merge_into = exception_region_starts(ssa);
    let no_merge_from = exception_region_ends(ssa);

    for _ in 0..max_iterations {
        let mut iteration_merges: usize = 0;

        let block_count = ssa.block_count();
        let mut pred_counts: Vec<usize> = vec![0; block_count];
        let mut pred_of: Vec<Option<usize>> = vec![None; block_count];
        for idx in 0..block_count {
            let successors = ssa
                .block(idx)
                .and_then(|b| b.terminator_op())
                .map(SsaOp::successors)
                .unwrap_or_default();
            for succ in successors {
                if succ < block_count {
                    if let Some(c) = pred_counts.get_mut(succ) {
                        *c = c.saturating_add(1);
                    }
                    if let Some(p) = pred_of.get_mut(succ) {
                        *p = Some(idx);
                    }
                }
            }
        }
        if let Some(c) = pred_counts.get_mut(0) {
            *c = c.saturating_add(1);
        }

        let mut pairs: Vec<(usize, usize)> = Vec::new();
        let mut consumed = BitSet::new(block_count);
        for a_idx in 0..block_count {
            if consumed.contains(a_idx) {
                continue;
            }
            let b_idx = match ssa.block(a_idx).and_then(|b| b.terminator_op()) {
                Some(SsaOp::Jump { target }) => *target,
                _ => continue,
            };
            if b_idx >= block_count || b_idx == a_idx {
                continue;
            }
            if pred_counts.get(b_idx).copied().unwrap_or(0) != 1 {
                continue;
            }
            if no_merge_from.contains(a_idx) || no_merge_into.contains(b_idx) {
                continue;
            }
            if block_reaches(ssa, b_idx, a_idx) {
                continue;
            }
            let b_empty = ssa.block(b_idx).is_none_or(|b| b.instructions().is_empty());
            if b_empty {
                continue;
            }
            pairs.push((a_idx, b_idx));
            consumed.insert(a_idx);
            consumed.insert(b_idx);
        }

        if !pairs.is_empty() {
            let result = ssa.edit(SsaEditOptions::new(), |editor| {
                for &(a_idx, b_idx) in &pairs {
                    if editor.coalesce_unconditional_successor(a_idx, b_idx)? {
                        let event = crate::events::Event {
                            kind: EventKind::BlockRemoved,
                            method: Some(method.clone()),
                            location: Some(b_idx),
                            message: format!("coalesced B{b_idx} into B{a_idx}"),
                            pass: None,
                        };
                        events.push(event);
                        iteration_merges = iteration_merges.saturating_add(1);
                    }
                }
                Ok(())
            });
            if result.is_err() {
                iteration_merges = 0;
            }
        }

        merged = merged.saturating_add(iteration_merges);
        if iteration_merges == 0 {
            break;
        }
    }

    merged
}

fn block_reaches<T: Target>(ssa: &SsaFunction<T>, start: usize, target: usize) -> bool {
    if start >= ssa.block_count() || target >= ssa.block_count() {
        return false;
    }

    let mut visited = BitSet::new(ssa.block_count());
    let mut worklist = VecDeque::new();
    worklist.push_back(start);
    visited.insert(start);

    while let Some(block_idx) = worklist.pop_front() {
        let successors = ssa
            .block(block_idx)
            .and_then(|block| block.terminator_op())
            .map(SsaOp::successors)
            .unwrap_or_default();
        for successor in successors {
            if successor == target {
                return true;
            }
            if successor < ssa.block_count() && visited.insert(successor) {
                worklist.push_back(successor);
            }
        }
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        events::EventLog,
        ir::{
            block::SsaBlock,
            exception::SsaExceptionHandler,
            instruction::SsaInstruction,
            ops::SsaOp,
            phi::{PhiNode, PhiOperand},
            value::ConstValue,
            variable::{DefSite, SsaVarId, VariableOrigin},
        },
        testing::{MockTarget, MockType, run_mock_pass_boundary},
    };

    fn instr(op: SsaOp<MockTarget>) -> SsaInstruction<MockTarget> {
        SsaInstruction::synthetic(op)
    }

    fn local_at(
        ssa: &mut SsaFunction<MockTarget>,
        idx: u16,
        block: usize,
        instr: usize,
    ) -> SsaVarId {
        ssa.create_variable(
            VariableOrigin::Local(idx),
            0,
            DefSite::instruction(block, instr),
            MockType::I32,
        )
    }

    /// A handler entry that is a bare forwarding jump must survive the
    /// trampoline pass. `coalesce_blocks` already refuses to merge across an
    /// exception-region boundary; the trampoline path had no such guard, so it
    /// redirected the region's predecessors past the handler entry and cleared
    /// it. Nothing in the crate rewrites `handler_start_block` afterwards, so the
    /// exception edge would still point at a now-empty block and the real handler
    /// body would lose its only root.
    #[test]
    fn a_handler_entry_that_is_a_trampoline_is_not_removed() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 4);

        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);

        let mut b1 = SsaBlock::new(1);
        b1.add_instruction(instr(SsaOp::Return { value: None }));
        ssa.add_block(b1);

        // The handler entry: a bare forwarding jump into the handler body.
        let mut b2 = SsaBlock::new(2);
        b2.add_instruction(instr(SsaOp::Jump { target: 3 }));
        ssa.add_block(b2);

        let mut b3 = SsaBlock::new(3);
        b3.add_instruction(instr(SsaOp::Return { value: None }));
        ssa.add_block(b3);

        ssa.set_exception_handlers(vec![SsaExceptionHandler {
            flags: 0,
            try_offset: 0,
            try_length: 1,
            handler_offset: 2,
            handler_length: 1,
            class_token_or_filter: 0,
            try_start_block: Some(0),
            try_end_block: Some(1),
            handler_start_block: Some(2),
            handler_end_block: Some(3),
            filter_start_block: None,
        }]);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        run(&mut ssa, &0u32, &log, 8);

        let handler_entry = ssa.block(2).expect("handler entry block must still exist");
        assert!(
            handler_entry.terminator_op().is_some(),
            "the handler entry must keep its terminator; `handler_start_block` \
             still points here and nothing rewrites it"
        );
        // Coalescing the entry with its body is fine — the entry keeps a
        // terminator and still roots the handler. What must never happen is the
        // entry being *emptied*, which is what the trampoline path did.
        assert!(
            !handler_entry.instructions().is_empty(),
            "the handler entry must not be cleared out from under \
             `handler_start_block`"
        );
    }

    /// `SsaOp::Leave` exits a protected region. Treating it as a plain
    /// forwarding jump rewrites `pred -> Leave(target)` into
    /// `pred -> Jump(target)`, dropping the region-exit semantics.
    #[test]
    fn a_leave_only_block_is_not_a_trampoline() {
        let mut block: SsaBlock<MockTarget> = SsaBlock::new(0);
        block.add_instruction(instr(SsaOp::Leave { target: 1 }));
        assert_eq!(
            block.is_trampoline(),
            None,
            "Leave carries region-exit semantics a Jump does not"
        );
        assert_eq!(
            block.is_unconditional_transfer(),
            Some(1),
            "but it is still structurally an unconditional transfer"
        );

        let mut jump: SsaBlock<MockTarget> = SsaBlock::new(1);
        jump.add_instruction(instr(SsaOp::Jump { target: 2 }));
        assert_eq!(jump.is_trampoline(), Some(2));
    }

    #[test]
    fn simple_trampoline_elimination() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 1);
        let v0 = local_at(&mut ssa, 0, 0, 0);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Const {
            dest: v0,
            value: ConstValue::I32(42),
        }));
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);
        let mut b1 = SsaBlock::new(1);
        b1.add_instruction(instr(SsaOp::Jump { target: 2 }));
        ssa.add_block(b1);
        let mut b2 = SsaBlock::new(2);
        b2.add_instruction(instr(SsaOp::Return { value: Some(v0) }));
        ssa.add_block(b2);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "simple block merge", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(changed);
        // B1 trampoline should be eliminated
        assert!(log.has(EventKind::BranchSimplified) || log.has(EventKind::BlockRemoved));
    }

    #[test]
    fn chain_of_trampolines() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 1);
        let v0 = local_at(&mut ssa, 0, 0, 0);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Const {
            dest: v0,
            value: ConstValue::I32(1),
        }));
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);
        for i in 1..4 {
            let mut b = SsaBlock::new(i);
            b.add_instruction(instr(SsaOp::Jump { target: i + 1 }));
            ssa.add_block(b);
        }
        let mut b4 = SsaBlock::new(4);
        b4.add_instruction(instr(SsaOp::Return { value: Some(v0) }));
        ssa.add_block(b4);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "trampoline chain block merge", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(changed, "chain of trampolines should be eliminated");
    }

    #[test]
    fn coalesce_sequential_blocks() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 2);
        let a = local_at(&mut ssa, 0, 0, 0);
        let b = local_at(&mut ssa, 1, 1, 0);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Const {
            dest: a,
            value: ConstValue::I32(10),
        }));
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);
        let mut b1 = SsaBlock::new(1);
        b1.add_instruction(instr(SsaOp::Copy { dest: b, src: a }));
        b1.add_instruction(instr(SsaOp::Return { value: Some(b) }));
        ssa.add_block(b1);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "sequential block coalescing", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(changed, "sequential blocks should coalesce");
    }

    #[test]
    fn coalesce_with_phi_operand() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 3);
        let v0 = local_at(&mut ssa, 0, 0, 0);
        let v1 = local_at(&mut ssa, 1, 1, 0);
        let phi_var =
            ssa.create_variable(VariableOrigin::Local(2), 0, DefSite::phi(2), MockType::I32);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Const {
            dest: v0,
            value: ConstValue::I32(5),
        }));
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);
        let mut b1 = SsaBlock::new(1);
        b1.add_instruction(instr(SsaOp::Const {
            dest: v1,
            value: ConstValue::I32(10),
        }));
        b1.add_instruction(instr(SsaOp::Jump { target: 2 }));
        ssa.add_block(b1);
        let mut b2 = SsaBlock::new(2);
        let mut phi = PhiNode::new(phi_var, VariableOrigin::Local(2));
        phi.add_operand(PhiOperand::new(v1, 1));
        b2.add_phi(phi);
        b2.add_instruction(instr(SsaOp::Return {
            value: Some(phi_var),
        }));
        ssa.add_block(b2);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "phi operand block coalescing", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(changed, "coalescing should preserve phi operands");
    }

    #[test]
    fn entry_trampoline_is_handled() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 1);
        let v0 = local_at(&mut ssa, 0, 1, 0);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);
        let mut b1 = SsaBlock::new(1);
        b1.add_instruction(instr(SsaOp::Const {
            dest: v0,
            value: ConstValue::I32(7),
        }));
        b1.add_instruction(instr(SsaOp::Return { value: Some(v0) }));
        ssa.add_block(b1);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "entry trampoline block merge", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(changed, "entry trampoline should be handled");
    }

    #[test]
    fn empty_function_no_changes() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 0);
        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "empty block merge", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(!changed);
    }

    #[test]
    fn no_trampoline_no_changes() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 1);
        let v0 = local_at(&mut ssa, 0, 0, 0);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Const {
            dest: v0,
            value: ConstValue::I32(1),
        }));
        b0.add_instruction(instr(SsaOp::Return { value: Some(v0) }));
        ssa.add_block(b0);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "no-trampoline block merge", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(!changed, "no trampolines should mean no changes");
    }

    #[test]
    fn trampoline_with_phi_successor() {
        let mut ssa: SsaFunction<MockTarget> = SsaFunction::new(0, 2);
        let v0 = local_at(&mut ssa, 0, 0, 0);
        let v1 = local_at(&mut ssa, 1, 2, 0);
        let phi_var =
            ssa.create_variable(VariableOrigin::Local(2), 0, DefSite::phi(2), MockType::I32);
        let mut b0 = SsaBlock::new(0);
        b0.add_instruction(instr(SsaOp::Const {
            dest: v0,
            value: ConstValue::I32(10),
        }));
        b0.add_instruction(instr(SsaOp::Jump { target: 1 }));
        ssa.add_block(b0);
        let mut b1 = SsaBlock::new(1);
        b1.add_instruction(instr(SsaOp::Jump { target: 2 }));
        ssa.add_block(b1);
        let mut b2 = SsaBlock::new(2);
        let mut phi = PhiNode::new(phi_var, VariableOrigin::Local(2));
        phi.add_operand(PhiOperand::new(v0, 1));
        b2.add_phi(phi);
        b2.add_instruction(instr(SsaOp::Const {
            dest: v1,
            value: ConstValue::I32(20),
        }));
        b2.add_instruction(instr(SsaOp::Return {
            value: Some(phi_var),
        }));
        ssa.add_block(b2);
        ssa.recompute_uses();

        let log: EventLog<MockTarget> = EventLog::new();
        let method = 0u32;
        let changed = run_mock_pass_boundary(&mut ssa, "phi successor trampoline merge", |ssa| {
            run(ssa, &method, &log, 10)
        });
        assert!(changed, "trampoline with phi successor should be handled");
    }
}