Skip to main content

flux_middle/
dep_graph.rs

1//! Data types for the no-panic call graph.
2//!
3//! The graph is *constructed* by the `flux-opt` crate (the `call_graph` query provider) but the
4//! types live here so they can be cached in `flux-middle` and consumed by both `flux-opt`
5//! (no-panic inference) and `flux-refineck` (the checker, which recovers the resolved callee at a
6//! call site by location).
7
8use std::{fmt, fs, io, path::Path};
9
10use flux_common::dbg::SpanTrace;
11use rustc_data_structures::{
12    fx::{FxIndexMap, FxIndexSet},
13    unord::UnordMap,
14};
15use rustc_hir::{def::DefKind, def_id::DefId};
16use rustc_macros::{TyDecodable, TyEncodable};
17use rustc_middle::{
18    mir::Location,
19    ty::{GenericArgs, Instance, InstanceKind, TyCtxt, TypeVisitableExt},
20};
21use rustc_serialize::ContextOrd;
22use serde::Serialize;
23use toposort_scc::IndexGraph;
24
25/// Identity of a call-graph node. Distinguishes an item *as defined in source* from a
26/// *monomorphization* synthesized while building the graph.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
28pub enum NodeKey<'tcx> {
29    /// An item as written in source (generic or not), identified by its `DefId`.
30    Item(DefId),
31    /// A generic item monomorphized at concrete type/const args while building the
32    /// call graph (e.g. `Vec::<i32>::push`). We must guarantee that the instance is fully
33    /// monomorphic, i.e., the `Instance`'s args are all concrete types/consts.
34    ///
35    /// Use `NodeKey::from_instance` to classify an `Instance` into a `NodeKey`.
36    Mono(Instance<'tcx>),
37}
38
39// Flux metadata is not encoded deterministically, so a stable comparator is never needed.
40impl<'tcx, E> ContextOrd<E> for NodeKey<'tcx> {}
41
42impl<'tcx> NodeKey<'tcx> {
43    /// Classifies an `Instance` into a `NodeKey`.
44    pub fn from_instance(instance: Instance<'tcx>) -> Self {
45        if let InstanceKind::Item(def_id) = instance.def
46            // - If `has_param()` is true then the instance is not fully monomorphic
47            // - If args is empty then is a non-generic item
48            && (instance.args.has_param() || instance.args.is_empty())
49        {
50            NodeKey::Item(def_id)
51        } else {
52            NodeKey::Mono(instance)
53        }
54    }
55
56    pub fn def_id(self) -> DefId {
57        match self {
58            NodeKey::Item(def_id) => def_id,
59            NodeKey::Mono(instance) => instance.def_id(),
60        }
61    }
62
63    /// The `Instance` this key denotes. For an [`Item`](NodeKey::Item) this rebuilds the identity
64    /// instance; for a [`Mono`](NodeKey::Mono) it is the stored instance.
65    pub fn instance(self, tcx: TyCtxt<'tcx>) -> Instance<'tcx> {
66        match self {
67            NodeKey::Item(def_id) => {
68                Instance::new_raw(def_id, GenericArgs::identity_for_item(tcx, def_id))
69            }
70            NodeKey::Mono(instance) => instance,
71        }
72    }
73
74    /// Whether this key denotes a locally-defined function item — the source item itself or a
75    /// monomorphization of it. Excludes foreign defs and non-`Item` instances (drop glue, fn-ptr
76    /// shims, etc.), which never carry a meaningful spec. Used to decide which specs a crate owns
77    /// and serializes into its own metadata.
78    #[allow(
79        clippy::disallowed_methods,
80        reason = "is responsibility of who builds the graph to filter out dummy extern spec items."
81    )]
82    pub fn is_local_item(self) -> bool {
83        self.def_id().is_local()
84            && match self {
85                NodeKey::Item(_) => true,
86                NodeKey::Mono(instance) => matches!(instance.def, InstanceKind::Item(_)),
87            }
88    }
89}
90
91/// A single call site observed in a function's MIR body.
92#[derive(Debug, Clone)]
93pub struct CallSite<'tcx> {
94    pub location: Location,
95    pub kind: CallSiteKind<'tcx>,
96}
97
98#[derive(Debug, Clone)]
99pub enum CallSiteKind<'tcx> {
100    /// `Call` terminator that resolved to a concrete callee node (a source item or a
101    /// monomorphization).
102    Resolved { callee: NodeKey<'tcx> },
103    /// Synthetic edge from an `Assert` terminator with a reachable unwind path —
104    /// represents the implicit call to `core::panicking::panic`.
105    SynthesizedPanic,
106    /// `Call` terminator on a `FnDef` where `Instance::try_resolve` failed.
107    Unresolved { def_id: DefId },
108    /// `Call` terminator on a non-`FnDef` type (function pointer, closure).
109    DynamicDispatch,
110}
111
112/// A node in the call graph. The node's provenance (source item vs monomorphization) is carried by
113/// its [`NodeKey`]; the node itself only records, when it has an analyzable body, the call sites
114/// observed in it.
115#[derive(Debug, Clone)]
116pub enum Node<'tcx> {
117    /// MIR was available and walked. `call_sites` are the Call/Assert terminators observed.
118    Analyzed { call_sites: Vec<CallSite<'tcx>> },
119    /// External crate function — panic spec looked up from crate metadata.
120    ExternalCrate,
121    /// Function with no analyzable body (no Rust body by design, MIR unavailable,
122    /// or a non-`Item` instance such as a shim or virtual dispatch stub).
123    /// Conservatively treated as `MightPanic`.
124    Leaf(DefKind),
125}
126
127impl<'tcx> Node<'tcx> {
128    /// Call sites observed in this node's body. Empty for non-`Analyzed` nodes.
129    fn call_sites(&self) -> &[CallSite<'tcx>] {
130        match self {
131            Node::Analyzed { call_sites } => call_sites,
132            Node::ExternalCrate | Node::Leaf(_) => &[],
133        }
134    }
135
136    /// The callee nodes of this node's resolved call sites (skipping unresolved/dynamic ones).
137    pub fn resolved_callees(&self) -> impl Iterator<Item = NodeKey<'tcx>> {
138        self.call_sites().iter().filter_map(|site| {
139            match site.kind {
140                CallSiteKind::Resolved { callee } => Some(callee),
141                _ => None,
142            }
143        })
144    }
145}
146
147pub struct CallGraph<'tcx> {
148    pub nodes: FxIndexMap<NodeKey<'tcx>, Node<'tcx>>,
149    pub callers: UnordMap<NodeKey<'tcx>, Vec<NodeKey<'tcx>>>,
150}
151
152impl<'tcx> CallGraph<'tcx> {
153    pub fn new(nodes: FxIndexMap<NodeKey<'tcx>, Node<'tcx>>) -> Self {
154        let mut callers: UnordMap<_, Vec<_>> = UnordMap::default();
155        for (&caller, node) in &nodes {
156            for callee in node.resolved_callees() {
157                callers.entry(callee).or_default().push(caller);
158            }
159        }
160        CallGraph { nodes, callers }
161    }
162
163    /// The callee node resolved for the `Call` terminator at `location` in the body of `caller`.
164    /// Returns `None` for call sites that did not resolve to a concrete node (unresolved trait
165    /// calls, dynamic dispatch) or whose body is not in the graph.
166    pub fn resolved_callee(&self, caller: DefId, location: Location) -> Option<NodeKey<'tcx>> {
167        let node = self.nodes.get(&NodeKey::Item(caller))?;
168        node.call_sites().iter().find_map(|site| {
169            match site.kind {
170                CallSiteKind::Resolved { callee } if site.location == location => Some(callee),
171                _ => None,
172            }
173        })
174    }
175}
176
177impl<'tcx> fmt::Display for NodeKey<'tcx> {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        match self {
180            NodeKey::Item(def_id) => write!(f, "{def_id:?}"),
181            NodeKey::Mono(instance) => write!(f, "{instance}"),
182        }
183    }
184}
185
186impl<'tcx> fmt::Display for Node<'tcx> {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        match self {
189            Node::Analyzed { .. } => write!(f, "Analyzed"),
190            Node::ExternalCrate => write!(f, "ExternalCrate"),
191            Node::Leaf(kind) => write!(f, "Leaf({kind:?})"),
192        }
193    }
194}
195
196impl<'tcx> fmt::Display for CallSiteKind<'tcx> {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            CallSiteKind::Resolved { callee } => write!(f, "-> {callee}"),
200            CallSiteKind::SynthesizedPanic => write!(f, "-> panic"),
201            CallSiteKind::Unresolved { def_id: method } => write!(f, "-> trait {method:?}"),
202            CallSiteKind::DynamicDispatch => write!(f, "-> <dynamic>"),
203        }
204    }
205}
206
207impl<'tcx> fmt::Display for CallGraph<'tcx> {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        writeln!(f, "call graph ({} nodes):", self.nodes.len())?;
210        let mut nodes: Vec<_> = self.nodes.iter().collect();
211        nodes.sort_by_key(|(key, _)| format!("{key}"));
212        for (key, node) in nodes {
213            writeln!(f, "  {key} [{node}]:")?;
214            for site in node.call_sites() {
215                writeln!(f, "    {} at {:?}", site.kind, site.location)?;
216            }
217        }
218        Ok(())
219    }
220}
221
222#[derive(Serialize)]
223pub struct JsonNode {
224    pub uid: usize,
225    pub path: String,
226    pub span: SpanTrace,
227    pub deps: Vec<usize>,
228}
229
230/// Topologically sort `def_ids` by `adj` (deps before dependents) and emit as JSON to `file_name`
231/// inside `dir`.
232pub fn dump_dep_graph_json(
233    tcx: TyCtxt<'_>,
234    dir: &Path,
235    file_name: &str,
236    def_ids: &[DefId],
237    adj: &[Vec<usize>],
238) -> io::Result<()> {
239    let mut graph = IndexGraph::from_adjacency_list(adj);
240    graph.transpose();
241    let topo_order = graph
242        .toposort_or_scc()
243        .unwrap_or_else(|sccs| sccs.into_iter().flatten().collect());
244
245    let mut uid_of: Vec<usize> = vec![0; def_ids.len()];
246    for (uid, &orig_idx) in topo_order.iter().enumerate() {
247        uid_of[orig_idx] = uid;
248    }
249
250    let json_nodes: Vec<JsonNode> = topo_order
251        .iter()
252        .enumerate()
253        .map(|(uid, &orig_idx)| {
254            let def_id = def_ids[orig_idx];
255            let dep_uids: Vec<usize> = adj[orig_idx].iter().map(|&j| uid_of[j]).collect();
256            JsonNode {
257                uid,
258                path: tcx.def_path_str(def_id),
259                span: SpanTrace::new(tcx, tcx.def_span(def_id)),
260                deps: dep_uids,
261            }
262        })
263        .collect();
264
265    fs::create_dir_all(dir)?;
266    let path = dir.join(file_name);
267    let file = fs::File::create(path)?;
268    serde_json::to_writer_pretty(file, &json_nodes)
269        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
270}
271
272impl<'tcx> CallGraph<'tcx> {
273    /// Dump the local portion of the call graph as a JSON array, topologically sorted so that
274    /// callees appear before callers (leaves first).
275    pub fn dump_dep_graph_json(&self, tcx: TyCtxt<'tcx>, dir: &Path) -> io::Result<()> {
276        // The JSON has a single node per local function: the generic item and all its
277        // monomorphizations (which are separate nodes in the graph) are merged into one node,
278        // identified by their common `DefId`.
279        let def_ids: FxIndexSet<DefId> = self
280            .nodes
281            .keys()
282            .filter(|key| key.is_local_item())
283            .map(|key| key.def_id())
284            .collect();
285        let idx_of = |key: &NodeKey<'tcx>| {
286            if key.is_local_item() { def_ids.get_index_of(&key.def_id()) } else { None }
287        };
288
289        // The local callees of each local function, collected from the bodies of the generic
290        // item and all its monomorphizations.
291        let mut adj: Vec<Vec<usize>> = vec![vec![]; def_ids.len()];
292        for (key, node) in &self.nodes {
293            let Some(caller_idx) = idx_of(key) else { continue };
294            adj[caller_idx].extend(node.resolved_callees().filter_map(|callee| idx_of(&callee)));
295        }
296        for deps in &mut adj {
297            deps.sort_unstable();
298            deps.dedup();
299        }
300        let def_ids: Vec<DefId> = def_ids.into_iter().collect();
301
302        dump_dep_graph_json(tcx, dir, "call_graph.json", &def_ids, &adj)
303    }
304}