Skip to main content

graphity_controlflow/
iterated_dominance_frontier.rs

1use graphity_core::{BiAdjacentGraph, Dominators, NONE, SortedIntView, csr, graphs};
2
3use crate::error::check_index;
4use crate::growth;
5use crate::int_hash_set::IntHashSet;
6
7/// The iterated dominance frontiers of a control-flow graph, which tell where SSA (static single
8/// assignment) form places phi-nodes.
9///
10/// In SSA form, every assignment to a variable creates a new version of it, and a phi-node merges the
11/// versions where paths of control flow meet. The phi-nodes of a variable go into the iterated
12/// dominance frontier of the blocks that assign it: the dominance frontier of these blocks, then the
13/// dominance frontier of the result, and so on until nothing new is added. A compiler asks this once
14/// per variable, so [`of`](Self::of) prepares the queries once per control-flow graph, and
15/// [`frontier_of`](Self::frontier_of) answers them. Here, for the loop variable `i` of a method
16/// `load`, whose control flow `cfg` has the blocks `entry` and `next`:
17///
18/// <!-- example: analyzing_control_flow.rs#frontierOf -->
19/// ```
20/// # use graphity_core::{BiAdjacentGraph, Dominators};
21/// # use graphity_controlflow::IteratedDominanceFrontier;
22/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
23/// # let (entry, next) = (0, 4);
24/// let dominators = Dominators::of(&BiAdjacentGraph::of(&cfg), entry);
25/// let phis = IteratedDominanceFrontier::of(&dominators);
26/// // i is assigned in entry (let mut i = 0) and in next (i += 1)
27/// let phi_blocks = phis.frontier_of(&[entry, next]);
28/// // phi_blocks: [1] - header
29/// # assert_eq!(phi_blocks, [1]);
30/// ```
31///
32/// Uses the algorithm of Sreedhar and Gao. A query walks the subtrees of the dominator tree below the
33/// nodes it is given and the nodes it adds, so its cost depends on the part of the graph it explores,
34/// not on the whole graph. It never builds the dominance frontiers themselves, which can grow
35/// quadratically with the node count;
36/// [`control_flow::dominance_frontiers`](crate::control_flow::dominance_frontiers) returns them as a
37/// graph.
38///
39/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
40///
41/// **Memory:** 16 x node_count bytes, plus the graph of the [`Dominators`], whose arrays it shares -
42/// Java keeps the `Dominators` themselves reachable.
43#[derive(Debug, Clone)]
44pub struct IteratedDominanceFrontier {
45    /// The analyzed graph, shared with the dominators; Java keeps the `Dominators` and reads its
46    /// graph per query.
47    graph: BiAdjacentGraph,
48    /// Depth of each node in the dominator forest, 0 for a root, [`NONE`] if unreachable.
49    depth: Box<[u32]>,
50    /// Position of each node in the preorder of the dominator forest.
51    preorder_index: Box<[u32]>,
52    /// Size of each node's subtree in the dominator forest, the node included.
53    subtree_size: Box<[u32]>,
54    /// Node at each preorder position.
55    order: Box<[u32]>,
56}
57
58impl IteratedDominanceFrontier {
59    /// Returns the iterated dominance frontiers of the graph that `dominators` were computed on, ready for
60    /// queries.
61    ///
62    /// They are prepared anew on every call, not cached: keep the result and query it for every variable.
63    ///
64    /// **Time:** O(node_count).
65    /// **Memory:** 16 x node_count bytes for the result; while it runs, 8 x node_count bytes more.
66    pub fn of(dominators: &Dominators) -> IteratedDominanceFrontier {
67        let tree = graphs::dominator_tree(dominators);
68        let n = tree.node_count() as usize;
69        let child_start = csr::out_adjacency_start(&tree);
70        let children = csr::out_adjacency(&tree);
71        let mut preorder_index = vec![0u32; n];
72        let mut order = vec![0u32; n];
73        let mut subtree_size = vec![0u32; n];
74        let mut depth = vec![0u32; n];
75
76        // Canonical preorder - roots ascending, children ascending - as the preorder of the
77        // core's parent forest computes it; change both together. Every node is pushed exactly
78        // once, so the stack fits in n slots; the subtree-size array serves as the stack until it
79        // is filled below. Preorder visits every parent before its children, so depth follows on
80        // the way.
81        let stack = &mut subtree_size;
82        let mut top = 0usize;
83        for node in (0..n as u32).rev() {
84            if dominators.immediate_dominator_of(node).is_none() {
85                stack[top] = node;
86                top += 1;
87                depth[node as usize] = if dominators.is_reachable(node) {
88                    0
89                } else {
90                    NONE
91                };
92            }
93        }
94        let mut position = 0u32;
95        while top > 0 {
96            top -= 1;
97            let node = stack[top] as usize;
98            preorder_index[node] = position;
99            order[position as usize] = node as u32;
100            position += 1;
101            for &child in children[child_start[node] as usize..child_start[node + 1] as usize]
102                .iter()
103                .rev()
104            {
105                depth[child as usize] = depth[node] + 1;
106                stack[top] = child;
107                top += 1;
108            }
109        }
110
111        // Reverse preorder visits every child before its parent.
112        subtree_size.fill(1);
113        for &node in order.iter().rev() {
114            if let Some(p) = dominators.immediate_dominator_of(node) {
115                subtree_size[p as usize] += subtree_size[node as usize];
116            }
117        }
118        IteratedDominanceFrontier {
119            graph: dominators.graph().clone(),
120            depth: depth.into(),
121            preorder_index: preorder_index.into(),
122            subtree_size: subtree_size.into(),
123            order: order.into(),
124        }
125    }
126
127    /// Returns the iterated dominance frontier of `nodes`, in ascending order.
128    ///
129    /// The result can contain given nodes, such as the header of a natural loop, which is in its own
130    /// dominance frontier. Nodes that the entries do not reach are ignored, and so are duplicates. The
131    /// result owns its array.
132    ///
133    /// **Time:** O(nodes.len() + e + (s + k) log(s + k)), where e is the number of nodes and edges the
134    /// query explores, at most node_count + edge_count; s is the number of distinct given nodes that the
135    /// entries reach, and k the size of the result.
136    /// **Memory:** 4 x k bytes for the result; while it runs, up to about 60 bytes per node the query
137    /// explores, and nothing sized by the whole graph.
138    ///
139    /// # Panics
140    /// With an `index out of bounds` message if a node is not in `0..node_count`; with an
141    /// `invalid argument` message if the query explores more than about 8 x 10^8 nodes.
142    #[track_caller]
143    pub fn frontier_of(&self, nodes: &[u32]) -> SortedIntView<'static> {
144        let n = self.depth.len();
145        let depth = &self.depth;
146        // Sized by a capped guess and grown on demand, so that duplicates and unreachable nodes in
147        // a long input cost no scratch space.
148        let initial = nodes.len().clamp(4, 1024);
149        let mut given = IntHashSet::with_expected(initial as u32);
150        let mut heap = DepthHeap::with_capacity(initial, n);
151        for &node in nodes {
152            check_index(node, n);
153            if depth[node as usize] == NONE || !given.add(node) {
154                continue;
155            }
156            heap.push(depth[node as usize], node);
157        }
158
159        let out = csr::out_adjacency_start(&self.graph);
160        let adj = csr::out_adjacency(&self.graph);
161        let mut in_frontier = IntHashSet::with_expected(DEFAULT_EXPECTED);
162        let mut walked = IntHashSet::with_expected(DEFAULT_EXPECTED);
163        let mut result: Vec<u32> = Vec::new();
164
165        // Deepest root first. A subtree walked once need not be walked again for a shallower
166        // root: every edge it could contribute leaves no deeper than the earlier root, and was
167        // taken then. Walked parts are closed under descendants, so the scan skips each one in a
168        // single step.
169        while let Some((root_depth, root)) = heap.pop() {
170            let mut position = self.preorder_index[root as usize];
171            let end = position + self.subtree_size[root as usize];
172            while position < end {
173                let x = self.order[position as usize];
174                if !walked.add(x) {
175                    position += self.subtree_size[x as usize];
176                    continue;
177                }
178                for &y in &adj[out[x as usize] as usize..out[x as usize + 1] as usize] {
179                    // Targets deeper than the root lie strictly inside its subtree and fall out
180                    // here; what remains - the root itself or a node beyond its subtree - is in
181                    // its frontier.
182                    let y_depth = depth[y as usize];
183                    if y_depth > root_depth || !in_frontier.add(y) {
184                        continue;
185                    }
186                    growth::push(&mut result, y);
187                    if !given.contains(y) {
188                        heap.push(y_depth, y);
189                    }
190                }
191                position += 1;
192            }
193        }
194
195        // Exactly k values, as Java's toIntArray.
196        result.shrink_to_fit();
197        result.sort_unstable();
198        SortedIntView::from_vec(result).expect("the frontier holds every node once")
199    }
200}
201
202/// The initial capacity of fastutil's `IntOpenHashSet()`, for the sets without a size guess.
203const DEFAULT_EXPECTED: u32 = 16;
204
205/// A binary max-heap of `(depth, node)` pairs, interleaved in one array as in Java.
206struct DepthHeap {
207    /// `(key, node)` per entry.
208    entries: Vec<u32>,
209    /// Number of entries.
210    size: usize,
211    /// Every node enters at most once, so the array never needs more than two slots per node of
212    /// the graph, and the growth is capped there instead of doubling past it.
213    max_len: usize,
214}
215
216impl DepthHeap {
217    fn with_capacity(capacity: usize, node_count: usize) -> Self {
218        Self {
219            entries: vec![0; 2 * capacity],
220            size: 0,
221            max_len: 2 * node_count,
222        }
223    }
224
225    /// Adds `(key, node)`, growing the array if needed.
226    fn push(&mut self, key: u32, node: u32) {
227        let heap = &mut self.entries;
228        if 2 * (self.size + 1) > heap.len() {
229            let grown = (2 * heap.len()).min(self.max_len);
230            // Exactly `grown`, as Java's Arrays.copyOf: resize alone rounds up to a doubling.
231            heap.reserve_exact(grown - heap.len());
232            heap.resize(grown, 0);
233        }
234        let mut i = self.size;
235        self.size += 1;
236        while i > 0 {
237            let parent = (i - 1) >> 1;
238            if heap[2 * parent] >= key {
239                break;
240            }
241            heap[2 * i] = heap[2 * parent];
242            heap[2 * i + 1] = heap[2 * parent + 1];
243            i = parent;
244        }
245        heap[2 * i] = key;
246        heap[2 * i + 1] = node;
247    }
248
249    /// Removes the entry with the largest key and returns it, or `None` if the heap is empty.
250    fn pop(&mut self) -> Option<(u32, u32)> {
251        if self.size == 0 {
252            return None;
253        }
254        let heap = &mut self.entries;
255        let top = (heap[0], heap[1]);
256        let last = self.size - 1;
257        let key = heap[2 * last];
258        let node = heap[2 * last + 1];
259        let mut i = 0usize;
260        loop {
261            let mut child = 2 * i + 1;
262            if child >= last {
263                break;
264            }
265            if child + 1 < last && heap[2 * (child + 1)] > heap[2 * child] {
266                child += 1;
267            }
268            if heap[2 * child] <= key {
269                break;
270            }
271            heap[2 * i] = heap[2 * child];
272            heap[2 * i + 1] = heap[2 * child + 1];
273            i = child;
274        }
275        heap[2 * i] = key;
276        heap[2 * i + 1] = node;
277        self.size = last;
278        Some(top)
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn the_heap_pops_the_deepest_first() {
288        let mut heap = DepthHeap::with_capacity(1, 8);
289        for (key, node) in [(2, 20), (5, 50), (1, 10), (7, 70), (3, 30), (5, 51), (0, 0)] {
290            heap.push(key, node);
291        }
292        let mut keys = Vec::new();
293        while let Some((key, node)) = heap.pop() {
294            assert_eq!(node / 10, key);
295            keys.push(key);
296        }
297        assert_eq!(keys, [7, 5, 5, 3, 2, 1, 0]);
298    }
299
300    #[test]
301    fn the_heap_grows_to_two_slots_per_node_and_no_further() {
302        let mut heap = DepthHeap::with_capacity(4, 5);
303        for node in 0..5 {
304            heap.push(node, node);
305        }
306        assert_eq!(heap.entries.len(), 10);
307        assert_eq!(heap.pop(), Some((4, 4)));
308    }
309}