]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/util/graphviz.rs
e89c9437706384e3a8ff65ca067135485f72a9dc
[rust.git] / compiler / rustc_mir / src / util / graphviz.rs
1 use rustc_graphviz as dot;
2 use rustc_hir::def_id::DefId;
3 use rustc_index::vec::Idx;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::TyCtxt;
6 use std::fmt::Debug;
7 use std::io::{self, Write};
8
9 use super::pretty::dump_mir_def_ids;
10
11 /// Write a graphviz DOT graph of a list of MIRs.
12 pub fn write_mir_graphviz<W>(tcx: TyCtxt<'_>, single: Option<DefId>, w: &mut W) -> io::Result<()>
13 where
14     W: Write,
15 {
16     let def_ids = dump_mir_def_ids(tcx, single);
17
18     let use_subgraphs = def_ids.len() > 1;
19     if use_subgraphs {
20         writeln!(w, "digraph __crate__ {{")?;
21     }
22
23     for def_id in def_ids {
24         let body = &tcx.optimized_mir(def_id);
25         write_mir_fn_graphviz(tcx, def_id, body, use_subgraphs, w)?;
26     }
27
28     if use_subgraphs {
29         writeln!(w, "}}")?;
30     }
31
32     Ok(())
33 }
34
35 // Must match `[0-9A-Za-z_]*`. This does not appear in the rendered graph, so
36 // it does not have to be user friendly.
37 pub fn graphviz_safe_def_name(def_id: DefId) -> String {
38     format!("{}_{}", def_id.krate.index(), def_id.index.index(),)
39 }
40
41 /// Write a graphviz DOT graph of the MIR.
42 pub fn write_mir_fn_graphviz<'tcx, W>(
43     tcx: TyCtxt<'tcx>,
44     def_id: DefId,
45     body: &Body<'_>,
46     subgraph: bool,
47     w: &mut W,
48 ) -> io::Result<()>
49 where
50     W: Write,
51 {
52     let kind = if subgraph { "subgraph" } else { "digraph" };
53     let cluster = if subgraph { "cluster_" } else { "" }; // Prints a border around MIR
54     let def_name = graphviz_safe_def_name(def_id);
55     writeln!(w, "{} {}Mir_{} {{", kind, cluster, def_name)?;
56
57     // Global graph properties
58     let font = r#"fontname="Courier, monospace""#;
59     let mut graph_attrs = vec![font];
60     let mut content_attrs = vec![font];
61
62     let dark_mode = tcx.sess.opts.debugging_opts.graphviz_dark_mode;
63     if dark_mode {
64         graph_attrs.push(r#"bgcolor="black""#);
65         content_attrs.push(r#"color="white""#);
66         content_attrs.push(r#"fontcolor="white""#);
67     }
68
69     writeln!(w, r#"    graph [{}];"#, graph_attrs.join(" "))?;
70     let content_attrs_str = content_attrs.join(" ");
71     writeln!(w, r#"    node [{}];"#, content_attrs_str)?;
72     writeln!(w, r#"    edge [{}];"#, content_attrs_str)?;
73
74     // Graph label
75     write_graph_label(tcx, def_id, body, w)?;
76
77     // Nodes
78     for (block, _) in body.basic_blocks().iter_enumerated() {
79         write_node(def_id, block, body, dark_mode, w)?;
80     }
81
82     // Edges
83     for (source, _) in body.basic_blocks().iter_enumerated() {
84         write_edges(def_id, source, body, w)?;
85     }
86     writeln!(w, "}}")
87 }
88
89 /// Write a graphviz HTML-styled label for the given basic block, with
90 /// all necessary escaping already performed. (This is suitable for
91 /// emitting directly, as is done in this module, or for use with the
92 /// LabelText::HtmlStr from librustc_graphviz.)
93 ///
94 /// `init` and `fini` are callbacks for emitting additional rows of
95 /// data (using HTML enclosed with `<tr>` in the emitted text).
96 pub fn write_node_label<W: Write, INIT, FINI>(
97     block: BasicBlock,
98     body: &Body<'_>,
99     dark_mode: bool,
100     w: &mut W,
101     num_cols: u32,
102     init: INIT,
103     fini: FINI,
104 ) -> io::Result<()>
105 where
106     INIT: Fn(&mut W) -> io::Result<()>,
107     FINI: Fn(&mut W) -> io::Result<()>,
108 {
109     let data = &body[block];
110
111     write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
112
113     // Basic block number at the top.
114     write!(
115         w,
116         r#"<tr><td bgcolor="{bgcolor}" {attrs} colspan="{colspan}">{blk}</td></tr>"#,
117         bgcolor = if dark_mode { "dimgray" } else { "gray" },
118         attrs = r#"align="center""#,
119         colspan = num_cols,
120         blk = block.index()
121     )?;
122
123     init(w)?;
124
125     // List of statements in the middle.
126     if !data.statements.is_empty() {
127         write!(w, r#"<tr><td align="left" balign="left">"#)?;
128         for statement in &data.statements {
129             write!(w, "{}<br/>", escape(statement))?;
130         }
131         write!(w, "</td></tr>")?;
132     }
133
134     // Terminator head at the bottom, not including the list of successor blocks. Those will be
135     // displayed as labels on the edges between blocks.
136     let mut terminator_head = String::new();
137     data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
138     write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head))?;
139
140     fini(w)?;
141
142     // Close the table
143     write!(w, "</table>")
144 }
145
146 /// Write a graphviz DOT node for the given basic block.
147 fn write_node<W: Write>(
148     def_id: DefId,
149     block: BasicBlock,
150     body: &Body<'_>,
151     dark_mode: bool,
152     w: &mut W,
153 ) -> io::Result<()> {
154     // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
155     write!(w, r#"    {} [shape="none", label=<"#, node(def_id, block))?;
156     write_node_label(block, body, dark_mode, w, 1, |_| Ok(()), |_| Ok(()))?;
157     // Close the node label and the node itself.
158     writeln!(w, ">];")
159 }
160
161 /// Write graphviz DOT edges with labels between the given basic block and all of its successors.
162 fn write_edges<W: Write>(
163     def_id: DefId,
164     source: BasicBlock,
165     body: &Body<'_>,
166     w: &mut W,
167 ) -> io::Result<()> {
168     let terminator = body[source].terminator();
169     let labels = terminator.kind.fmt_successor_labels();
170
171     for (&target, label) in terminator.successors().zip(labels) {
172         let src = node(def_id, source);
173         let trg = node(def_id, target);
174         writeln!(w, r#"    {} -> {} [label="{}"];"#, src, trg, label)?;
175     }
176
177     Ok(())
178 }
179
180 /// Write the graphviz DOT label for the overall graph. This is essentially a block of text that
181 /// will appear below the graph, showing the type of the `fn` this MIR represents and the types of
182 /// all the variables and temporaries.
183 fn write_graph_label<'tcx, W: Write>(
184     tcx: TyCtxt<'tcx>,
185     def_id: DefId,
186     body: &Body<'_>,
187     w: &mut W,
188 ) -> io::Result<()> {
189     write!(w, "    label=<fn {}(", dot::escape_html(&tcx.def_path_str(def_id)))?;
190
191     // fn argument types.
192     for (i, arg) in body.args_iter().enumerate() {
193         if i > 0 {
194             write!(w, ", ")?;
195         }
196         write!(w, "{:?}: {}", Place::from(arg), escape(&body.local_decls[arg].ty))?;
197     }
198
199     write!(w, ") -&gt; {}", escape(&body.return_ty()))?;
200     write!(w, r#"<br align="left"/>"#)?;
201
202     for local in body.vars_and_temps_iter() {
203         let decl = &body.local_decls[local];
204
205         write!(w, "let ")?;
206         if decl.mutability == Mutability::Mut {
207             write!(w, "mut ")?;
208         }
209
210         write!(w, r#"{:?}: {};<br align="left"/>"#, Place::from(local), escape(&decl.ty))?;
211     }
212
213     for var_debug_info in &body.var_debug_info {
214         write!(
215             w,
216             r#"debug {} =&gt; {};<br align="left"/>"#,
217             var_debug_info.name,
218             escape(&var_debug_info.place)
219         )?;
220     }
221
222     writeln!(w, ">;")
223 }
224
225 fn node(def_id: DefId, block: BasicBlock) -> String {
226     format!("bb{}__{}", block.index(), graphviz_safe_def_name(def_id))
227 }
228
229 fn escape<T: Debug>(t: &T) -> String {
230     dot::escape_html(&format!("{:?}", t))
231 }