dotscope 0.7.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
//! Control flow simplification pass.
//!
//! Simplifies the control flow graph through several transformations:
//!
//! 1. **Jump threading**: Skip intermediate trampoline blocks
//! 2. **Branch canonicalization**: Simplify `branch cond, B, B` to `jump B`
//! 3. **Unreachable tail removal**: Remove code after unconditional exits
//!
//! Uses an iterative fixed-point algorithm to handle cascading simplifications.
//!
//! ## Example
//!
//! Before:
//! ```text
//! B0: jump B1
//! B1: jump B2
//! B2: ret
//! ```
//!
//! After:
//! ```text
//! B0: jump B2    // Directly to B2
//! B1: jump B2    // Will be eliminated by DCE
//! B2: ret
//! ```
//!

use std::collections::BTreeMap;

use crate::{
    analysis::{SsaFunction, SsaOp},
    compiler::{
        pass::SsaPass,
        passes::{deadcode::find_dead_tails, utils::resolve_chain},
        CompilerContext, EventKind, EventLog,
    },
    metadata::token::Token,
    CilObject, Result,
};

/// Control flow simplification pass.
///
/// Performs iterative control flow simplification including:
/// - Jump threading through trampoline blocks
/// - Branch-to-same-target simplification
/// - Dead tail removal (code after terminators)
///
/// The pass iterates until no more changes are made (fixed point).
pub struct ControlFlowSimplificationPass {
    /// Maximum fixpoint iterations before stopping.
    max_iterations: usize,
}

impl ControlFlowSimplificationPass {
    /// Creates a new control flow simplification pass.
    ///
    /// # Arguments
    ///
    /// * `max_iterations` - Maximum fixpoint iterations for jump threading, branch
    ///   simplification, and dead tail removal. The default config value is 20.
    #[must_use]
    pub fn new(max_iterations: usize) -> Self {
        Self { max_iterations }
    }

    /// Finds branches where both targets resolve to the same block.
    ///
    /// A branch `branch cond, B, B` can be simplified to `jump B` since
    /// the condition doesn't affect the control flow. Also detects cases
    /// where targets are different blocks but resolve to the same ultimate
    /// destination through trampoline chains.
    ///
    /// # Arguments
    ///
    /// * `ssa` - The SSA function to analyze.
    /// * `trampolines` - Map of trampoline blocks to their targets.
    ///
    /// # Returns
    ///
    /// A vector of (block index, target block) pairs for branches to simplify.
    fn find_same_target_branches(
        ssa: &SsaFunction,
        trampolines: &BTreeMap<usize, usize>,
    ) -> Vec<(usize, usize)> {
        ssa.iter_blocks()
            .filter_map(|(block_idx, block)| {
                block.terminator_op().and_then(|op| match op {
                    SsaOp::Branch {
                        true_target,
                        false_target,
                        ..
                    }
                    | SsaOp::BranchCmp {
                        true_target,
                        false_target,
                        ..
                    } => {
                        if true_target == false_target {
                            return Some((block_idx, *true_target));
                        }
                        // Resolve through trampoline chains to catch convergent targets
                        let true_ultimate = resolve_chain(trampolines, *true_target);
                        let false_ultimate = resolve_chain(trampolines, *false_target);
                        if true_ultimate == false_ultimate {
                            Some((block_idx, true_ultimate))
                        } else {
                            None
                        }
                    }
                    SsaOp::Switch {
                        targets, default, ..
                    } => {
                        if targets.iter().all(|t| *t == *default) {
                            return Some((block_idx, *default));
                        }
                        // Resolve through trampoline chains
                        let default_ultimate = resolve_chain(trampolines, *default);
                        if targets
                            .iter()
                            .all(|t| resolve_chain(trampolines, *t) == default_ultimate)
                        {
                            return Some((block_idx, default_ultimate));
                        }
                        // Self-loop elimination: if all cases except one are
                        // self-loops (target == block_idx), the switch degenerates
                        // to a jump to the single non-self target. This handles
                        // residual CFF in exception handlers where the obfuscator
                        // creates an irresolvable cycle with endfinally as the
                        // only exit.
                        let non_self: Vec<usize> = targets
                            .iter()
                            .chain(std::iter::once(default))
                            .copied()
                            .filter(|&t| t != block_idx)
                            .collect();
                        if !non_self.is_empty() && non_self.iter().all(|t| *t == non_self[0]) {
                            Some((block_idx, non_self[0]))
                        } else {
                            None
                        }
                    }
                    _ => None,
                })
            })
            .collect()
    }

