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