Skip to main content

cranelift_codegen/
post_dominator_tree.rs

1//! A post-dominator tree for a single function.
2//!
3//! The *post-dominator tree* is the dual of the [`DominatorTree`]: it answers
4//! whether every path from a block to a function exit (a `return`, `trap`,
5//! etc.) must pass through some other block.
6//!
7//! It is computed by reusing the ordinary dominator-tree machinery on a
8//! modified version of the control-flow graph:
9//!
10//! * Add a virtual *sink* node.
11//!
12//! * Every block whose terminator does not branch anywhere (`return`,
13//!   `return_call`, `trap`, etc.) is given an edge to the virtual sink.
14//!
15//! * Reverse every edge in the graph, so `a -> b` becomes `b -> a`.
16//!
17//! * Compute the dominator tree of this reversed graph, rooted at the virtual
18//!   sink.
19//!
20//! Note that we don't actually reify this modified version of the control-flow
21//! graph, we instead use the `ReverseGraph` implementation of the
22//! `DomTreeGraph` trait.
23
24use crate::dominator_tree::{ChildIter, DomTreeGraph, DominatorTree};
25use crate::flowgraph::{BlockPredecessor, ControlFlowGraph};
26use crate::ir::{Block, Layout, ProgramPoint};
27use core::cmp::Ordering;
28
29/// The reversed control-flow graph, augmented with a virtual sink above the
30/// function's exit blocks. Computing a `DominatorTree` over this graph yields
31/// the post-dominator tree.
32struct ReverseGraph<'a> {
33    cfg: &'a ControlFlowGraph,
34}
35
36impl DomTreeGraph for ReverseGraph<'_> {
37    fn num_blocks(&self) -> usize {
38        self.cfg.num_blocks()
39    }
40
41    fn roots(&self) -> impl Iterator<Item = Block> {
42        // The roots of the post-dominator forest are the function's exit
43        // blocks: those whose terminator branches nowhere (e.g. `return`,
44        // `return_call`, `trap`, etc...). These are exactly the blocks with no
45        // CFG successors, and they are precisely the blocks with an edge to the
46        // virtual sink.
47        //
48        // `cfg.blocks()` may include blocks not in the layout, but those are
49        // isolated in the graph (no predecessors or successors), so they only
50        // ever appear as trivial single-node roots and never affect the
51        // post-domination of any real block.
52        self.cfg
53            .blocks()
54            .filter(|&block| self.cfg.succ_iter(block).next().is_none())
55    }
56
57    fn successors(&self, block: Block) -> impl Iterator<Item = Block> {
58        // Edges are reversed: a successor in the reversed graph is a
59        // predecessor in the CFG.
60        self.cfg
61            .pred_iter(block)
62            .map(|pred: BlockPredecessor| pred.block)
63    }
64
65    fn predecessors(&self, block: Block) -> impl Iterator<Item = Block> {
66        // Edges are reversed: a predecessor in the reversed graph is a
67        // successor in the CFG.
68        self.cfg.succ_iter(block)
69    }
70}
71
72/// The post-dominator tree for a single function.
73pub struct PostDominatorTree {
74    /// The dominator tree of the reversed CFG. Its "dominates" relation is
75    /// post-domination in the original function.
76    dom_tree: DominatorTree,
77}
78
79impl Default for PostDominatorTree {
80    fn default() -> Self {
81        Self::new()
82    }
83}
84
85impl PostDominatorTree {
86    /// Allocate a new blank post-dominator tree.
87    ///
88    /// Use `compute` to compute the post-dominator tree for a function.
89    pub fn new() -> Self {
90        Self {
91            dom_tree: DominatorTree::new(),
92        }
93    }
94
95    /// Allocate and compute a post-dominator tree.
96    pub fn with_cfg(cfg: &ControlFlowGraph) -> Self {
97        let mut post_domtree = Self::new();
98        post_domtree.compute(cfg);
99        post_domtree
100    }
101
102    /// Reset and compute the post-dominator tree from the control-flow graph
103    /// `cfg`.
104    pub fn compute(&mut self, cfg: &ControlFlowGraph) {
105        debug_assert!(cfg.is_valid());
106        self.dom_tree.compute_from_graph(&ReverseGraph { cfg });
107    }
108
109    /// Clear the data structures used to represent the post-dominator
110    /// tree.
111    ///
112    /// This will leave the tree in a state where `is_valid()` returns `false`.
113    pub fn clear(&mut self) {
114        self.dom_tree.clear();
115    }
116
117    /// Check if the post-dominator tree is in a valid state.
118    ///
119    /// Note that this doesn't perform any kind of validity checks. It simply
120    /// checks if the `compute()` method has been called since the last
121    /// `clear()`. It does not check that the post-dominator tree is consistent
122    /// with the CFG.
123    pub fn is_valid(&self) -> bool {
124        self.dom_tree.is_valid()
125    }
126
127    /// Returns the immediate post-dominator of `block`.
128    ///
129    /// `block_a` is said to *post-dominate* `block_b` if all control-flow paths
130    /// from `block_b` out of this function (via return or trap) must go through
131    /// `block_a`.
132    ///
133    /// The *immediate post-dominator* is the post-dominator that is closest to
134    /// `block`. All other post-dominators also post-dominate the immediate
135    /// post-dominator.
136    ///
137    /// This returns `None` if `block` diverges and cannot exit the function, or
138    /// if `block` directly exits the function (returns or traps).
139    pub fn immediate_post_dominator(&self, block: Block) -> Option<Block> {
140        self.dom_tree.idom(block)
141    }
142
143    /// Returns `true` if every path from `b` out of this function (via return
144    /// or trap) must go through `a`.
145    pub fn post_dominates<A, B>(&self, a: A, b: B, layout: &Layout) -> bool
146    where
147        A: Into<ProgramPoint>,
148        B: Into<ProgramPoint>,
149    {
150        let a = a.into();
151        let b = b.into();
152        match a {
153            ProgramPoint::Block(block_a) => match b {
154                ProgramPoint::Block(block_b) => self.block_post_dominates(block_a, block_b),
155                ProgramPoint::Inst(inst_b) => {
156                    let block_b = layout
157                        .inst_block(inst_b)
158                        .expect("instruction not in layout");
159                    // A block header does not post-dominate a later instruction
160                    // in its own block, but a header does post-dominate
161                    // instructions in blocks that it strictly post-dominates.
162                    block_a != block_b && self.block_post_dominates(block_a, block_b)
163                }
164            },
165            ProgramPoint::Inst(inst_a) => {
166                let block_a: Block = layout
167                    .inst_block(inst_a)
168                    .expect("Instruction not in layout.");
169                match b {
170                    ProgramPoint::Block(block_b) => {
171                        // An instruction post-dominates the header of its own
172                        // block: control reaches the instruction after the
173                        // header.
174                        self.block_post_dominates(block_a, block_b)
175                    }
176                    ProgramPoint::Inst(inst_b) => {
177                        let block_b = layout
178                            .inst_block(inst_b)
179                            .expect("instruction not in layout");
180                        if block_a == block_b {
181                            // Within a block, `a` post-dominates `b` iff `a` is
182                            // at or after `b`.
183                            layout.pp_cmp(a, b) != Ordering::Less
184                        } else {
185                            self.block_post_dominates(block_a, block_b)
186                        }
187                    }
188                }
189            }
190        }
191    }
192
193    /// Returns `true` if every path from `block_b` to a function exit (return
194    /// or trap) must go through `block_a`.
195    ///
196    /// Every block post-dominates itself. If `block_a != block_b` and either
197    /// block diverges, returns `false`.
198    pub fn block_post_dominates(&self, block_a: Block, block_b: Block) -> bool {
199        self.dom_tree.block_dominates(block_a, block_b)
200    }
201
202    /// Get an iterator over the direct children of `block` in the
203    /// post-dominator tree.
204    ///
205    /// These are the blocks whose immediate post-dominator is `block`.
206    pub fn children(&self, block: Block) -> ChildIter<'_> {
207        self.dom_tree.children(block)
208    }
209
210    /// Is function exit (via return or trap) unreachable from the given block?
211    pub fn diverges(&self, block: Block) -> bool {
212        // A block is reachable in the reversed graph iff it can reach a
213        // function exit; if it cannot, then function exit diverges away from
214        // it.
215        !self.dom_tree.is_reachable(block)
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::cursor::{Cursor, FuncCursor};
223    use crate::ir::types::*;
224    use crate::ir::{Function, InstBuilder, TrapCode};
225    use alloc::string::String;
226    use alloc::vec::Vec;
227    use mutatis::{Mutate, check::Check, mutators as m};
228
229    #[test]
230    fn empty() {
231        let func = Function::new();
232        let cfg = ControlFlowGraph::with_function(&func);
233        let pdt = PostDominatorTree::with_cfg(&cfg);
234        assert!(pdt.is_valid());
235    }
236
237    #[test]
238    fn lifecycle() {
239        let mut func = Function::new();
240        let block0 = func.dfg.make_block();
241        let mut cur = FuncCursor::new(&mut func);
242        cur.insert_block(block0);
243        cur.ins().return_(&[]);
244        let cfg = ControlFlowGraph::with_function(cur.func);
245
246        let mut pdt = PostDominatorTree::new();
247        assert!(!pdt.is_valid());
248        pdt.compute(&cfg);
249        assert!(pdt.is_valid());
250        pdt.clear();
251        assert!(!pdt.is_valid());
252        // Recompute after clear.
253        pdt.compute(&cfg);
254        assert!(pdt.is_valid());
255    }
256
257    #[test]
258    fn straight_line() {
259        let mut func = Function::new();
260        let block0 = func.dfg.make_block();
261        let mut cur = FuncCursor::new(&mut func);
262        cur.insert_block(block0);
263        let v0 = cur.ins().iconst(I32, 1);
264        let v1 = cur.ins().iadd(v0, v0);
265        cur.ins().return_(&[]);
266
267        let cfg = ControlFlowGraph::with_function(cur.func);
268        let pdt = PostDominatorTree::with_cfg(&cfg);
269
270        // The single block is an exit, so it has no post-dominator and does not
271        // diverge.
272        assert_eq!(pdt.immediate_post_dominator(block0), None);
273        assert!(pdt.block_post_dominates(block0, block0));
274        assert!(!pdt.diverges(block0));
275
276        // Instruction-level: a later instruction post-dominates an earlier one.
277        let v0_def = cur.func.dfg.value_def(v0).unwrap_inst();
278        let v1_def = cur.func.dfg.value_def(v1).unwrap_inst();
279        assert!(pdt.post_dominates(v1_def, v0_def, &cur.func.layout));
280        assert!(!pdt.post_dominates(v0_def, v1_def, &cur.func.layout));
281        assert!(pdt.post_dominates(v0_def, v0_def, &cur.func.layout));
282    }
283
284    #[test]
285    fn if_else_diamond() {
286        let mut func = Function::new();
287        let block0 = func.dfg.make_block();
288        let block1 = func.dfg.make_block();
289        let block2 = func.dfg.make_block();
290        let join = func.dfg.make_block();
291
292        let mut cur = FuncCursor::new(&mut func);
293
294        cur.insert_block(block0);
295        let v0 = cur.ins().iconst(I32, 0);
296        cur.ins().brif(v0, block1, &[], block2, &[]);
297
298        cur.insert_block(block1);
299        cur.ins().jump(join, &[]);
300
301        cur.insert_block(block2);
302        cur.ins().jump(join, &[]);
303
304        cur.insert_block(join);
305        cur.ins().return_(&[]);
306
307        let cfg = ControlFlowGraph::with_function(cur.func);
308        let pdt = PostDominatorTree::with_cfg(&cfg);
309
310        // Every path out of the function passes through `join`.
311        assert_eq!(pdt.immediate_post_dominator(block0), Some(join));
312        assert_eq!(pdt.immediate_post_dominator(block1), Some(join));
313        assert_eq!(pdt.immediate_post_dominator(block2), Some(join));
314        assert_eq!(pdt.immediate_post_dominator(join), None);
315
316        assert!(pdt.block_post_dominates(join, block0));
317        assert!(pdt.block_post_dominates(join, block1));
318        // An arm does not post-dominate the entry (the other arm avoids it).
319        assert!(!pdt.block_post_dominates(block1, block0));
320        assert!(!pdt.block_post_dominates(block2, block0));
321        // The entry does not post-dominate the join.
322        assert!(!pdt.block_post_dominates(block0, join));
323
324        for block in [block0, block1, block2, join] {
325            assert!(!pdt.diverges(block));
326        }
327
328        // Cross-block `post_dominates` with instruction/block endpoints.
329        let layout = &cur.func.layout;
330        let entry_term = layout.last_inst(block0).unwrap();
331        let join_term = layout.last_inst(join).unwrap();
332        // The join's terminator post-dominates the entry's terminator...
333        assert!(pdt.post_dominates(join_term, entry_term, layout));
334        // ...but not vice versa.
335        assert!(!pdt.post_dominates(entry_term, join_term, layout));
336        // Block/instruction mixes across blocks defer to block post-domination.
337        assert!(pdt.post_dominates(join, entry_term, layout));
338        assert!(!pdt.post_dominates(entry_term, join, layout));
339
340        // `join` post-dominates the three other blocks.
341        let mut kids = pdt.children(join).collect::<alloc::vec::Vec<_>>();
342        kids.sort();
343        assert_eq!(kids, [block0, block1, block2]);
344    }
345
346    #[test]
347    fn terminating_loop() {
348        let mut func = Function::new();
349        let entry = func.dfg.make_block();
350        let header = func.dfg.make_block();
351        let body = func.dfg.make_block();
352        let exit = func.dfg.make_block();
353
354        let mut cur = FuncCursor::new(&mut func);
355
356        cur.insert_block(entry);
357        cur.ins().jump(header, &[]);
358        cur.insert_block(header);
359        let v0 = cur.ins().iconst(I32, 0);
360        cur.ins().brif(v0, body, &[], exit, &[]);
361
362        cur.insert_block(body);
363        cur.ins().jump(header, &[]);
364        cur.insert_block(exit);
365        cur.ins().return_(&[]);
366
367        let cfg = ControlFlowGraph::with_function(cur.func);
368        let pdt = PostDominatorTree::with_cfg(&cfg);
369
370        assert_eq!(pdt.immediate_post_dominator(entry), Some(header));
371        assert_eq!(pdt.immediate_post_dominator(header), Some(exit));
372        assert_eq!(pdt.immediate_post_dominator(body), Some(header));
373        assert_eq!(pdt.immediate_post_dominator(exit), None);
374
375        assert!(pdt.block_post_dominates(exit, entry));
376        assert!(pdt.block_post_dominates(exit, body));
377        assert!(pdt.block_post_dominates(header, body));
378        assert!(!pdt.block_post_dominates(body, header));
379
380        // The loop can always exit, so nothing diverges.
381        for block in [entry, header, body, exit] {
382            assert!(!pdt.diverges(block));
383        }
384    }
385
386    #[test]
387    fn infinite_loop() {
388        let mut func = Function::new();
389        let block0 = func.dfg.make_block();
390        let mut cur = FuncCursor::new(&mut func);
391        cur.insert_block(block0);
392        cur.ins().jump(block0, &[]);
393
394        let cfg = ControlFlowGraph::with_function(cur.func);
395        let pdt = PostDominatorTree::with_cfg(&cfg);
396
397        // There is no exit block, so the function never returns: every block
398        // diverges and has no post-dominator.
399        assert!(pdt.is_valid());
400        assert!(pdt.diverges(block0));
401        assert_eq!(pdt.immediate_post_dominator(block0), None);
402    }
403
404    #[test]
405    fn infinite_loop_with_side_exit() {
406        let mut func = Function::new();
407        let entry = func.dfg.make_block();
408        let header = func.dfg.make_block();
409        let body = func.dfg.make_block();
410        let exit = func.dfg.make_block();
411
412        let mut cur = FuncCursor::new(&mut func);
413
414        cur.insert_block(entry);
415        cur.ins().jump(header, &[]);
416
417        cur.insert_block(header);
418        let v0 = cur.ins().iconst(I32, 0);
419        cur.ins().brif(v0, exit, &[], body, &[]);
420
421        // `body` loops forever and never reaches an exit.
422        cur.insert_block(body);
423        cur.ins().jump(body, &[]);
424
425        cur.insert_block(exit);
426        cur.ins().return_(&[]);
427
428        let cfg = ControlFlowGraph::with_function(cur.func);
429        let pdt = PostDominatorTree::with_cfg(&cfg);
430
431        // Only `body` diverges.
432        assert!(pdt.diverges(body));
433        assert_eq!(pdt.immediate_post_dominator(body), None);
434
435        assert!(!pdt.diverges(entry));
436        assert!(!pdt.diverges(header));
437        assert!(!pdt.diverges(exit));
438        assert_eq!(pdt.immediate_post_dominator(header), Some(exit));
439        assert_eq!(pdt.immediate_post_dominator(entry), Some(header));
440        assert_eq!(pdt.immediate_post_dominator(exit), None);
441    }
442
443    #[test]
444    fn multiple_returns() {
445        let mut func = Function::new();
446        let entry = func.dfg.make_block();
447        let block1 = func.dfg.make_block();
448        let block2 = func.dfg.make_block();
449
450        let mut cur = FuncCursor::new(&mut func);
451
452        cur.insert_block(entry);
453        let v0 = cur.ins().iconst(I32, 0);
454        cur.ins().brif(v0, block1, &[], block2, &[]);
455
456        cur.insert_block(block1);
457        cur.ins().return_(&[]);
458
459        cur.insert_block(block2);
460        cur.ins().return_(&[]);
461
462        let cfg = ControlFlowGraph::with_function(cur.func);
463        let pdt = PostDominatorTree::with_cfg(&cfg);
464
465        // Two distinct exit blocks: neither post-dominates the entry, and the
466        // entry's only post-dominator is the (virtual) sink.
467        assert_eq!(pdt.immediate_post_dominator(block1), None);
468        assert_eq!(pdt.immediate_post_dominator(block2), None);
469        assert_eq!(pdt.immediate_post_dominator(entry), None);
470
471        assert!(!pdt.block_post_dominates(block1, entry));
472        assert!(!pdt.block_post_dominates(block2, entry));
473
474        // Blocks in distinct exit subtrees do not post-dominate each other.
475        assert!(!pdt.block_post_dominates(block1, block2));
476        assert!(!pdt.block_post_dominates(block2, block1));
477
478        for block in [entry, block1, block2] {
479            assert!(!pdt.diverges(block));
480        }
481    }
482
483    #[test]
484    fn trap_as_exit() {
485        let mut func = Function::new();
486        let entry = func.dfg.make_block();
487        let ret_block = func.dfg.make_block();
488        let trap_block = func.dfg.make_block();
489
490        let mut cur = FuncCursor::new(&mut func);
491
492        cur.insert_block(entry);
493        let v0 = cur.ins().iconst(I32, 0);
494        cur.ins().brif(v0, ret_block, &[], trap_block, &[]);
495
496        cur.insert_block(ret_block);
497        cur.ins().return_(&[]);
498
499        cur.insert_block(trap_block);
500        cur.ins().trap(TrapCode::unwrap_user(1));
501
502        let cfg = ControlFlowGraph::with_function(cur.func);
503        let pdt = PostDominatorTree::with_cfg(&cfg);
504
505        // A `trap` is a function exit, so `trap_block` is a root of the forest
506        // and does not diverge.
507        assert_eq!(pdt.immediate_post_dominator(trap_block), None);
508        assert_eq!(pdt.immediate_post_dominator(ret_block), None);
509        assert_eq!(pdt.immediate_post_dominator(entry), None);
510
511        assert!(!pdt.diverges(trap_block));
512        assert!(!pdt.diverges(ret_block));
513        assert!(!pdt.diverges(entry));
514    }
515
516    #[test]
517    fn insts_post_dominate_same_block() {
518        let mut func = Function::new();
519        let block0 = func.dfg.make_block();
520
521        let mut cur = FuncCursor::new(&mut func);
522        cur.insert_block(block0);
523        let v1 = cur.ins().iconst(I32, 1);
524        let v2 = cur.ins().iadd(v1, v1);
525        let v3 = cur.ins().iadd(v2, v2);
526        cur.ins().return_(&[]);
527
528        let cfg = ControlFlowGraph::with_function(cur.func);
529        let pdt = PostDominatorTree::with_cfg(&cfg);
530
531        let v1_def = cur.func.dfg.value_def(v1).unwrap_inst();
532        let v2_def = cur.func.dfg.value_def(v2).unwrap_inst();
533        let v3_def = cur.func.dfg.value_def(v3).unwrap_inst();
534        let layout = &cur.func.layout;
535
536        // Later instructions post-dominate earlier ones.
537        assert!(pdt.post_dominates(v2_def, v1_def, layout));
538        assert!(pdt.post_dominates(v3_def, v1_def, layout));
539        assert!(pdt.post_dominates(v3_def, v2_def, layout));
540
541        // Earlier instructions do not post-dominate later ones.
542        assert!(!pdt.post_dominates(v1_def, v2_def, layout));
543        assert!(!pdt.post_dominates(v1_def, v3_def, layout));
544
545        // An instruction post-dominates itself.
546        assert!(pdt.post_dominates(v2_def, v2_def, layout));
547
548        // An instruction post-dominates the header of its own block...
549        assert!(pdt.post_dominates(v1_def, block0, layout));
550        // ...but a block header does not post-dominate a later instruction in
551        // its own block.
552        assert!(!pdt.post_dominates(block0, v1_def, layout));
553
554        // A block post-dominates itself.
555        assert!(pdt.post_dominates(block0, block0, layout));
556    }
557
558    /// Property-based test against a brute-force oracle.
559    ///
560    /// We mutate a small abstract control-flow graph with `mutatis`, build a
561    /// corresponding Cranelift function, and compare the `PostDominatorTree`
562    /// against an independent post-dominance dataflow computed on the abstract
563    /// graph.
564    #[test]
565    fn post_dominators_match_oracle() -> mutatis::check::CheckResult<GraphSpec> {
566        use Terminator::*;
567
568        let corpus = [
569            // Straight-line: a single returning block.
570            GraphSpec {
571                blocks: alloc::vec![Return],
572            },
573            // Straight-line: chained jumps and a return.
574            GraphSpec {
575                blocks: alloc::vec![Jump(1), Jump(2), Return],
576            },
577            // If-else diamond.
578            GraphSpec {
579                blocks: alloc::vec![Brif(1, 2), Jump(3), Jump(3), Return],
580            },
581            // Terminating loop.
582            GraphSpec {
583                blocks: alloc::vec![Jump(1), Brif(1, 2), Return],
584            },
585            // Infinite loop.
586            GraphSpec {
587                blocks: alloc::vec![Jump(1), Jump(0)],
588            },
589        ];
590
591        Check::new()
592            .iters(10_000)
593            .run_with(m::default::<GraphSpec>(), corpus, check_post_dominance)
594    }
595
596    /// Cap on the number of blocks we build, so node indices (plus the virtual
597    /// sink) fit in a `u64` bitmask.
598    const MAX_BLOCKS: usize = 12;
599
600    /// Description of a whole control-flow graph.
601    #[derive(Clone, Debug, Default, Mutate)]
602    struct GraphSpec {
603        blocks: Vec<Terminator>,
604    }
605
606    impl GraphSpec {
607        fn fixup(&self) -> Option<Self> {
608            let n = self.blocks.len().min(MAX_BLOCKS);
609            if n == 0 {
610                return None;
611            }
612            let mut graph = GraphSpec {
613                blocks: self.blocks[..n].to_vec(),
614            };
615            for terminator in &mut graph.blocks {
616                terminator.fixup(n);
617            }
618            Some(graph)
619        }
620
621        /// Build a Cranelift function realizing `terminators`. Block 0 is the entry.
622        fn build(&self) -> (Function, Vec<Block>) {
623            let mut func = Function::new();
624
625            let blocks: Vec<Block> = (0..self.blocks.len())
626                .map(|_| func.dfg.make_block())
627                .collect();
628
629            let mut cur = FuncCursor::new(&mut func);
630            for (i, terminator) in self.blocks.iter().enumerate() {
631                cur.insert_block(blocks[i]);
632                match *terminator {
633                    Terminator::Return => {
634                        cur.ins().return_(&[]);
635                    }
636                    Terminator::Jump(t) => {
637                        cur.ins().jump(blocks[t], &[]);
638                    }
639                    Terminator::Brif(t1, t2) => {
640                        let c = cur.ins().iconst(I32, 0);
641                        cur.ins().brif(c, blocks[t1], &[], blocks[t2], &[]);
642                    }
643                }
644            }
645            (func, blocks)
646        }
647    }
648
649    /// A block's terminator.
650    #[derive(Clone, Copy, Debug, Default, Mutate)]
651    enum Terminator {
652        #[default]
653        Return,
654        Jump(usize),
655        Brif(usize, usize),
656    }
657
658    impl Terminator {
659        fn fixup(&mut self, n: usize) {
660            match self {
661                Self::Return => {}
662                Self::Jump(a) => {
663                    *a %= n;
664                }
665                Self::Brif(a, b) => {
666                    *a %= n;
667                    *b %= n;
668                }
669            }
670        }
671    }
672
673    /// Check that the `PostDominatorTree` agrees with a brute-force
674    /// post-dominance dataflow on the abstract graph.
675    fn check_post_dominance(graph: &GraphSpec) -> Result<(), String> {
676        let Some(graph) = graph.fixup() else {
677            return Ok(());
678        };
679
680        let (func, blocks) = graph.build();
681        let cfg = ControlFlowGraph::with_function(&func);
682        let pdt = PostDominatorTree::with_cfg(&cfg);
683
684        // The virtual sink is node `n`. Exit blocks have an edge to it.
685        let sink = graph.blocks.len();
686        let succ: Vec<Vec<usize>> = graph
687            .blocks
688            .iter()
689            .map(|t| match *t {
690                Terminator::Return => alloc::vec![sink],
691                Terminator::Jump(x) => alloc::vec![x],
692                Terminator::Brif(x, y) => alloc::vec![x, y],
693            })
694            .collect();
695
696        // Which nodes can reach the sink? Those that cannot are the diverging
697        // blocks. Post-domination is only well-defined for the rest.
698        let mut reaches = alloc::vec![false; graph.blocks.len() + 1];
699        reaches[sink] = true;
700        loop {
701            let mut changed = false;
702            for i in 0..graph.blocks.len() {
703                if !reaches[i] && succ[i].iter().any(|&s| reaches[s]) {
704                    reaches[i] = true;
705                    changed = true;
706                }
707            }
708            if !changed {
709                break;
710            }
711        }
712
713        // Post-dominance sets as bitmasks over node indices `0..=sink`, via the
714        // greatest fixpoint of `pdom(i) = {i} ∪ ⋂_{s ∈ succ(i)} pdom(s)`.
715        let bit = |x: usize| 1u64 << x;
716        let universe = bit(graph.blocks.len() + 1) - 1;
717        let mut pdom = alloc::vec![universe; graph.blocks.len() + 1];
718        pdom[sink] = bit(sink);
719        loop {
720            let mut changed = false;
721            for i in 0..graph.blocks.len() {
722                let mut inter = u64::MAX;
723                for &s in &succ[i] {
724                    inter &= pdom[s];
725                }
726                let next = bit(i) | inter;
727                if next != pdom[i] {
728                    pdom[i] = next;
729                    changed = true;
730                }
731            }
732            if !changed {
733                break;
734            }
735        }
736
737        for i in 0..graph.blocks.len() {
738            let expect_diverges = !reaches[i];
739            if pdt.diverges(blocks[i]) != expect_diverges {
740                return Err(format!(
741                    "diverges({i}) = {}, expected {expect_diverges}",
742                    pdt.diverges(blocks[i]),
743                ));
744            }
745
746            // Diverging blocks only post-dominate themselves (`pdom[i]` stays `universe` when
747            // block `i` cannot reach the sink).
748            for a in 0..graph.blocks.len() {
749                let expect = if expect_diverges {
750                    a == i
751                } else {
752                    pdom[i] & bit(a) != 0
753                };
754                if pdt.block_post_dominates(blocks[a], blocks[i]) != expect {
755                    return Err(format!(
756                        "block_post_dominates({a}, {i}) = {}, expected {expect}",
757                        pdt.block_post_dominates(blocks[a], blocks[i]),
758                    ));
759                }
760            }
761
762            if expect_diverges {
763                if pdt.immediate_post_dominator(blocks[i]).is_some() {
764                    return Err(format!(
765                        "immediate_post_dominator({i}) should be None for a diverging block;",
766                    ));
767                }
768                continue;
769            }
770
771            // The immediate post-dominator is the strict post-dominator with
772            // the largest post-dominator set (i.e. closest to `i`). The
773            // post-dominators form a chain to the sink with strictly decreasing
774            // set sizes, so this is unique. The virtual sink maps to `None`.
775            let strict = pdom[i] & !bit(i);
776            let mut best: Option<(u32, usize)> = None;
777            for x in 0..=graph.blocks.len() {
778                if strict & bit(x) != 0 {
779                    let size = pdom[x].count_ones();
780                    if best.map_or(true, |(best_size, _)| size > best_size) {
781                        best = Some((size, x));
782                    }
783                }
784            }
785            let expect_ipdom = match best {
786                Some((_, x)) if x != sink => Some(blocks[x]),
787                _ => None,
788            };
789            if pdt.immediate_post_dominator(blocks[i]) != expect_ipdom {
790                return Err(format!(
791                    "immediate_post_dominator({i}) = {:?}, expected {expect_ipdom:?}",
792                    pdt.immediate_post_dominator(blocks[i]),
793                ));
794            }
795        }
796
797        Ok(())
798    }
799}