1 //! Hook into libgraphviz for rendering dataflow graphs for MIR.
3 use rustc::mir::{BasicBlock, Body};
4 use rustc_hir::def_id::DefId;
8 use std::marker::PhantomData;
11 use crate::util::graphviz_safe_def_name;
13 use super::DataflowBuilder;
14 use super::DebugFormatted;
15 use super::{BitDenotation, DataflowState};
17 pub trait MirWithFlowState<'tcx> {
18 type BD: BitDenotation<'tcx>;
19 fn def_id(&self) -> DefId;
20 fn body(&self) -> &Body<'tcx>;
21 fn flow_state(&self) -> &DataflowState<'tcx, Self::BD>;
24 impl<'a, 'tcx, BD> MirWithFlowState<'tcx> for DataflowBuilder<'a, 'tcx, BD>
26 BD: BitDenotation<'tcx>,
29 fn def_id(&self) -> DefId {
32 fn body(&self) -> &Body<'tcx> {
33 self.flow_state.body()
35 fn flow_state(&self) -> &DataflowState<'tcx, Self::BD> {
36 &self.flow_state.flow_state
40 struct Graph<'a, 'tcx, MWF, P>
42 MWF: MirWithFlowState<'tcx>,
45 phantom: PhantomData<&'tcx ()>,
49 pub(crate) fn print_borrowck_graph_to<'a, 'tcx, BD, P>(
50 mbcx: &DataflowBuilder<'a, 'tcx, BD>,
55 BD: BitDenotation<'tcx>,
56 P: Fn(&BD, BD::Idx) -> DebugFormatted,
58 let g = Graph { mbcx, phantom: PhantomData, render_idx };
59 let mut v = Vec::new();
60 dot::render(&g, &mut v)?;
61 debug!("print_borrowck_graph_to path: {} def_id: {:?}", path.display(), mbcx.def_id);
65 pub type Node = BasicBlock;
67 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
73 fn outgoing(body: &Body<'_>, bb: BasicBlock) -> Vec<Edge> {
74 (0..body[bb].terminator().successors().count())
75 .map(|index| Edge { source: bb, index: index })
79 impl<'a, 'tcx, MWF, P> dot::Labeller<'a> for Graph<'a, 'tcx, MWF, P>
81 MWF: MirWithFlowState<'tcx>,
82 P: Fn(&MWF::BD, <MWF::BD as BitDenotation<'tcx>>::Idx) -> DebugFormatted,
86 fn graph_id(&self) -> dot::Id<'_> {
87 let name = graphviz_safe_def_name(self.mbcx.def_id());
88 dot::Id::new(format!("graph_for_def_id_{}", name)).unwrap()
91 fn node_id(&self, n: &Node) -> dot::Id<'_> {
92 dot::Id::new(format!("bb_{}", n.index())).unwrap()
95 fn node_label(&self, n: &Node) -> dot::LabelText<'_> {
96 // Node label is something like this:
97 // +---------+----------------------------------+------------------+------------------+
98 // | ENTRY | MIR | GEN | KILL |
99 // +---------+----------------------------------+------------------+------------------+
100 // | | 0: StorageLive(_7) | bb3[2]: reserved | bb2[0]: reserved |
101 // | | 1: StorageLive(_8) | bb3[2]: active | bb2[0]: active |
102 // | | 2: _8 = &mut _1 | | bb4[2]: reserved |
103 // | | | | bb4[2]: active |
104 // | | | | bb9[0]: reserved |
105 // | | | | bb9[0]: active |
106 // | | | | bb10[0]: reserved|
107 // | | | | bb10[0]: active |
108 // | | | | bb11[0]: reserved|
109 // | | | | bb11[0]: active |
110 // +---------+----------------------------------+------------------+------------------+
111 // | [00-00] | _7 = const Foo::twiddle(move _8) | [0c-00] | [f3-0f] |
112 // +---------+----------------------------------+------------------+------------------+
113 let mut v = Vec::new();
114 self.node_label_internal(n, &mut v, *n, self.mbcx.body()).unwrap();
115 dot::LabelText::html(String::from_utf8(v).unwrap())
118 fn node_shape(&self, _n: &Node) -> Option<dot::LabelText<'_>> {
119 Some(dot::LabelText::label("none"))
122 fn edge_label(&'a self, e: &Edge) -> dot::LabelText<'a> {
123 let term = self.mbcx.body()[e.source].terminator();
124 let label = &term.kind.fmt_successor_labels()[e.index];
125 dot::LabelText::label(label.clone())
129 impl<'a, 'tcx, MWF, P> Graph<'a, 'tcx, MWF, P>
131 MWF: MirWithFlowState<'tcx>,
132 P: Fn(&MWF::BD, <MWF::BD as BitDenotation<'tcx>>::Idx) -> DebugFormatted,
134 /// Generate the node label
135 fn node_label_internal<W: io::Write>(
141 ) -> io::Result<()> {
143 const HDRS: [&str; 4] = ["ENTRY", "MIR", "BLOCK GENS", "BLOCK KILLS"];
144 const HDR_FMT: &str = "bgcolor=\"grey\"";
145 write!(w, "<table><tr><td rowspan=\"{}\">", HDRS.len())?;
146 write!(w, "{:?}", block.index())?;
147 write!(w, "</td></tr><tr>")?;
149 write!(w, "<td {}>{}</td>", HDR_FMT, hdr)?;
154 self.node_label_verbose_row(n, w, block, body)?;
155 self.node_label_final_row(n, w, block, body)?;
156 write!(w, "</table>")?;
161 /// Builds the verbose row: full MIR data, and detailed gen/kill/entry sets.
162 fn node_label_verbose_row<W: io::Write>(
168 ) -> io::Result<()> {
171 macro_rules! dump_set_for {
172 ($set:ident, $interpret:ident) => {
175 let flow = self.mbcx.flow_state();
177 flow.$interpret(&flow.operator, flow.sets.$set(i), &self.render_idx);
178 for e in &entry_interp {
179 write!(w, "{:?}<br/>", e)?;
187 dump_set_for!(entry_set_for, interpret_set);
192 let data = &body[block];
193 for (i, statement) in data.statements.iter().enumerate() {
196 "{}<br align=\"left\"/>",
197 dot::escape_html(&format!("{:3}: {:?}", i, statement))
204 dump_set_for!(gen_set_for, interpret_hybrid_set);
207 dump_set_for!(kill_set_for, interpret_hybrid_set);
214 /// Builds the summary row: terminator, gen/kill/entry bit sets.
215 fn node_label_final_row<W: io::Write>(
221 ) -> io::Result<()> {
224 let flow = self.mbcx.flow_state();
229 let set = flow.sets.entry_set_for(i);
230 write!(w, "<td>{:?}</td>", dot::escape_html(&set.to_string()))?;
235 let data = &body[block];
236 let mut terminator_head = String::new();
237 data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
238 write!(w, "{}", dot::escape_html(&terminator_head))?;
243 let trans = flow.sets.trans_for(i);
244 write!(w, "<td>{:?}</td>", dot::escape_html(&format!("{:?}", trans.gen_set)))?;
245 write!(w, "<td>{:?}</td>", dot::escape_html(&format!("{:?}", trans.kill_set)))?;
253 impl<'a, 'tcx, MWF, P> dot::GraphWalk<'a> for Graph<'a, 'tcx, MWF, P>
255 MWF: MirWithFlowState<'tcx>,
259 fn nodes(&self) -> dot::Nodes<'_, Node> {
260 self.mbcx.body().basic_blocks().indices().collect::<Vec<_>>().into()
263 fn edges(&self) -> dot::Edges<'_, Edge> {
264 let body = self.mbcx.body();
266 body.basic_blocks().indices().flat_map(|bb| outgoing(body, bb)).collect::<Vec<_>>().into()
269 fn source(&self, edge: &Edge) -> Node {
273 fn target(&self, edge: &Edge) -> Node {
274 let body = self.mbcx.body();
275 *body[edge.source].terminator().successors().nth(edge.index).unwrap()