Skip to main content

dfir_lang/graph/
flat_to_partitioned.rs

1//! Subgraph partioning algorithm
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use proc_macro2::Span;
6use slotmap::{SecondaryMap, SparseSecondaryMap};
7
8use super::meta_graph::DfirGraph;
9use super::ops::{DelayType, FloType};
10use super::{Color, GraphEdgeId, GraphNode, GraphNodeId, GraphSubgraphId, graph_algorithms};
11use crate::diagnostic::{Diagnostic, Level};
12use crate::union_find::UnionFind;
13
14/// Helper struct for tracking barrier crossers, see [`find_barrier_crossers`].
15struct BarrierCrossers {
16    /// Edge barrier crossers, including what type.
17    pub edge_barrier_crossers: SecondaryMap<GraphEdgeId, DelayType>,
18    /// Singleton reference barrier crossers, considered to be [`DelayType::Stratum`].
19    pub singleton_barrier_crossers: Vec<(GraphNodeId, GraphNodeId)>,
20}
21impl BarrierCrossers {
22    /// Iterate pairs of nodes that are across a barrier. Excludes `DelayType::NextIteration` pairs.
23    fn iter_node_pairs<'a>(
24        &'a self,
25        partitioned_graph: &'a DfirGraph,
26    ) -> impl 'a + Iterator<Item = ((GraphNodeId, GraphNodeId), DelayType)> {
27        let edge_pairs_iter = self
28            .edge_barrier_crossers
29            .iter()
30            .map(|(edge_id, &delay_type)| {
31                let src_dst = partitioned_graph.edge(edge_id);
32                (src_dst, delay_type)
33            });
34        let singleton_pairs_iter = self
35            .singleton_barrier_crossers
36            .iter()
37            .map(|&src_dst| (src_dst, DelayType::Stratum));
38        edge_pairs_iter.chain(singleton_pairs_iter)
39    }
40
41    /// Insert/replace edge.
42    fn replace_edge(&mut self, old_edge_id: GraphEdgeId, new_edge_id: GraphEdgeId) {
43        if let Some(delay_type) = self.edge_barrier_crossers.remove(old_edge_id) {
44            self.edge_barrier_crossers.insert(new_edge_id, delay_type);
45        }
46    }
47}
48
49/// Find all the barrier crossers.
50fn find_barrier_crossers(partitioned_graph: &DfirGraph) -> BarrierCrossers {
51    let edge_barrier_crossers = partitioned_graph
52        .edges()
53        .filter(|&(_, (_src, dst))| {
54            // Ignore barriers within `loop {` blocks.
55            partitioned_graph.node_loop(dst).is_none()
56        })
57        .filter_map(|(edge_id, (_src, dst))| {
58            let (_src_port, dst_port) = partitioned_graph.edge_ports(edge_id);
59            let op_constraints = partitioned_graph.node_op_inst(dst)?.op_constraints;
60            let input_barrier = (op_constraints.input_delaytype_fn)(dst_port)?;
61            Some((edge_id, input_barrier))
62        })
63        .collect();
64    let singleton_barrier_crossers = partitioned_graph
65        .node_ids()
66        .flat_map(|dst| {
67            partitioned_graph
68                .node_singleton_references(dst)
69                .iter()
70                .flatten()
71                .map(move |&src_ref| (src_ref, dst))
72        })
73        .collect();
74    BarrierCrossers {
75        edge_barrier_crossers,
76        singleton_barrier_crossers,
77    }
78}
79
80fn find_subgraph_unionfind(
81    partitioned_graph: &DfirGraph,
82    barrier_crossers: &BarrierCrossers,
83) -> (UnionFind<GraphNodeId>, BTreeSet<GraphEdgeId>) {
84    // Modality (color) of nodes, push or pull.
85    // TODO(mingwei)? This does NOT consider `DelayType` barriers (which generally imply `Pull`),
86    // which makes it inconsistant with the final output in `as_code()`. But this doesn't create
87    // any bugs since we exclude `DelayType` edges from joining subgraphs anyway.
88    let mut node_color = partitioned_graph
89        .node_ids()
90        .filter_map(|node_id| {
91            let op_color = partitioned_graph.node_color(node_id)?;
92            Some((node_id, op_color))
93        })
94        .collect::<SparseSecondaryMap<_, _>>();
95
96    let mut subgraph_unionfind: UnionFind<GraphNodeId> =
97        UnionFind::with_capacity(partitioned_graph.nodes().len());
98
99    // Will contain all edges which are handoffs. Starts out with all edges and
100    // we remove from this set as we combine nodes into subgraphs.
101    let mut handoff_edges: BTreeSet<GraphEdgeId> = partitioned_graph.edge_ids().collect();
102    // Would sort edges here for priority (for now, no sort/priority).
103
104    // Each edge gets looked at in order. However we may not know if a linear
105    // chain of operators is PUSH vs PULL until we look at the ends. A fancier
106    // algorithm would know to handle linear chains from the outside inward.
107    // But instead we just run through the edges in a loop until no more
108    // progress is made. Could have some sort of O(N^2) pathological worst
109    // case.
110    let mut progress = true;
111    while progress {
112        progress = false;
113        // TODO(mingwei): Could this iterate `handoff_edges` instead? (Modulo ownership). Then no case (1) below.
114        for (edge_id, (src, dst)) in partitioned_graph.edges().collect::<Vec<_>>() {
115            // Ignore (1) already added edges as well as (2) new self-cycles. (Unless reference edge).
116            if subgraph_unionfind.same_set(src, dst) {
117                // Note that the _edge_ `edge_id` might not be in the subgraph even when both `src` and `dst` are. This prevents case 2.
118                // Handoffs will be inserted later for this self-loop.
119                continue;
120            }
121
122            // Do not connect stratum crossers (next edges).
123            if barrier_crossers
124                .iter_node_pairs(partitioned_graph)
125                .any(|((x_src, x_dst), _)| {
126                    (subgraph_unionfind.same_set(x_src, src)
127                        && subgraph_unionfind.same_set(x_dst, dst))
128                        || (subgraph_unionfind.same_set(x_src, dst)
129                            && subgraph_unionfind.same_set(x_dst, src))
130                })
131            {
132                continue;
133            }
134
135            // Do not connect across loop contexts.
136            if partitioned_graph.node_loop(src) != partitioned_graph.node_loop(dst) {
137                continue;
138            }
139            // Do not connect `next_iteration()`.
140            if partitioned_graph.node_op_inst(dst).is_some_and(|op_inst| {
141                Some(FloType::NextIteration) == op_inst.op_constraints.flo_type
142            }) {
143                continue;
144            }
145
146            if can_connect_colorize(&mut node_color, src, dst) {
147                // At this point we have selected this edge and its src & dst to be
148                // within a single subgraph.
149                subgraph_unionfind.union(src, dst);
150                assert!(handoff_edges.remove(&edge_id));
151                progress = true;
152            }
153        }
154    }
155
156    (subgraph_unionfind, handoff_edges)
157}
158
159/// Builds the datastructures for checking which subgraph each node belongs to
160/// after handoffs have already been inserted to partition subgraphs.
161/// This list of nodes in each subgraph are returned in topological sort order.
162fn make_subgraph_collect(
163    partitioned_graph: &DfirGraph,
164    mut subgraph_unionfind: UnionFind<GraphNodeId>,
165) -> SecondaryMap<GraphNodeId, Vec<GraphNodeId>> {
166    // We want the nodes of each subgraph to be listed in topo-sort order.
167    // We could do this on each subgraph, or we could do it all at once on the
168    // whole node graph by ignoring handoffs, which is what we do here:
169    let topo_sort = graph_algorithms::topo_sort(
170        partitioned_graph
171            .nodes()
172            .filter(|&(_, node)| !matches!(node, GraphNode::Handoff { .. }))
173            .map(|(node_id, _)| node_id),
174        |v| {
175            partitioned_graph
176                .node_predecessor_nodes(v)
177                .filter(|&pred_id| {
178                    let pred = partitioned_graph.node(pred_id);
179                    !matches!(pred, GraphNode::Handoff { .. })
180                })
181        },
182    )
183    .expect("Subgraphs are in-out trees.");
184
185    let mut grouped_nodes: SecondaryMap<GraphNodeId, Vec<GraphNodeId>> = Default::default();
186    for node_id in topo_sort {
187        let repr_node = subgraph_unionfind.find(node_id);
188        if !grouped_nodes.contains_key(repr_node) {
189            grouped_nodes.insert(repr_node, Default::default());
190        }
191        grouped_nodes[repr_node].push(node_id);
192    }
193    grouped_nodes
194}
195
196/// Find subgraph and insert handoffs.
197/// Modifies barrier_crossers so that the edge OUT of an inserted handoff has
198/// the DelayType data.
199fn make_subgraphs(partitioned_graph: &mut DfirGraph, barrier_crossers: &mut BarrierCrossers) {
200    // Algorithm:
201    // 1. Each node begins as its own subgraph.
202    // 2. Collect edges. (Future optimization: sort so edges which should not be split across a handoff come first).
203    // 3. For each edge, try to join `(to, from)` into the same subgraph.
204
205    // TODO(mingwei):
206    // self.partitioned_graph.assert_valid();
207
208    let (subgraph_unionfind, handoff_edges) =
209        find_subgraph_unionfind(partitioned_graph, barrier_crossers);
210
211    // Insert handoffs between subgraphs (or on subgraph self-loop edges)
212    for edge_id in handoff_edges {
213        let (src_id, dst_id) = partitioned_graph.edge(edge_id);
214
215        // Already has a handoff, no need to insert one.
216        let src_node = partitioned_graph.node(src_id);
217        let dst_node = partitioned_graph.node(dst_id);
218        if matches!(src_node, GraphNode::Handoff { .. })
219            || matches!(dst_node, GraphNode::Handoff { .. })
220        {
221            continue;
222        }
223
224        let hoff = GraphNode::Handoff {
225            src_span: src_node.span(),
226            dst_span: dst_node.span(),
227        };
228        let (_node_id, out_edge_id) = partitioned_graph.insert_intermediate_node(edge_id, hoff);
229
230        // Update barrier_crossers for inserted node.
231        barrier_crossers.replace_edge(edge_id, out_edge_id);
232    }
233
234    // Determine node's subgraph and subgraph's nodes.
235    // This list of nodes in each subgraph are to be in topological sort order.
236    // Eventually returned directly in the [`DfirGraph`].
237    let grouped_nodes = make_subgraph_collect(partitioned_graph, subgraph_unionfind);
238    for (_repr_node, member_nodes) in grouped_nodes {
239        partitioned_graph.insert_subgraph(member_nodes).unwrap();
240    }
241}
242
243/// Set `src` or `dst` color if `None` based on the other (if possible):
244/// `None` indicates an op could be pull or push i.e. unary-in & unary-out.
245/// So in that case we color `src` or `dst` based on its newfound neighbor (the other one).
246///
247/// Returns if `src` and `dst` can be in the same subgraph.
248fn can_connect_colorize(
249    node_color: &mut SparseSecondaryMap<GraphNodeId, Color>,
250    src: GraphNodeId,
251    dst: GraphNodeId,
252) -> bool {
253    // Pull -> Pull
254    // Push -> Push
255    // Pull -> [Computation] -> Push
256    // Push -> [Handoff] -> Pull
257    let can_connect = match (node_color.get(src), node_color.get(dst)) {
258        // Linear chain, can't connect because it may cause future conflicts.
259        // But if it doesn't in the _future_ we can connect it (once either/both ends are determined).
260        (None, None) => false,
261
262        // Infer left side.
263        (None, Some(Color::Pull | Color::Comp)) => {
264            node_color.insert(src, Color::Pull);
265            true
266        }
267        (None, Some(Color::Push | Color::Hoff)) => {
268            node_color.insert(src, Color::Push);
269            true
270        }
271
272        // Infer right side.
273        (Some(Color::Pull | Color::Hoff), None) => {
274            node_color.insert(dst, Color::Pull);
275            true
276        }
277        (Some(Color::Comp | Color::Push), None) => {
278            node_color.insert(dst, Color::Push);
279            true
280        }
281
282        // Both sides already specified.
283        (Some(Color::Pull), Some(Color::Pull)) => true,
284        (Some(Color::Pull), Some(Color::Comp)) => true,
285        (Some(Color::Pull), Some(Color::Push)) => true,
286
287        (Some(Color::Comp), Some(Color::Pull)) => false,
288        (Some(Color::Comp), Some(Color::Comp)) => false,
289        (Some(Color::Comp), Some(Color::Push)) => true,
290
291        (Some(Color::Push), Some(Color::Pull)) => false,
292        (Some(Color::Push), Some(Color::Comp)) => false,
293        (Some(Color::Push), Some(Color::Push)) => true,
294
295        // Handoffs are not part of subgraphs.
296        (Some(Color::Hoff), Some(_)) => false,
297        (Some(_), Some(Color::Hoff)) => false,
298    };
299    can_connect
300}
301
302/// Topologically sorts subgraphs and marks tick-boundary (`defer_tick` / `defer_tick_lazy`)
303/// handoffs with their delay type for double-buffered codegen in `as_code`.
304///
305/// Returns an error if there is an intra-tick cycle (i.e. the subgraph DAG has a cycle when
306/// tick-boundary edges are excluded).
307fn order_subgraphs(
308    partitioned_graph: &mut DfirGraph,
309    barrier_crossers: &BarrierCrossers,
310) -> Result<(), Diagnostic> {
311    // Build a subgraph-level directed graph, excluding tick-boundary edges.
312    let mut sg_preds: BTreeMap<GraphSubgraphId, Vec<GraphSubgraphId>> = Default::default();
313
314    // Track which handoff edges are tick-boundary, keyed by (src_sg, dst_sg).
315    let mut tick_edges: Vec<(GraphEdgeId, DelayType)> = Vec::new();
316
317    // Iterate handoffs between subgraphs.
318    for (node_id, node) in partitioned_graph.nodes() {
319        if !matches!(node, GraphNode::Handoff { .. }) {
320            continue;
321        }
322        assert_eq!(1, partitioned_graph.node_successors(node_id).len());
323        let (succ_edge, succ) = partitioned_graph.node_successors(node_id).next().unwrap();
324
325        let succ_edge_delaytype = barrier_crossers
326            .edge_barrier_crossers
327            .get(succ_edge)
328            .copied();
329        // Tick edges are excluded from the topo sort — they are cross-tick by design.
330        if let Some(delay_type @ (DelayType::Tick | DelayType::TickLazy)) = succ_edge_delaytype {
331            tick_edges.push((succ_edge, delay_type));
332            continue;
333        }
334
335        assert_eq!(1, partitioned_graph.node_predecessors(node_id).len());
336        let (_edge_id, pred) = partitioned_graph.node_predecessors(node_id).next().unwrap();
337
338        let pred_sg = partitioned_graph.node_subgraph(pred).unwrap();
339        let succ_sg = partitioned_graph.node_subgraph(succ).unwrap();
340
341        sg_preds.entry(succ_sg).or_default().push(pred_sg);
342    }
343    // Include singleton reference edges.
344    for &(pred, succ) in barrier_crossers.singleton_barrier_crossers.iter() {
345        assert_ne!(pred, succ, "TODO(mingwei)");
346        let pred_sg = partitioned_graph.node_subgraph(pred).unwrap();
347        let succ_sg = partitioned_graph.node_subgraph(succ).unwrap();
348        assert_ne!(pred_sg, succ_sg);
349        sg_preds.entry(succ_sg).or_default().push(pred_sg);
350    }
351
352    // Topological sort — rejects intra-tick cycles.
353    if let Err(cycle) = graph_algorithms::topo_sort(partitioned_graph.subgraph_ids(), |v| {
354        sg_preds.get(&v).into_iter().flatten().copied()
355    }) {
356        let span = cycle
357            .first()
358            .and_then(|&sg_id| partitioned_graph.subgraph(sg_id).first().copied())
359            .map(|n| partitioned_graph.node(n).span())
360            .unwrap_or_else(Span::call_site);
361        return Err(Diagnostic::spanned(
362            span,
363            Level::Error,
364            "Cyclical dataflow within a tick is not supported. Use `defer_tick()` or `defer_tick_lazy()` to break the cycle across ticks.",
365        ));
366    }
367
368    // Mark tick-boundary handoffs with their delay type.
369    // These handoffs are excluded from the intra-tick topo ordering in
370    // `as_code`; instead, their double-buffered handoff semantics defer data
371    // across the tick boundary to the next tick.
372    for (edge_id, delay_type) in tick_edges {
373        let (hoff, _dst) = partitioned_graph.edge(edge_id);
374        assert!(matches!(
375            partitioned_graph.node(hoff),
376            GraphNode::Handoff { .. }
377        ));
378        partitioned_graph.set_handoff_delay_type(hoff, delay_type);
379    }
380    Ok(())
381}
382
383/// Main method for this module. Partitions a flat [`DfirGraph`] into one with subgraphs.
384///
385/// Returns an error if an intra-tick cycle exists in the graph.
386pub fn partition_graph(flat_graph: DfirGraph) -> Result<DfirGraph, Diagnostic> {
387    // Pre-find barrier crossers (input edges with a `DelayType`).
388    let mut barrier_crossers = find_barrier_crossers(&flat_graph);
389    let mut partitioned_graph = flat_graph;
390
391    // Partition into subgraphs.
392    make_subgraphs(&mut partitioned_graph, &mut barrier_crossers);
393
394    // Topologically order subgraphs and mark tick-boundary handoffs for double-buffering.
395    order_subgraphs(&mut partitioned_graph, &barrier_crossers)?;
396
397    Ok(partitioned_graph)
398}