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