    /// Applies jump threading to all control flow instructions.
    ///
    /// Updates jumps, branches, and switches to skip trampoline blocks
    /// and go directly to their ultimate targets.
    ///
    /// # Arguments
    ///
    /// * `ssa` - The SSA function to modify.
    /// * `trampolines` - The map of trampoline blocks.
    /// * `method_token` - The method token for change tracking.
    /// * `changes` - The change set to record modifications.
    ///
    /// # Returns
    ///
    /// The number of control flow instructions that were updated.
    fn apply_jump_threading(
        ssa: &mut SsaFunction,
        trampolines: &BTreeMap<usize, usize>,
        method_token: Token,
        changes: &mut EventLog,
    ) -> usize {
        // Precompute ultimate targets for all trampolines
        let ultimate_targets: BTreeMap<usize, usize> = trampolines
            .keys()
            .map(|&t| (t, resolve_chain(trampolines, t)))
            .collect();

        let mut threaded_count = 0;

        for block_idx in 0..ssa.block_count() {
            if let Some(block) = ssa.block_mut(block_idx) {
                if let Some(last) = block.instructions_mut().last_mut() {
                    let op = last.op_mut();
                    let old_targets = op.successors();

                    // Redirect each trampoline to its ultimate target
                    let mut changed = false;
                    for (&trampoline, &ultimate) in &ultimate_targets {
                        if op.redirect_target(trampoline, ultimate) {
                            changed = true;
                        }
                    }

                    if changed {
                        let new_targets = op.successors();
                        changes
                            .record(EventKind::ControlFlowRestructured)
                            .at(method_token, block_idx)
                            .message(format!("jump threaded: {old_targets:?} -> {new_targets:?}"));
                        threaded_count += 1;
                    }
                }
            }
        }

        threaded_count
    }

    /// Simplifies branches where both targets are the same.
    ///
    /// Converts `branch cond, B, B` to `jump B`.
    ///
    /// # Arguments
    ///
    /// * `ssa` - The SSA function to modify.
    /// * `same_target_branches` - The branches to simplify.
    /// * `method_token` - The method token for change tracking.
    /// * `changes` - The change set to record modifications.
    ///
    /// # Returns
    ///
    /// The number of branches that were simplified.
    fn simplify_same_target_branches(
        ssa: &mut SsaFunction,
        same_target_branches: &[(usize, usize)],
        method_token: Token,
        changes: &mut EventLog,
    ) -> usize {
        let mut simplified_count = 0;

        for &(block_idx, target) in same_target_branches {
            if let Some(block) = ssa.block_mut(block_idx) {
                if let Some(last) = block.instructions_mut().last_mut() {
                    last.set_op(SsaOp::Jump { target });
                    changes
                        .record(EventKind::BranchSimplified)
                        .at(method_token, block_idx)
                        .message(format!(
                            "branch to same target simplified: B{block_idx} branch -> jump B{target}"
                        ));
                    simplified_count += 1;
                }
            }
        }

        simplified_count
    }

