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, LOCAL_CRATE};
14 use rustc::mir::visit::Visitor;
15 use rustc::ty::{self, TyCtxt};
16 use rustc::ty::item_path;
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_data_structures::indexed_vec::Idx;
19 use std::fmt::Display;
21 use std::io::{self, Write};
22 use std::path::{Path, PathBuf};
23 use super::graphviz::write_mir_fn_graphviz;
24 use transform::MirSource;
26 const INDENT: &'static str = " ";
27 /// Alignment for lining up comments following MIR statements
28 pub(crate) const ALIGN: usize = 40;
30 /// An indication of where we are in the control flow graph. Used for printing
31 /// extra information in `dump_mir`
33 /// We have not started dumping the control flow graph, but we are about to.
36 /// We just finished dumping the control flow graph. This is right before EOF
39 /// We are about to start dumping the given basic block.
40 BeforeBlock(BasicBlock),
42 /// We are just about to dump the given statement or terminator.
43 BeforeLocation(Location),
45 /// We just dumped the given statement or terminator.
46 AfterLocation(Location),
48 /// We just dumped the terminator for a block but not the closing `}`.
49 AfterTerminator(BasicBlock),
52 /// If the session is properly configured, dumps a human-readable
53 /// representation of the mir into:
56 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
59 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
60 /// where `<filter>` takes the following forms:
62 /// - `all` -- dump MIR for all fns, all passes, all everything
63 /// - a filter defined by a set of substrings combined with `&` and `|`
64 /// (`&` has higher precedence). At least one of the `|`-separated groups
65 /// must match; an `|`-separated group matches if all of its `&`-separated
66 /// substrings are matched.
70 /// - `nll` == match if `nll` appears in the name
71 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
72 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
73 /// or `typeck` appears in the name.
74 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
75 /// or `typeck` and `bar` both appear in the name.
76 pub fn dump_mir<'a, 'gcx, 'tcx, F>(
77 tcx: TyCtxt<'a, 'gcx, 'tcx>,
78 pass_num: Option<&dyn Display>,
80 disambiguator: &dyn Display,
85 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
87 if !dump_enabled(tcx, pass_name, source) {
91 let node_path = item_path::with_forced_impl_filename_line(|| {
92 // see notes on #41697 below
93 tcx.item_path_str(source.def_id)
95 dump_matched_mir_node(
107 pub fn dump_enabled<'a, 'gcx, 'tcx>(
108 tcx: TyCtxt<'a, 'gcx, 'tcx>,
112 let filters = match tcx.sess.opts.debugging_opts.dump_mir {
113 None => return false,
114 Some(ref filters) => filters,
116 let node_path = item_path::with_forced_impl_filename_line(|| {
117 // see notes on #41697 below
118 tcx.item_path_str(source.def_id)
120 filters.split("|").any(|or_filter| {
121 or_filter.split("&").all(|and_filter| {
122 and_filter == "all" || pass_name.contains(and_filter) || node_path.contains(and_filter)
127 // #41697 -- we use `with_forced_impl_filename_line()` because
128 // `item_path_str()` would otherwise trigger `type_of`, and this can
129 // run while we are already attempting to evaluate `type_of`.
131 fn dump_matched_mir_node<'a, 'gcx, 'tcx, F>(
132 tcx: TyCtxt<'a, 'gcx, 'tcx>,
133 pass_num: Option<&dyn Display>,
136 disambiguator: &dyn Display,
141 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
143 let _: io::Result<()> = do catch {
144 let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?;
145 writeln!(file, "// MIR for `{}`", node_path)?;
146 writeln!(file, "// source = {:?}", source)?;
147 writeln!(file, "// pass_name = {}", pass_name)?;
148 writeln!(file, "// disambiguator = {}", disambiguator)?;
149 if let Some(ref layout) = mir.generator_layout {
150 writeln!(file, "// generator_layout = {:?}", layout)?;
153 extra_data(PassWhere::BeforeCFG, &mut file)?;
154 write_mir_fn(tcx, source, mir, &mut extra_data, &mut file)?;
155 extra_data(PassWhere::AfterCFG, &mut file)?;
158 if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
159 let _: io::Result<()> = do catch {
161 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
162 write_mir_fn_graphviz(tcx, source.def_id, mir, &mut file)?;
167 /// Returns the path to the filename where we should dump a given MIR.
168 /// Also used by other bits of code (e.g., NLL inference) that dump
169 /// graphviz data or other things.
171 tcx: TyCtxt<'_, '_, '_>,
173 pass_num: Option<&dyn Display>,
175 disambiguator: &dyn Display,
178 let promotion_id = match source.promoted {
179 Some(id) => format!("-{:?}", id),
180 None => String::new(),
183 let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
187 None => format!(".-------"),
188 Some(pass_num) => format!(".{}", pass_num),
192 let mut file_path = PathBuf::new();
193 file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
195 let item_name = tcx.hir
196 .def_path(source.def_id)
197 .to_filename_friendly_no_crate();
199 let file_name = format!(
200 "rustc.{}{}{}.{}.{}.{}",
209 file_path.push(&file_name);
214 /// Attempts to open a file where we should dump a given MIR or other
215 /// bit of MIR-related data. Used by `mir-dump`, but also by other
216 /// bits of code (e.g., NLL inference) that dump graphviz data or
217 /// other things, and hence takes the extension as an argument.
218 pub(crate) fn create_dump_file(
219 tcx: TyCtxt<'_, '_, '_>,
221 pass_num: Option<&dyn Display>,
223 disambiguator: &dyn Display,
225 ) -> io::Result<fs::File> {
226 let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
227 if let Some(parent) = file_path.parent() {
228 fs::create_dir_all(parent)?;
230 fs::File::create(&file_path)
233 /// Write out a human-readable textual representation for the given MIR.
234 pub fn write_mir_pretty<'a, 'gcx, 'tcx>(
235 tcx: TyCtxt<'a, 'gcx, 'tcx>,
236 single: Option<DefId>,
238 ) -> io::Result<()> {
241 "// WARNING: This output format is intended for human consumers only"
245 "// and is subject to change without notice. Knock yourself out."
248 let mut first = true;
249 for def_id in dump_mir_def_ids(tcx, single) {
250 let mir = &tcx.optimized_mir(def_id);
255 // Put empty lines between all items
259 write_mir_fn(tcx, MirSource::item(def_id), mir, &mut |_, _| Ok(()), w)?;
261 for (i, mir) in mir.promoted.iter_enumerated() {
263 let src = MirSource {
267 write_mir_fn(tcx, src, mir, &mut |_, _| Ok(()), w)?;
273 pub fn write_mir_fn<'a, 'gcx, 'tcx, F>(
274 tcx: TyCtxt<'a, 'gcx, 'tcx>,
281 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
283 write_mir_intro(tcx, src, mir, w)?;
284 for block in mir.basic_blocks().indices() {
285 extra_data(PassWhere::BeforeBlock(block), w)?;
286 write_basic_block(tcx, block, mir, extra_data, w)?;
287 if block.index() + 1 != mir.basic_blocks().len() {
296 /// Write out a human-readable textual representation for the given basic block.
297 pub fn write_basic_block<'cx, 'gcx, 'tcx, F>(
298 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
305 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
307 let data = &mir[block];
309 // Basic block label at the top.
310 let cleanup_text = if data.is_cleanup { " // cleanup" } else { "" };
311 let lbl = format!("{}{:?}: {{", INDENT, block);
312 writeln!(w, "{0:1$}{2}", lbl, ALIGN, cleanup_text)?;
314 // List of statements in the middle.
315 let mut current_location = Location {
319 for statement in &data.statements {
320 extra_data(PassWhere::BeforeLocation(current_location), w)?;
321 let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
327 comment(tcx, statement.source_info),
331 write_extra(tcx, w, |visitor| {
332 visitor.visit_statement(current_location.block, statement, current_location);
335 extra_data(PassWhere::AfterLocation(current_location), w)?;
337 current_location.statement_index += 1;
340 // Terminator at the bottom.
341 extra_data(PassWhere::BeforeLocation(current_location), w)?;
342 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
348 comment(tcx, data.terminator().source_info),
352 write_extra(tcx, w, |visitor| {
353 visitor.visit_terminator(current_location.block, data.terminator(), current_location);
356 extra_data(PassWhere::AfterLocation(current_location), w)?;
357 extra_data(PassWhere::AfterTerminator(block), w)?;
359 writeln!(w, "{}}}", INDENT)
362 /// After we print the main statement, we sometimes dump extra
363 /// information. There's often a lot of little things "nuzzled up" in
365 fn write_extra<'cx, 'gcx, 'tcx, F>(
366 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
367 write: &mut dyn Write,
371 F: FnMut(&mut ExtraComments<'cx, 'gcx, 'tcx>),
373 let mut extra_comments = ExtraComments {
377 visit_op(&mut extra_comments);
378 for comment in extra_comments.comments {
379 writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
384 struct ExtraComments<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
385 _tcx: TyCtxt<'cx, 'gcx, 'tcx>, // don't need it now, but bet we will soon
386 comments: Vec<String>,
389 impl<'cx, 'gcx, 'tcx> ExtraComments<'cx, 'gcx, 'tcx> {
390 fn push(&mut self, lines: &str) {
391 for line in lines.split("\n") {
392 self.comments.push(line.to_string());
397 impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ExtraComments<'cx, 'gcx, 'tcx> {
398 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
399 self.super_constant(constant, location);
400 let Constant { span, ty, literal } = constant;
401 self.push(&format!("mir::Constant"));
402 self.push(&format!("+ span: {:?}", span));
403 self.push(&format!("+ ty: {:?}", ty));
404 self.push(&format!("+ literal: {:?}", literal));
407 fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
408 self.super_const(constant);
409 let ty::Const { ty, val, .. } = constant;
410 self.push(&format!("ty::Const"));
411 self.push(&format!("+ ty: {:?}", ty));
412 self.push(&format!("+ val: {:?}", val));
415 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
416 self.super_rvalue(rvalue, location);
418 Rvalue::Aggregate(kind, _) => match **kind {
419 AggregateKind::Closure(def_id, substs) => {
420 self.push(&format!("closure"));
421 self.push(&format!("+ def_id: {:?}", def_id));
422 self.push(&format!("+ substs: {:#?}", substs));
425 AggregateKind::Generator(def_id, substs, movability) => {
426 self.push(&format!("generator"));
427 self.push(&format!("+ def_id: {:?}", def_id));
428 self.push(&format!("+ substs: {:#?}", substs));
429 self.push(&format!("+ movability: {:?}", movability));
440 fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
444 tcx.sess.codemap().span_to_string(span)
448 /// Prints user-defined variables in a scope tree.
450 /// Returns the total number of variables printed.
454 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
458 ) -> io::Result<()> {
459 let indent = depth * INDENT.len();
461 let children = match scope_tree.get(&parent) {
462 Some(childs) => childs,
463 None => return Ok(()),
466 for &child in children {
467 let data = &mir.source_scopes[child];
468 assert_eq!(data.parent_scope, Some(parent));
469 writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
471 // User variable types (including the user's name in a comment).
472 for local in mir.vars_iter() {
473 let var = &mir.local_decls[local];
474 let (name, source_info) = if var.source_info.scope == child {
475 (var.name.unwrap(), var.source_info)
477 // Not a variable or not declared in this scope.
481 let mut_str = if var.mutability == Mutability::Mut {
487 let indent = indent + INDENT.len();
488 let indented_var = format!(
489 "{0:1$}let {2}{3:?}: {4:?};",
498 "{0:1$} // \"{2}\" in {3}",
502 comment(tcx, source_info)
506 write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;
508 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
514 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
515 /// local variables (both user-defined bindings and compiler temporaries).
516 pub fn write_mir_intro<'a, 'gcx, 'tcx>(
517 tcx: TyCtxt<'a, 'gcx, 'tcx>,
521 ) -> io::Result<()> {
522 write_mir_sig(tcx, src, mir, w)?;
525 // construct a scope tree and write it out
526 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = FxHashMap();
527 for (index, scope_data) in mir.source_scopes.iter().enumerate() {
528 if let Some(parent) = scope_data.parent_scope {
532 .push(SourceScope::new(index));
534 // Only the argument scope has no parent, because it's the root.
535 assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
539 // Print return place
540 let indented_retptr = format!("{}let mut {:?}: {};",
543 mir.local_decls[RETURN_PLACE].ty);
544 writeln!(w, "{0:1$} // return place",
548 write_scope_tree(tcx, mir, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
550 write_temp_decls(mir, w)?;
552 // Add an empty line before the first block is printed.
558 fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
559 let id = tcx.hir.as_local_node_id(src.def_id).unwrap();
560 let body_owner_kind = tcx.hir.body_owner_kind(id);
561 match (body_owner_kind, src.promoted) {
562 (_, Some(i)) => write!(w, "{:?} in", i)?,
563 (hir::BodyOwnerKind::Fn, _) => write!(w, "fn")?,
564 (hir::BodyOwnerKind::Const, _) => write!(w, "const")?,
565 (hir::BodyOwnerKind::Static(hir::MutImmutable), _) => write!(w, "static")?,
566 (hir::BodyOwnerKind::Static(hir::MutMutable), _) => write!(w, "static mut")?,
569 item_path::with_forced_impl_filename_line(|| {
570 // see notes on #41697 elsewhere
571 write!(w, " {}", tcx.item_path_str(src.def_id))
574 match (body_owner_kind, src.promoted) {
575 (hir::BodyOwnerKind::Fn, None) => {
578 // fn argument types.
579 for (i, arg) in mir.args_iter().enumerate() {
583 write!(w, "{:?}: {}", Place::Local(arg), mir.local_decls[arg].ty)?;
586 write!(w, ") -> {}", mir.return_ty())?;
588 (hir::BodyOwnerKind::Const, _) | (hir::BodyOwnerKind::Static(_), _) | (_, Some(_)) => {
589 assert_eq!(mir.arg_count, 0);
590 write!(w, ": {} =", mir.return_ty())?;
594 if let Some(yield_ty) = mir.yield_ty {
596 writeln!(w, "yields {}", yield_ty)?;
602 fn write_temp_decls(mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
603 // Compiler-introduced temporary types.
604 for temp in mir.temps_iter() {
607 "{}let mut {:?}: {};",
610 mir.local_decls[temp].ty
617 pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option<DefId>) -> Vec<DefId> {
618 if let Some(i) = single {
621 tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()