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;
7 use std::io::{self, Write};
9 use super::pretty::dump_mir_def_ids;
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<()>
16 let def_ids = dump_mir_def_ids(tcx, single);
18 let use_subgraphs = def_ids.len() > 1;
20 writeln!(w, "digraph __crate__ {{")?;
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)?;
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(),)
41 /// Write a graphviz DOT graph of the MIR.
42 pub fn write_mir_fn_graphviz<'tcx, W>(
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)?;
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];
62 let dark_mode = tcx.sess.opts.debugging_opts.graphviz_dark_mode;
64 graph_attrs.push(r#"bgcolor="black""#);
65 content_attrs.push(r#"color="white""#);
66 content_attrs.push(r#"fontcolor="white""#);
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)?;
75 write_graph_label(tcx, def_id, body, w)?;
78 for (block, _) in body.basic_blocks().iter_enumerated() {
79 write_node(def_id, block, body, dark_mode, w)?;
83 for (source, _) in body.basic_blocks().iter_enumerated() {
84 write_edges(def_id, source, body, w)?;
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.)
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>(
106 INIT: Fn(&mut W) -> io::Result<()>,
107 FINI: Fn(&mut W) -> io::Result<()>,
109 let data = &body[block];
111 write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
113 // Basic block number at the top.
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""#,
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))?;
131 write!(w, "</td></tr>")?;
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))?;
143 write!(w, "</table>")
146 /// Write a graphviz DOT node for the given basic block.
147 fn write_node<W: Write>(
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.
161 /// Write graphviz DOT edges with labels between the given basic block and all of its successors.
162 fn write_edges<W: Write>(
167 ) -> io::Result<()> {
168 let terminator = body[source].terminator();
169 let labels = terminator.kind.fmt_successor_labels();
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)?;
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>(
188 ) -> io::Result<()> {
189 write!(w, " label=<fn {}(", dot::escape_html(&tcx.def_path_str(def_id)))?;
191 // fn argument types.
192 for (i, arg) in body.args_iter().enumerate() {
196 write!(w, "{:?}: {}", Place::from(arg), escape(&body.local_decls[arg].ty))?;
199 write!(w, ") -> {}", escape(&body.return_ty()))?;
200 write!(w, r#"<br align="left"/>"#)?;
202 for local in body.vars_and_temps_iter() {
203 let decl = &body.local_decls[local];
206 if decl.mutability == Mutability::Mut {
210 write!(w, r#"{:?}: {};<br align="left"/>"#, Place::from(local), escape(&decl.ty))?;
213 for var_debug_info in &body.var_debug_info {
216 r#"debug {} => {};<br align="left"/>"#,
218 escape(&var_debug_info.place)
225 fn node(def_id: DefId, block: BasicBlock) -> String {
226 format!("bb{}__{}", block.index(), graphviz_safe_def_name(def_id))
229 fn escape<T: Debug>(t: &T) -> String {
230 dot::escape_html(&format!("{:?}", t))