1 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
3 use rustc::mir::visit::Visitor;
4 use rustc::ty::{self, TyCtxt};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::indexed_vec::Idx;
8 use std::fmt::Write as _;
10 use std::io::{self, Write};
11 use std::path::{Path, PathBuf};
12 use super::graphviz::write_mir_fn_graphviz;
13 use crate::transform::MirSource;
15 const INDENT: &str = " ";
16 /// Alignment for lining up comments following MIR statements
17 pub(crate) const ALIGN: usize = 40;
19 /// An indication of where we are in the control flow graph. Used for printing
20 /// extra information in `dump_mir`
22 /// We have not started dumping the control flow graph, but we are about to.
25 /// We just finished dumping the control flow graph. This is right before EOF
28 /// We are about to start dumping the given basic block.
29 BeforeBlock(BasicBlock),
31 /// We are just about to dump the given statement or terminator.
32 BeforeLocation(Location),
34 /// We just dumped the given statement or terminator.
35 AfterLocation(Location),
37 /// We just dumped the terminator for a block but not the closing `}`.
38 AfterTerminator(BasicBlock),
41 /// If the session is properly configured, dumps a human-readable
42 /// representation of the mir into:
45 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
48 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
49 /// where `<filter>` takes the following forms:
51 /// - `all` -- dump MIR for all fns, all passes, all everything
52 /// - a filter defined by a set of substrings combined with `&` and `|`
53 /// (`&` has higher precedence). At least one of the `|`-separated groups
54 /// must match; an `|`-separated group matches if all of its `&`-separated
55 /// substrings are matched.
59 /// - `nll` == match if `nll` appears in the name
60 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
61 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
62 /// or `typeck` appears in the name.
63 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
64 /// or `typeck` and `bar` both appear in the name.
65 pub fn dump_mir<'tcx, F>(
67 pass_num: Option<&dyn Display>,
69 disambiguator: &dyn Display,
70 source: MirSource<'tcx>,
74 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
76 if !dump_enabled(tcx, pass_name, source) {
80 let node_path = ty::print::with_forced_impl_filename_line(|| {
81 // see notes on #41697 below
82 tcx.def_path_str(source.def_id())
84 dump_matched_mir_node(
96 pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, source: MirSource<'tcx>) -> bool {
97 let filters = match tcx.sess.opts.debugging_opts.dump_mir {
99 Some(ref filters) => filters,
101 let node_path = ty::print::with_forced_impl_filename_line(|| {
102 // see notes on #41697 below
103 tcx.def_path_str(source.def_id())
105 filters.split('|').any(|or_filter| {
106 or_filter.split('&').all(|and_filter| {
107 and_filter == "all" || pass_name.contains(and_filter) || node_path.contains(and_filter)
112 // #41697 -- we use `with_forced_impl_filename_line()` because
113 // `def_path_str()` would otherwise trigger `type_of`, and this can
114 // run while we are already attempting to evaluate `type_of`.
116 fn dump_matched_mir_node<'tcx, F>(
118 pass_num: Option<&dyn Display>,
121 disambiguator: &dyn Display,
122 source: MirSource<'tcx>,
126 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
128 let _: io::Result<()> = try {
129 let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?;
130 writeln!(file, "// MIR for `{}`", node_path)?;
131 writeln!(file, "// source = {:?}", source)?;
132 writeln!(file, "// pass_name = {}", pass_name)?;
133 writeln!(file, "// disambiguator = {}", disambiguator)?;
134 if let Some(ref layout) = body.generator_layout {
135 writeln!(file, "// generator_layout = {:?}", layout)?;
138 extra_data(PassWhere::BeforeCFG, &mut file)?;
139 write_user_type_annotations(body, &mut file)?;
140 write_mir_fn(tcx, source, body, &mut extra_data, &mut file)?;
141 extra_data(PassWhere::AfterCFG, &mut file)?;
144 if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
145 let _: io::Result<()> = try {
147 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
148 write_mir_fn_graphviz(tcx, source.def_id(), body, &mut file)?;
153 /// Returns the path to the filename where we should dump a given MIR.
154 /// Also used by other bits of code (e.g., NLL inference) that dump
155 /// graphviz data or other things.
159 pass_num: Option<&dyn Display>,
161 disambiguator: &dyn Display,
162 source: MirSource<'tcx>,
164 let promotion_id = match source.promoted {
165 Some(id) => format!("-{:?}", id),
166 None => String::new(),
169 let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
173 None => ".-------".to_string(),
174 Some(pass_num) => format!(".{}", pass_num),
178 let mut file_path = PathBuf::new();
179 file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
182 .def_path(source.def_id())
183 .to_filename_friendly_no_crate();
184 // All drop shims have the same DefId, so we have to add the type
185 // to get unique file names.
186 let shim_disambiguator = match source.instance {
187 ty::InstanceDef::DropGlue(_, Some(ty)) => {
188 // Unfortunately, pretty-printed typed are not very filename-friendly.
189 // We dome some filtering.
190 let mut s = ".".to_owned();
191 s.extend(ty.to_string()
193 .filter_map(|c| match c {
195 ':' | '<' | '>' => Some('_'),
203 let file_name = format!(
204 "rustc.{}{}{}{}.{}.{}.{}",
214 file_path.push(&file_name);
219 /// Attempts to open a file where we should dump a given MIR or other
220 /// bit of MIR-related data. Used by `mir-dump`, but also by other
221 /// bits of code (e.g., NLL inference) that dump graphviz data or
222 /// other things, and hence takes the extension as an argument.
223 pub(crate) fn create_dump_file(
226 pass_num: Option<&dyn Display>,
228 disambiguator: &dyn Display,
229 source: MirSource<'tcx>,
230 ) -> io::Result<fs::File> {
231 let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
232 if let Some(parent) = file_path.parent() {
233 fs::create_dir_all(parent)?;
235 fs::File::create(&file_path)
238 /// Write out a human-readable textual representation for the given MIR.
239 pub fn write_mir_pretty<'tcx>(
241 single: Option<DefId>,
243 ) -> io::Result<()> {
246 "// WARNING: This output format is intended for human consumers only"
250 "// and is subject to change without notice. Knock yourself out."
253 let mut first = true;
254 for def_id in dump_mir_def_ids(tcx, single) {
255 let body = &tcx.optimized_mir(def_id);
260 // Put empty lines between all items
264 write_mir_fn(tcx, MirSource::item(def_id), body, &mut |_, _| Ok(()), w)?;
266 for (i, body) in tcx.promoted_mir(def_id).iter_enumerated() {
268 let src = MirSource {
269 instance: ty::InstanceDef::Item(def_id),
272 write_mir_fn(tcx, src, body, &mut |_, _| Ok(()), w)?;
278 pub fn write_mir_fn<'tcx, F>(
280 src: MirSource<'tcx>,
286 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
288 write_mir_intro(tcx, src, body, w)?;
289 for block in body.basic_blocks().indices() {
290 extra_data(PassWhere::BeforeBlock(block), w)?;
291 write_basic_block(tcx, block, body, extra_data, w)?;
292 if block.index() + 1 != body.basic_blocks().len() {
301 /// Write out a human-readable textual representation for the given basic block.
302 pub fn write_basic_block<'tcx, F>(
310 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
312 let data = &body[block];
314 // Basic block label at the top.
315 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
316 writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
318 // List of statements in the middle.
319 let mut current_location = Location {
323 for statement in &data.statements {
324 extra_data(PassWhere::BeforeLocation(current_location), w)?;
325 let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
331 comment(tcx, statement.source_info),
335 write_extra(tcx, w, |visitor| {
336 visitor.visit_statement(statement, current_location);
339 extra_data(PassWhere::AfterLocation(current_location), w)?;
341 current_location.statement_index += 1;
344 // Terminator at the bottom.
345 extra_data(PassWhere::BeforeLocation(current_location), w)?;
346 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
352 comment(tcx, data.terminator().source_info),
356 write_extra(tcx, w, |visitor| {
357 visitor.visit_terminator(data.terminator(), current_location);
360 extra_data(PassWhere::AfterLocation(current_location), w)?;
361 extra_data(PassWhere::AfterTerminator(block), w)?;
363 writeln!(w, "{}}}", INDENT)
366 /// After we print the main statement, we sometimes dump extra
367 /// information. There's often a lot of little things "nuzzled up" in
369 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
371 F: FnMut(&mut ExtraComments<'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<'tcx> {
385 _tcx: TyCtxt<'tcx>, // don't need it now, but bet we will soon
386 comments: Vec<String>,
389 impl ExtraComments<'tcx> {
390 fn push(&mut self, lines: &str) {
391 for line in lines.split('\n') {
392 self.comments.push(line.to_string());
397 impl Visitor<'tcx> for ExtraComments<'tcx> {
398 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
399 self.super_constant(constant, location);
400 let Constant { span, ty, user_ty, literal } = constant;
401 self.push("mir::Constant");
402 self.push(&format!("+ span: {:?}", span));
403 self.push(&format!("+ ty: {:?}", ty));
404 if let Some(user_ty) = user_ty {
405 self.push(&format!("+ user_ty: {:?}", user_ty));
407 self.push(&format!("+ literal: {:?}", literal));
410 fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
411 self.super_const(constant);
412 let ty::Const { ty, val, .. } = constant;
413 self.push("ty::Const");
414 self.push(&format!("+ ty: {:?}", ty));
415 self.push(&format!("+ val: {:?}", val));
418 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
419 self.super_rvalue(rvalue, location);
421 Rvalue::Aggregate(kind, _) => match **kind {
422 AggregateKind::Closure(def_id, substs) => {
423 self.push("closure");
424 self.push(&format!("+ def_id: {:?}", def_id));
425 self.push(&format!("+ substs: {:#?}", substs));
428 AggregateKind::Generator(def_id, substs, movability) => {
429 self.push("generator");
430 self.push(&format!("+ def_id: {:?}", def_id));
431 self.push(&format!("+ substs: {:#?}", substs));
432 self.push(&format!("+ movability: {:?}", movability));
435 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
437 self.push(&format!("+ user_ty: {:?}", user_ty));
448 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
452 tcx.sess.source_map().span_to_string(span)
456 /// Prints local variables in a scope tree.
460 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
464 ) -> io::Result<()> {
465 let indent = depth * INDENT.len();
467 // Local variable types (including the user's name in a comment).
468 for (local, local_decl) in body.local_decls.iter_enumerated() {
469 if (1..body.arg_count+1).contains(&local.index()) {
470 // Skip over argument locals, they're printed in the signature.
474 if local_decl.source_info.scope != parent {
475 // Not declared in this scope.
479 let mut_str = if local_decl.mutability == Mutability::Mut {
485 let mut indented_decl = format!(
486 "{0:1$}let {2}{3:?}: {4:?}",
493 for user_ty in local_decl.user_ty.projections() {
494 write!(indented_decl, " as {:?}", user_ty).unwrap();
496 indented_decl.push_str(";");
498 let local_name = if local == RETURN_PLACE {
499 format!(" return place")
500 } else if let Some(name) = local_decl.name {
501 format!(" \"{}\"", name)
508 "{0:1$} //{2} in {3}",
512 comment(tcx, local_decl.source_info),
516 let children = match scope_tree.get(&parent) {
517 Some(childs) => childs,
518 None => return Ok(()),
521 for &child in children {
522 assert_eq!(body.source_scopes[child].parent_scope, Some(parent));
523 writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
524 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
525 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
531 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
532 /// local variables (both user-defined bindings and compiler temporaries).
533 pub fn write_mir_intro<'tcx>(
535 src: MirSource<'tcx>,
538 ) -> io::Result<()> {
539 write_mir_sig(tcx, src, body, w)?;
542 // construct a scope tree and write it out
543 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
544 for (index, scope_data) in body.source_scopes.iter().enumerate() {
545 if let Some(parent) = scope_data.parent_scope {
549 .push(SourceScope::new(index));
551 // Only the argument scope has no parent, because it's the root.
552 assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
556 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
558 // Add an empty line before the first block is printed.
566 src: MirSource<'tcx>,
569 ) -> io::Result<()> {
570 use rustc::hir::def::DefKind;
572 trace!("write_mir_sig: {:?}", src.instance);
573 let kind = tcx.def_kind(src.def_id());
574 let is_function = match kind {
576 | Some(DefKind::Method)
577 | Some(DefKind::Ctor(..)) => true,
578 _ => tcx.is_closure(src.def_id()),
580 match (kind, src.promoted) {
581 (_, Some(i)) => write!(w, "{:?} in ", i)?,
582 (Some(DefKind::Const), _)
583 | (Some(DefKind::AssocConst), _) => write!(w, "const ")?,
584 (Some(DefKind::Static), _) =>
585 write!(w, "static {}", if tcx.is_mutable_static(src.def_id()) { "mut " } else { "" })?,
586 (_, _) if is_function => write!(w, "fn ")?,
587 (None, _) => {}, // things like anon const, not an item
588 _ => bug!("Unexpected def kind {:?}", kind),
591 ty::print::with_forced_impl_filename_line(|| {
592 // see notes on #41697 elsewhere
593 write!(w, " {}", tcx.def_path_str(src.def_id()))
596 if src.promoted.is_none() && is_function {
599 // fn argument types.
600 for (i, arg) in body.args_iter().enumerate() {
604 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
607 write!(w, ") -> {}", body.return_ty())?;
609 assert_eq!(body.arg_count, 0);
610 write!(w, ": {} =", body.return_ty())?;
613 if let Some(yield_ty) = body.yield_ty {
615 writeln!(w, "yields {}", yield_ty)?;
619 // Next thing that gets printed is the opening {
624 fn write_user_type_annotations(body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
625 if !body.user_type_annotations.is_empty() {
626 writeln!(w, "| User Type Annotations")?;
628 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
629 writeln!(w, "| {:?}: {:?} at {:?}", index.index(), annotation.user_ty, annotation.span)?;
631 if !body.user_type_annotations.is_empty() {
637 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
638 if let Some(i) = single {
641 tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()