    /// Removes dead code tails (instructions after terminators).
    ///
    /// # Arguments
    ///
    /// * `ssa` - The SSA function to modify.
    /// * `dead_tails` - The dead tails to remove.
    /// * `method_token` - The method token for change tracking.
    /// * `changes` - The change set to record modifications.
    ///
    /// # Returns
    ///
    /// The number of instructions removed.
    fn remove_dead_tails(
        ssa: &mut SsaFunction,
        dead_tails: &[(usize, usize)],
        method_token: Token,
        changes: &mut EventLog,
    ) -> usize {
        let mut removed_count = 0;

        for &(block_idx, start_idx) in dead_tails {
            if let Some(block) = ssa.block_mut(block_idx) {
                let instr_count = block.instruction_count();
                let to_remove = instr_count.saturating_sub(start_idx);
                for _ in 0..to_remove {
                    block.instructions_mut().pop();
                    removed_count += 1;
                }
                if to_remove > 0 {
                    changes
                        .record(EventKind::InstructionRemoved)
                        .at(method_token, block_idx)
                        .message(format!(
                            "removed {to_remove} dead instructions after terminator in B{block_idx}"
                        ));
                }
            }
        }

        removed_count
    }

    /// Runs a single iteration of control flow simplification.
    ///
    /// # Arguments
    ///
    /// * `ssa` - The SSA function to modify.
    /// * `method_token` - The method token for change tracking.
    /// * `changes` - The change set to record modifications.
    ///
    /// # Returns
    ///
    /// The total number of changes made during this iteration.
    fn run_iteration(ssa: &mut SsaFunction, method_token: Token, changes: &mut EventLog) -> usize {
        let mut total_changes = 0;

        // Step 1: Find and apply jump threading (don't skip entry block)
        let trampolines = ssa.find_trampoline_blocks(false);
        if !trampolines.is_empty() {
            total_changes += Self::apply_jump_threading(ssa, &trampolines, method_token, changes);
        }

        // Step 2: Simplify branches to same target (also resolves through trampolines)
        let same_target_branches = Self::find_same_target_branches(ssa, &trampolines);
        if !same_target_branches.is_empty() {
            total_changes += Self::simplify_same_target_branches(
                ssa,
                &same_target_branches,
                method_token,
                changes,
            );
        }

        // Step 3: Remove dead tails
        let dead_tails = find_dead_tails(ssa);
        if !dead_tails.is_empty() {
            total_changes += Self::remove_dead_tails(ssa, &dead_tails, method_token, changes);
        }

        total_changes
    }
}

