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.
11 use build::{Location, ScopeAuxiliaryVec, ScopeId};
13 use rustc::mir::repr::*;
14 use rustc::mir::transform::MirSource;
15 use rustc::ty::{self, TyCtxt};
16 use rustc_data_structures::fnv::FnvHashMap;
17 use rustc_data_structures::indexed_vec::{Idx};
18 use std::fmt::Display;
20 use std::io::{self, Write};
21 use syntax::ast::NodeId;
23 const INDENT: &'static str = " ";
24 /// Alignment for lining up comments following MIR statements
25 const ALIGN: usize = 40;
27 /// If the session is properly configured, dumps a human-readable
28 /// representation of the mir into:
31 /// rustc.node<node_id>.<pass_name>.<disambiguator>
34 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
35 /// where `<filter>` takes the following forms:
37 /// - `all` -- dump MIR for all fns, all passes, all everything
38 /// - `substring1&substring2,...` -- `&`-separated list of substrings
39 /// that can appear in the pass-name or the `item_path_str` for the given
40 /// node-id. If any one of the substrings match, the data is dumped out.
41 pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
43 disambiguator: &Display,
46 auxiliary: Option<&ScopeAuxiliaryVec>) {
47 let filters = match tcx.sess.opts.debugging_opts.dump_mir {
49 Some(ref filters) => filters,
51 let node_id = src.item_id();
52 let node_path = tcx.item_path_str(tcx.map.local_def_id(node_id));
57 pass_name.contains(filter) ||
58 node_path.contains(filter)
64 let promotion_id = match src {
65 MirSource::Promoted(_, id) => format!("-{:?}", id),
69 let file_name = format!("rustc.node{}{}.{}.{}.mir",
70 node_id, promotion_id, pass_name, disambiguator);
71 let _ = fs::File::create(&file_name).and_then(|mut file| {
72 try!(writeln!(file, "// MIR for `{}`", node_path));
73 try!(writeln!(file, "// node_id = {}", node_id));
74 try!(writeln!(file, "// pass_name = {}", pass_name));
75 try!(writeln!(file, "// disambiguator = {}", disambiguator));
76 try!(writeln!(file, ""));
77 try!(write_mir_fn(tcx, src, mir, &mut file, auxiliary));
82 /// Write out a human-readable textual representation for the given MIR.
83 pub fn write_mir_pretty<'a, 'b, 'tcx, I>(tcx: TyCtxt<'b, 'tcx, 'tcx>,
87 where I: Iterator<Item=(&'a NodeId, &'a Mir<'tcx>)>, 'tcx: 'a
90 for (&id, mir) in iter {
94 // Put empty lines between all items
98 let src = MirSource::from_node(tcx, id);
99 write_mir_fn(tcx, src, mir, w, None)?;
101 for (i, mir) in mir.promoted.iter_enumerated() {
103 write_mir_fn(tcx, MirSource::Promoted(id, i), mir, w, None)?;
114 fn scope_entry_exit_annotations(auxiliary: Option<&ScopeAuxiliaryVec>)
115 -> FnvHashMap<Location, Vec<Annotation>>
117 // compute scope/entry exit annotations
118 let mut annotations = FnvHashMap();
119 if let Some(auxiliary) = auxiliary {
120 for (scope_id, auxiliary) in auxiliary.iter_enumerated() {
121 annotations.entry(auxiliary.dom)
123 .push(Annotation::EnterScope(scope_id));
125 for &loc in &auxiliary.postdoms {
126 annotations.entry(loc)
128 .push(Annotation::ExitScope(scope_id));
135 pub fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
139 auxiliary: Option<&ScopeAuxiliaryVec>)
141 let annotations = scope_entry_exit_annotations(auxiliary);
142 write_mir_intro(tcx, src, mir, w)?;
143 for block in mir.basic_blocks().indices() {
144 write_basic_block(tcx, block, mir, w, &annotations)?;
145 if block.index() + 1 != mir.basic_blocks().len() {
154 /// Write out a human-readable textual representation for the given basic block.
155 fn write_basic_block(tcx: TyCtxt,
159 annotations: &FnvHashMap<Location, Vec<Annotation>>)
161 let data = &mir[block];
163 // Basic block label at the top.
164 writeln!(w, "{}{:?}: {{", INDENT, block)?;
166 // List of statements in the middle.
167 let mut current_location = Location { block: block, statement_index: 0 };
168 for statement in &data.statements {
169 if let Some(ref annotations) = annotations.get(¤t_location) {
170 for annotation in annotations.iter() {
172 Annotation::EnterScope(id) =>
173 writeln!(w, "{0}{0}// Enter Scope({1})",
174 INDENT, id.index())?,
175 Annotation::ExitScope(id) =>
176 writeln!(w, "{0}{0}// Exit Scope({1})",
177 INDENT, id.index())?,
182 let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
183 writeln!(w, "{0:1$} // {2}",
186 comment(tcx, statement.source_info))?;
188 current_location.statement_index += 1;
191 // Terminator at the bottom.
192 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
193 writeln!(w, "{0:1$} // {2}",
196 comment(tcx, data.terminator().source_info))?;
198 writeln!(w, "{}}}\n", INDENT)
201 fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
202 format!("scope {} at {}", scope.index(), tcx.sess.codemap().span_to_string(span))
205 fn write_scope_tree(tcx: TyCtxt,
207 scope_tree: &FnvHashMap<VisibilityScope, Vec<VisibilityScope>>,
209 parent: VisibilityScope,
212 let indent = depth * INDENT.len();
214 let children = match scope_tree.get(&parent) {
215 Some(childs) => childs,
216 None => return Ok(()),
219 for &child in children {
220 let data = &mir.visibility_scopes[child];
221 assert_eq!(data.parent_scope, Some(parent));
222 writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
224 // User variable types (including the user's name in a comment).
225 for (id, var) in mir.var_decls.iter_enumerated() {
226 // Skip if not declared in this scope.
227 if var.source_info.scope != child {
231 let mut_str = if var.mutability == Mutability::Mut {
237 let indent = indent + INDENT.len();
238 let indented_var = format!("{0:1$}let {2}{3:?}: {4};",
244 writeln!(w, "{0:1$} // \"{2}\" in {3}",
248 comment(tcx, var.source_info))?;
251 write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;
253 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
259 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
260 /// local variables (both user-defined bindings and compiler temporaries).
261 fn write_mir_intro<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
266 write_mir_sig(tcx, src, mir, w)?;
269 // construct a scope tree and write it out
270 let mut scope_tree: FnvHashMap<VisibilityScope, Vec<VisibilityScope>> = FnvHashMap();
271 for (index, scope_data) in mir.visibility_scopes.iter().enumerate() {
272 if let Some(parent) = scope_data.parent_scope {
273 scope_tree.entry(parent)
275 .push(VisibilityScope::new(index));
277 // Only the argument scope has no parent, because it's the root.
278 assert_eq!(index, ARGUMENT_VISIBILITY_SCOPE.index());
282 write_scope_tree(tcx, mir, &scope_tree, w, ARGUMENT_VISIBILITY_SCOPE, 1)?;
284 write_mir_decls(mir, w)
287 fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut Write)
291 MirSource::Fn(_) => write!(w, "fn")?,
292 MirSource::Const(_) => write!(w, "const")?,
293 MirSource::Static(_, hir::MutImmutable) => write!(w, "static")?,
294 MirSource::Static(_, hir::MutMutable) => write!(w, "static mut")?,
295 MirSource::Promoted(_, i) => write!(w, "{:?} in", i)?
298 write!(w, " {}", tcx.node_path_str(src.item_id()))?;
300 if let MirSource::Fn(_) = src {
303 // fn argument types.
304 for (i, arg) in mir.arg_decls.iter_enumerated() {
308 write!(w, "{:?}: {}", Lvalue::Arg(i), arg.ty)?;
314 match mir.return_ty {
315 ty::FnOutput::FnConverging(ty) => write!(w, "{}", ty),
316 ty::FnOutput::FnDiverging => write!(w, "!"),
319 assert!(mir.arg_decls.is_empty());
320 write!(w, ": {} =", mir.return_ty.unwrap())
324 fn write_mir_decls(mir: &Mir, w: &mut Write) -> io::Result<()> {
325 // Compiler-introduced temporary types.
326 for (id, temp) in mir.temp_decls.iter_enumerated() {
327 writeln!(w, "{}let mut {:?}: {};", INDENT, id, temp.ty)?;
330 // Wrote any declaration? Add an empty line before the first block is printed.
331 if !mir.var_decls.is_empty() || !mir.temp_decls.is_empty() {