1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use rustc::hir::def_id::DefId;
14 use rustc::ty::TyCtxt;
16 use std::io::{self, Write};
18 use rustc_data_structures::indexed_vec::Idx;
20 use super::pretty::dump_mir_def_ids;
22 /// Write a graphviz DOT graph of a list of MIRs.
23 pub fn write_mir_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>,
24 single: Option<DefId>,
29 for def_id in dump_mir_def_ids(tcx, single) {
30 let mir = &tcx.optimized_mir(def_id);
31 write_mir_fn_graphviz(tcx, def_id, mir, w)?;
36 /// Write a graphviz DOT graph of the MIR.
37 pub fn write_mir_fn_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>,
40 w: &mut W) -> io::Result<()>
43 writeln!(w, "digraph Mir_{} {{", tcx.hir.as_local_node_id(def_id).unwrap())?;
45 // Global graph properties
46 writeln!(w, r#" graph [fontname="monospace"];"#)?;
47 writeln!(w, r#" node [fontname="monospace"];"#)?;
48 writeln!(w, r#" edge [fontname="monospace"];"#)?;
51 write_graph_label(tcx, def_id, mir, w)?;
54 for (block, _) in mir.basic_blocks().iter_enumerated() {
55 write_node(block, mir, w)?;
59 for (source, _) in mir.basic_blocks().iter_enumerated() {
60 write_edges(source, mir, w)?;
65 /// Write a graphviz HTML-styled label for the given basic block, with
66 /// all necessary escaping already performed. (This is suitable for
67 /// emitting directly, as is done in this module, or for use with the
68 /// LabelText::HtmlStr from libgraphviz.)
70 /// `init` and `fini` are callbacks for emitting additional rows of
71 /// data (using HTML enclosed with `<tr>` in the emitted text).
72 pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
77 fini: FINI) -> io::Result<()>
78 where INIT: Fn(&mut W) -> io::Result<()>,
79 FINI: Fn(&mut W) -> io::Result<()>
81 let data = &mir[block];
83 write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
85 // Basic block number at the top.
86 write!(w, r#"<tr><td {attrs} colspan="{colspan}">{blk}</td></tr>"#,
87 attrs=r#"bgcolor="gray" align="center""#,
93 // List of statements in the middle.
94 if !data.statements.is_empty() {
95 write!(w, r#"<tr><td align="left" balign="left">"#)?;
96 for statement in &data.statements {
97 write!(w, "{}<br/>", escape(statement))?;
99 write!(w, "</td></tr>")?;
102 // Terminator head at the bottom, not including the list of successor blocks. Those will be
103 // displayed as labels on the edges between blocks.
104 let mut terminator_head = String::new();
105 data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
106 write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head))?;
111 writeln!(w, "</table>")
114 /// Write a graphviz DOT node for the given basic block.
115 fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
116 // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
117 write!(w, r#" {} [shape="none", label=<"#, node(block))?;
118 write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?;
119 // Close the node label and the node itself.
123 /// Write graphviz DOT edges with labels between the given basic block and all of its successors.
124 fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
125 let terminator = mir[source].terminator();
126 let labels = terminator.kind.fmt_successor_labels();
128 for (&target, label) in terminator.successors().iter().zip(labels) {
129 writeln!(w, r#" {} -> {} [label="{}"];"#, node(source), node(target), label)?;
135 /// Write the graphviz DOT label for the overall graph. This is essentially a block of text that
136 /// will appear below the graph, showing the type of the `fn` this MIR represents and the types of
137 /// all the variables and temporaries.
138 fn write_graph_label<'a, 'gcx, 'tcx, W: Write>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
143 write!(w, " label=<fn {}(", dot::escape_html(&tcx.item_path_str(def_id)))?;
145 // fn argument types.
146 for (i, arg) in mir.args_iter().enumerate() {
150 write!(w, "{:?}: {}", Lvalue::Local(arg), escape(&mir.local_decls[arg].ty))?;
153 write!(w, ") -> {}", escape(mir.return_ty))?;
154 write!(w, r#"<br align="left"/>"#)?;
156 for local in mir.vars_and_temps_iter() {
157 let decl = &mir.local_decls[local];
160 if decl.mutability == Mutability::Mut {
164 if let Some(name) = decl.name {
165 write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
166 Lvalue::Local(local), escape(&decl.ty), name)?;
168 write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
169 Lvalue::Local(local), escape(&decl.ty))?;
176 fn node(block: BasicBlock) -> String {
177 format!("bb{}", block.index())
180 fn escape<T: Debug>(t: &T) -> String {
181 dot::escape_html(&format!("{:?}", t))