impl SsaPass for ControlFlowSimplificationPass {
    fn name(&self) -> &'static str {
        "control-flow-simplification"
    }

    fn description(&self) -> &'static str {
        "Simplifies control flow by threading jumps and eliminating trampolines"
    }

    fn run_on_method(
        &self,
        ssa: &mut SsaFunction,
        method_token: Token,
        ctx: &CompilerContext,
        _assembly: &CilObject,
    ) -> Result<bool> {
        let mut changes = EventLog::new();

        // Iterate until fixed point
        for _ in 0..self.max_iterations {
            let iteration_changes = Self::run_iteration(ssa, method_token, &mut changes);
            if iteration_changes == 0 {
                break;
            }
        }

        let changed = !changes.is_empty();
        if changed {
            ctx.events.merge(&changes);
        }
        Ok(changed)
    }
}
#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::sync::Arc;

    use crate::{
        analysis::{
            CallGraph, ConstValue, SsaBlock, SsaFunction, SsaFunctionBuilder, SsaInstruction,
            SsaOp, SsaVarId,
        },
        compiler::{
            passes::{controlflow::ControlFlowSimplificationPass, deadcode::find_dead_tails},
            CompilerContext, SsaPass,
        },
        metadata::token::Token,
        test::helpers::test_assembly_arc,
    };

    /// Helper to create a minimal analysis context for testing.
    fn test_context() -> CompilerContext {
        let call_graph = Arc::new(CallGraph::new());
        CompilerContext::new(call_graph)
    }

    #[test]
    fn test_find_same_target_branches_none() {
        let ssa = SsaFunctionBuilder::new(3, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 1, 2); // Different targets
                });
            })
            .unwrap();

        let same_targets =
            ControlFlowSimplificationPass::find_same_target_branches(&ssa, &BTreeMap::new());
        assert!(same_targets.is_empty());
    }

    #[test]
    fn test_find_same_target_branches_found() {
        let ssa = SsaFunctionBuilder::new(2, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 1, 1); // Same target!
                });
                f.block(1, |b| b.ret());
            })
            .unwrap();

        let same_targets =
            ControlFlowSimplificationPass::find_same_target_branches(&ssa, &BTreeMap::new());
        assert_eq!(same_targets.len(), 1);
        assert_eq!(same_targets[0], (0, 1));
    }

    #[test]
    fn test_find_same_target_branches_multiple() {
        let ssa = SsaFunctionBuilder::new(4, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 2, 2);
                });
                f.block(1, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 3, 3);
                });
                f.block(2, |b| b.ret());
                f.block(3, |b| b.ret());
            })
            .unwrap();

        let same_targets =
            ControlFlowSimplificationPass::find_same_target_branches(&ssa, &BTreeMap::new());
        assert_eq!(same_targets.len(), 2);
    }

    #[test]
    fn test_find_same_target_branches_convergent_trampolines() {
        // Branch(cond, 1, 2) where both 1 and 2 are trampolines to 3
        let ssa = SsaFunctionBuilder::new(4, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 1, 2); // Different targets...
                });
                f.block(1, |b| b.jump(3)); // ...but both trampoline to 3
                f.block(2, |b| b.jump(3));
                f.block(3, |b| b.ret());
            })
            .unwrap();

        // Without trampoline info, targets look different
        let same_targets =
            ControlFlowSimplificationPass::find_same_target_branches(&ssa, &BTreeMap::new());
        assert!(same_targets.is_empty());

        // With trampoline info, convergence is detected
        let trampolines = ssa.find_trampoline_blocks(false);
        let same_targets =
            ControlFlowSimplificationPass::find_same_target_branches(&ssa, &trampolines);
        assert_eq!(same_targets.len(), 1);
        assert_eq!(same_targets[0], (0, 3));
    }

    #[test]
    fn test_find_same_target_branches_one_trampoline() {
        // Branch(cond, 2, 1) where 1 is a trampoline to 2
        let ssa = SsaFunctionBuilder::new(3, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 2, 1); // true goes direct, false via trampoline
                });
                f.block(1, |b| b.jump(2)); // trampoline to 2
                f.block(2, |b| b.ret());
            })
            .unwrap();

        let trampolines = ssa.find_trampoline_blocks(false);
        let same_targets =
            ControlFlowSimplificationPass::find_same_target_branches(&ssa, &trampolines);
        assert_eq!(same_targets.len(), 1);
        assert_eq!(same_targets[0], (0, 2));
    }

    #[test]
    fn test_find_dead_tails_empty() {
        let ssa = SsaFunctionBuilder::new(0, 0).build_with(|_f| {}).unwrap();
        let dead_tails = find_dead_tails(&ssa);
        assert!(dead_tails.is_empty());
    }

    #[test]
    fn test_find_dead_tails_with_dead_code() {
        // Need to use manual construction here since builder won't allow
        // instructions after a terminator
        let mut ssa = SsaFunction::new(1, 0);

        let mut block0 = SsaBlock::new(0);
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Return { value: None }));
        // Dead code after return
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Const {
            dest: SsaVarId::from_index(0),
            value: ConstValue::I32(42),
        }));
        ssa.add_block(block0);

        let dead_tails = find_dead_tails(&ssa);
        assert_eq!(dead_tails.len(), 1);
        assert_eq!(dead_tails[0], (0, 1));
    }

    #[test]
    fn test_find_dead_tails_no_dead_code() {
        let ssa = SsaFunctionBuilder::new(1, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let _ = b.const_i32(42);
                    b.ret();
                });
            })
            .unwrap();

        let dead_tails = find_dead_tails(&ssa);
        assert!(dead_tails.is_empty());
    }

    #[test]
    fn test_find_dead_tails_multiple_dead_instructions() {
        // Need to use manual construction here since builder won't allow
        // instructions after a terminator
        let mut ssa = SsaFunction::new(1, 0);

        let mut block0 = SsaBlock::new(0);
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Return { value: None }));
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Const {
            dest: SsaVarId::from_index(0),
            value: ConstValue::I32(1),
        }));
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Const {
            dest: SsaVarId::from_index(1),
            value: ConstValue::I32(2),
        }));
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Const {
            dest: SsaVarId::from_index(2),
            value: ConstValue::I32(3),
        }));
        ssa.add_block(block0);

        let dead_tails = find_dead_tails(&ssa);
        assert_eq!(dead_tails.len(), 1);
        assert_eq!(dead_tails[0], (0, 1)); // Start at index 1
    }

    #[test]
    fn test_pass_empty_function() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        let mut ssa = SsaFunctionBuilder::new(0, 0).build_with(|_f| {}).unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(!changed);
    }

    #[test]
    fn test_pass_no_simplification_needed() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        let mut ssa = SsaFunctionBuilder::new(1, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let _ = b.const_i32(42);
                    b.ret();
                });
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(!changed);
    }

    #[test]
    fn test_pass_jump_threading() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        // Block 0: jump to trampoline
        // Block 1: trampoline to block 2
        // Block 2: return
        let mut ssa = SsaFunctionBuilder::new(3, 0)
            .build_with(|f| {
                f.block(0, |b| b.jump(1));
                f.block(1, |b| b.jump(2));
                f.block(2, |b| b.ret());
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // Verify block 0 now jumps directly to block 2
        if let Some(block) = ssa.block(0) {
            if let Some(SsaOp::Jump { target }) = block.terminator_op() {
                assert_eq!(*target, 2);
            }
        }
    }

    #[test]
    fn test_pass_leave_threading() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        // Block 0: leave to trampoline
        // Block 1: trampoline (leave) to block 2
        // Block 2: return
        let mut ssa = SsaFunctionBuilder::new(3, 0)
            .build_with(|f| {
                f.block(0, |b| b.leave(1));
                f.block(1, |b| b.leave(2));
                f.block(2, |b| b.ret());
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // Verify block 0 now leaves directly to block 2
        if let Some(block) = ssa.block(0) {
            if let Some(SsaOp::Leave { target }) = block.terminator_op() {
                assert_eq!(*target, 2);
            }
        }
    }

    #[test]
    fn test_pass_branch_threading() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        // Block 0: branch to trampolines
        // Block 1: trampoline to block 3
        // Block 2: trampoline to block 4
        // Block 3, 4: return
        let mut ssa = SsaFunctionBuilder::new(5, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 1, 2);
                });
                f.block(1, |b| b.jump(3));
                f.block(2, |b| b.jump(4));
                f.block(3, |b| b.ret());
                f.block(4, |b| b.ret());
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // Verify branch targets were threaded
        if let Some(block) = ssa.block(0) {
            if let Some(SsaOp::Branch {
                true_target,
                false_target,
                ..
            }) = block.terminator_op()
            {
                assert_eq!(*true_target, 3);
                assert_eq!(*false_target, 4);
            }
        }
    }

    #[test]
    fn test_pass_switch_threading() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        // Block 0: switch with trampoline targets
        // Blocks 1, 2, 3: trampolines to block 4
        // Block 4: return
        let mut ssa = SsaFunctionBuilder::new(5, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let val = b.const_i32(0);
                    b.switch(val, vec![1, 2], 3);
                });
                f.block(1, |b| b.jump(4));
                f.block(2, |b| b.jump(4));
                f.block(3, |b| b.jump(4));
                f.block(4, |b| b.ret());
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // Verify switch targets were threaded
        if let Some(block) = ssa.block(0) {
            if let Some(SsaOp::Switch {
                targets, default, ..
            }) = block.terminator_op()
            {
                assert!(targets.iter().all(|&t| t == 4));
                assert_eq!(*default, 4);
            }
        }
    }

    #[test]
    fn test_pass_same_target_branch_simplification() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        // Block 0: branch to same target
        let mut ssa = SsaFunctionBuilder::new(2, 0)
            .build_with(|f| {
                f.block(0, |b| {
                    let cond = b.const_true();
                    b.branch(cond, 1, 1);
                });
                f.block(1, |b| b.ret());
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // Verify branch was converted to jump
        if let Some(block) = ssa.block(0) {
            assert!(matches!(
                block.terminator_op(),
                Some(SsaOp::Jump { target: 1 })
            ));
        }
    }

    #[test]
    fn test_pass_dead_tail_removal() {
        // Need to use manual construction here since builder won't allow
        // instructions after a terminator
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        let mut ssa = SsaFunction::new(1, 0);

        let mut block0 = SsaBlock::new(0);
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Return { value: None }));
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Const {
            dest: SsaVarId::from_index(0),
            value: ConstValue::I32(42),
        }));
        ssa.add_block(block0);

        assert_eq!(ssa.block(0).unwrap().instruction_count(), 2);

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        assert_eq!(ssa.block(0).unwrap().instruction_count(), 1);
    }

    #[test]
    fn test_pass_iterative_convergence() {
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        // Create a chain: 0 -> 1 -> 2 -> 3 -> 4
        let mut ssa = SsaFunctionBuilder::new(5, 0)
            .build_with(|f| {
                f.block(0, |b| b.jump(1));
                f.block(1, |b| b.jump(2));
                f.block(2, |b| b.jump(3));
                f.block(3, |b| b.jump(4));
                f.block(4, |b| b.ret());
            })
            .unwrap();

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // All jumps should now go directly to block 4
        for i in 0..4 {
            if let Some(block) = ssa.block(i) {
                if let Some(SsaOp::Jump { target }) = block.terminator_op() {
                    assert_eq!(*target, 4);
                }
            }
        }
    }

    #[test]
    fn test_pass_combined_simplifications() {
        // Need to use manual construction here since builder won't allow
        // instructions after a terminator (for the dead tail test case)
        let pass = ControlFlowSimplificationPass::new(20);
        let ctx = test_context();
        let mut ssa = SsaFunction::new(4, 0);

        // Block 0: branch to same trampoline target
        let mut block0 = SsaBlock::new(0);
        block0.add_instruction(SsaInstruction::synthetic(SsaOp::Branch {
            condition: SsaVarId::from_index(0),
            true_target: 1,
            false_target: 1,
        }));
        ssa.add_block(block0);

        // Block 1: trampoline to block 2
        let mut block1 = SsaBlock::new(1);
        block1.add_instruction(SsaInstruction::synthetic(SsaOp::Jump { target: 2 }));
        ssa.add_block(block1);

        // Block 2: trampoline to block 3
        let mut block2 = SsaBlock::new(2);
        block2.add_instruction(SsaInstruction::synthetic(SsaOp::Jump { target: 3 }));
        ssa.add_block(block2);

        // Block 3: return with dead tail
        let mut block3 = SsaBlock::new(3);
        block3.add_instruction(SsaInstruction::synthetic(SsaOp::Return { value: None }));
        block3.add_instruction(SsaInstruction::synthetic(SsaOp::Nop));
        ssa.add_block(block3);

        let changed = pass
            .run_on_method(&mut ssa, Token::new(0x06000001), &ctx, &test_assembly_arc())
            .unwrap();
        assert!(changed);

        // Block 0 should be a jump to block 3
        if let Some(block) = ssa.block(0) {
            assert!(matches!(
                block.terminator_op(),
                Some(SsaOp::Jump { target: 3 })
            ));
        }

        // Block 3 should have no dead tail
        assert_eq!(ssa.block(3).unwrap().instruction_count(), 1);
    }
}