]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/pretty.rs
7965a9499a16cc6de0a1b4deaaee38a0a99c7551
[rust.git] / compiler / rustc_middle / src / mir / pretty.rs
1 use std::collections::BTreeSet;
2 use std::fmt::Display;
3 use std::fmt::Write as _;
4 use std::fs;
5 use std::io::{self, Write};
6 use std::path::{Path, PathBuf};
7
8 use super::graphviz::write_mir_fn_graphviz;
9 use super::spanview::write_mir_fn_spanview;
10 use either::Either;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_hir::def_id::DefId;
13 use rustc_index::vec::Idx;
14 use rustc_middle::mir::interpret::{
15     read_target_uint, AllocId, Allocation, ConstAllocation, ConstValue, GlobalAlloc, Pointer,
16     Provenance,
17 };
18 use rustc_middle::mir::visit::Visitor;
19 use rustc_middle::mir::MirSource;
20 use rustc_middle::mir::*;
21 use rustc_middle::ty::{self, TyCtxt};
22 use rustc_target::abi::Size;
23
24 const INDENT: &str = "    ";
25 /// Alignment for lining up comments following MIR statements
26 pub(crate) const ALIGN: usize = 40;
27
28 /// An indication of where we are in the control flow graph. Used for printing
29 /// extra information in `dump_mir`
30 pub enum PassWhere {
31     /// We have not started dumping the control flow graph, but we are about to.
32     BeforeCFG,
33
34     /// We just finished dumping the control flow graph. This is right before EOF
35     AfterCFG,
36
37     /// We are about to start dumping the given basic block.
38     BeforeBlock(BasicBlock),
39
40     /// We are just about to dump the given statement or terminator.
41     BeforeLocation(Location),
42
43     /// We just dumped the given statement or terminator.
44     AfterLocation(Location),
45
46     /// We just dumped the terminator for a block but not the closing `}`.
47     AfterTerminator(BasicBlock),
48 }
49
50 /// If the session is properly configured, dumps a human-readable
51 /// representation of the mir into:
52 ///
53 /// ```text
54 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
55 /// ```
56 ///
57 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
58 /// where `<filter>` takes the following forms:
59 ///
60 /// - `all` -- dump MIR for all fns, all passes, all everything
61 /// - a filter defined by a set of substrings combined with `&` and `|`
62 ///   (`&` has higher precedence). At least one of the `|`-separated groups
63 ///   must match; an `|`-separated group matches if all of its `&`-separated
64 ///   substrings are matched.
65 ///
66 /// Example:
67 ///
68 /// - `nll` == match if `nll` appears in the name
69 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
70 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
71 ///   or `typeck` appears in the name.
72 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
73 ///   or `typeck` and `bar` both appear in the name.
74 #[inline]
75 pub fn dump_mir<'tcx, F>(
76     tcx: TyCtxt<'tcx>,
77     pass_num: Option<&dyn Display>,
78     pass_name: &str,
79     disambiguator: &dyn Display,
80     body: &Body<'tcx>,
81     extra_data: F,
82 ) where
83     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
84 {
85     if !dump_enabled(tcx, pass_name, body.source.def_id()) {
86         return;
87     }
88
89     dump_matched_mir_node(tcx, pass_num, pass_name, disambiguator, body, extra_data);
90 }
91
92 pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) -> bool {
93     let Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir else {
94         return false;
95     };
96     // see notes on #41697 below
97     let node_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(def_id));
98     filters.split('|').any(|or_filter| {
99         or_filter.split('&').all(|and_filter| {
100             let and_filter_trimmed = and_filter.trim();
101             and_filter_trimmed == "all"
102                 || pass_name.contains(and_filter_trimmed)
103                 || node_path.contains(and_filter_trimmed)
104         })
105     })
106 }
107
108 // #41697 -- we use `with_forced_impl_filename_line()` because
109 // `def_path_str()` would otherwise trigger `type_of`, and this can
110 // run while we are already attempting to evaluate `type_of`.
111
112 fn dump_matched_mir_node<'tcx, F>(
113     tcx: TyCtxt<'tcx>,
114     pass_num: Option<&dyn Display>,
115     pass_name: &str,
116     disambiguator: &dyn Display,
117     body: &Body<'tcx>,
118     mut extra_data: F,
119 ) where
120     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
121 {
122     let _: io::Result<()> = try {
123         let mut file =
124             create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body.source)?;
125         // see notes on #41697 above
126         let def_path =
127             ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
128         write!(file, "// MIR for `{}", def_path)?;
129         match body.source.promoted {
130             None => write!(file, "`")?,
131             Some(promoted) => write!(file, "::{:?}`", promoted)?,
132         }
133         writeln!(file, " {} {}", disambiguator, pass_name)?;
134         if let Some(ref layout) = body.generator_layout() {
135             writeln!(file, "/* generator_layout = {:#?} */", layout)?;
136         }
137         writeln!(file)?;
138         extra_data(PassWhere::BeforeCFG, &mut file)?;
139         write_user_type_annotations(tcx, body, &mut file)?;
140         write_mir_fn(tcx, body, &mut extra_data, &mut file)?;
141         extra_data(PassWhere::AfterCFG, &mut file)?;
142     };
143
144     if tcx.sess.opts.unstable_opts.dump_mir_graphviz {
145         let _: io::Result<()> = try {
146             let mut file =
147                 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, body.source)?;
148             write_mir_fn_graphviz(tcx, body, false, &mut file)?;
149         };
150     }
151
152     if let Some(spanview) = tcx.sess.opts.unstable_opts.dump_mir_spanview {
153         let _: io::Result<()> = try {
154             let file_basename =
155                 dump_file_basename(tcx, pass_num, pass_name, disambiguator, body.source);
156             let mut file = create_dump_file_with_basename(tcx, &file_basename, "html")?;
157             if body.source.def_id().is_local() {
158                 write_mir_fn_spanview(tcx, body, spanview, &file_basename, &mut file)?;
159             }
160         };
161     }
162 }
163
164 /// Returns the file basename portion (without extension) of a filename path
165 /// where we should dump a MIR representation output files.
166 fn dump_file_basename<'tcx>(
167     tcx: TyCtxt<'tcx>,
168     pass_num: Option<&dyn Display>,
169     pass_name: &str,
170     disambiguator: &dyn Display,
171     source: MirSource<'tcx>,
172 ) -> String {
173     let promotion_id = match source.promoted {
174         Some(id) => format!("-{:?}", id),
175         None => String::new(),
176     };
177
178     let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
179         String::new()
180     } else {
181         match pass_num {
182             None => ".-------".to_string(),
183             Some(pass_num) => format!(".{}", pass_num),
184         }
185     };
186
187     let crate_name = tcx.crate_name(source.def_id().krate);
188     let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
189     // All drop shims have the same DefId, so we have to add the type
190     // to get unique file names.
191     let shim_disambiguator = match source.instance {
192         ty::InstanceDef::DropGlue(_, Some(ty)) => {
193             // Unfortunately, pretty-printed typed are not very filename-friendly.
194             // We dome some filtering.
195             let mut s = ".".to_owned();
196             s.extend(ty.to_string().chars().filter_map(|c| match c {
197                 ' ' => None,
198                 ':' | '<' | '>' => Some('_'),
199                 c => Some(c),
200             }));
201             s
202         }
203         _ => String::new(),
204     };
205
206     format!(
207         "{}.{}{}{}{}.{}.{}",
208         crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator,
209     )
210 }
211
212 /// Returns the path to the filename where we should dump a given MIR.
213 /// Also used by other bits of code (e.g., NLL inference) that dump
214 /// graphviz data or other things.
215 fn dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf {
216     let mut file_path = PathBuf::new();
217     file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
218
219     let file_name = format!("{}.{}", basename, extension,);
220
221     file_path.push(&file_name);
222
223     file_path
224 }
225
226 /// Attempts to open the MIR dump file with the given name and extension.
227 fn create_dump_file_with_basename(
228     tcx: TyCtxt<'_>,
229     file_basename: &str,
230     extension: &str,
231 ) -> io::Result<io::BufWriter<fs::File>> {
232     let file_path = dump_path(tcx, file_basename, extension);
233     if let Some(parent) = file_path.parent() {
234         fs::create_dir_all(parent).map_err(|e| {
235             io::Error::new(
236                 e.kind(),
237                 format!("IO error creating MIR dump directory: {:?}; {}", parent, e),
238             )
239         })?;
240     }
241     Ok(io::BufWriter::new(fs::File::create(&file_path).map_err(|e| {
242         io::Error::new(e.kind(), format!("IO error creating MIR dump file: {:?}; {}", file_path, e))
243     })?))
244 }
245
246 /// Attempts to open a file where we should dump a given MIR or other
247 /// bit of MIR-related data. Used by `mir-dump`, but also by other
248 /// bits of code (e.g., NLL inference) that dump graphviz data or
249 /// other things, and hence takes the extension as an argument.
250 pub fn create_dump_file<'tcx>(
251     tcx: TyCtxt<'tcx>,
252     extension: &str,
253     pass_num: Option<&dyn Display>,
254     pass_name: &str,
255     disambiguator: &dyn Display,
256     source: MirSource<'tcx>,
257 ) -> io::Result<io::BufWriter<fs::File>> {
258     create_dump_file_with_basename(
259         tcx,
260         &dump_file_basename(tcx, pass_num, pass_name, disambiguator, source),
261         extension,
262     )
263 }
264
265 /// Write out a human-readable textual representation for the given MIR.
266 pub fn write_mir_pretty<'tcx>(
267     tcx: TyCtxt<'tcx>,
268     single: Option<DefId>,
269     w: &mut dyn Write,
270 ) -> io::Result<()> {
271     writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
272     writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
273
274     let mut first = true;
275     for def_id in dump_mir_def_ids(tcx, single) {
276         if first {
277             first = false;
278         } else {
279             // Put empty lines between all items
280             writeln!(w)?;
281         }
282
283         let render_body = |w: &mut dyn Write, body| -> io::Result<()> {
284             write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
285
286             for body in tcx.promoted_mir(def_id) {
287                 writeln!(w)?;
288                 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
289             }
290             Ok(())
291         };
292
293         // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
294         if tcx.is_const_fn_raw(def_id) {
295             render_body(w, tcx.optimized_mir(def_id))?;
296             writeln!(w)?;
297             writeln!(w, "// MIR FOR CTFE")?;
298             // Do not use `render_body`, as that would render the promoteds again, but these
299             // are shared between mir_for_ctfe and optimized_mir
300             write_mir_fn(tcx, tcx.mir_for_ctfe(def_id), &mut |_, _| Ok(()), w)?;
301         } else {
302             let instance_mir =
303                 tcx.instance_mir(ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)));
304             render_body(w, instance_mir)?;
305         }
306     }
307     Ok(())
308 }
309
310 /// Write out a human-readable textual representation for the given function.
311 pub fn write_mir_fn<'tcx, F>(
312     tcx: TyCtxt<'tcx>,
313     body: &Body<'tcx>,
314     extra_data: &mut F,
315     w: &mut dyn Write,
316 ) -> io::Result<()>
317 where
318     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
319 {
320     write_mir_intro(tcx, body, w)?;
321     for block in body.basic_blocks.indices() {
322         extra_data(PassWhere::BeforeBlock(block), w)?;
323         write_basic_block(tcx, block, body, extra_data, w)?;
324         if block.index() + 1 != body.basic_blocks.len() {
325             writeln!(w)?;
326         }
327     }
328
329     writeln!(w, "}}")?;
330
331     write_allocations(tcx, body, w)?;
332
333     Ok(())
334 }
335
336 /// Write out a human-readable textual representation for the given basic block.
337 pub fn write_basic_block<'tcx, F>(
338     tcx: TyCtxt<'tcx>,
339     block: BasicBlock,
340     body: &Body<'tcx>,
341     extra_data: &mut F,
342     w: &mut dyn Write,
343 ) -> io::Result<()>
344 where
345     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
346 {
347     let data = &body[block];
348
349     // Basic block label at the top.
350     let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
351     writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
352
353     // List of statements in the middle.
354     let mut current_location = Location { block, statement_index: 0 };
355     for statement in &data.statements {
356         extra_data(PassWhere::BeforeLocation(current_location), w)?;
357         let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
358         writeln!(
359             w,
360             "{:A$} // {}{}",
361             indented_body,
362             if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
363             comment(tcx, statement.source_info, body.span),
364             A = ALIGN,
365         )?;
366
367         write_extra(tcx, w, |visitor| {
368             visitor.visit_statement(statement, current_location);
369         })?;
370
371         extra_data(PassWhere::AfterLocation(current_location), w)?;
372
373         current_location.statement_index += 1;
374     }
375
376     // Terminator at the bottom.
377     extra_data(PassWhere::BeforeLocation(current_location), w)?;
378     let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
379     writeln!(
380         w,
381         "{:A$} // {}{}",
382         indented_terminator,
383         if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
384         comment(tcx, data.terminator().source_info, body.span),
385         A = ALIGN,
386     )?;
387
388     write_extra(tcx, w, |visitor| {
389         visitor.visit_terminator(data.terminator(), current_location);
390     })?;
391
392     extra_data(PassWhere::AfterLocation(current_location), w)?;
393     extra_data(PassWhere::AfterTerminator(block), w)?;
394
395     writeln!(w, "{}}}", INDENT)
396 }
397
398 /// After we print the main statement, we sometimes dump extra
399 /// information. There's often a lot of little things "nuzzled up" in
400 /// a statement.
401 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
402 where
403     F: FnMut(&mut ExtraComments<'tcx>),
404 {
405     let mut extra_comments = ExtraComments { tcx, comments: vec![] };
406     visit_op(&mut extra_comments);
407     for comment in extra_comments.comments {
408         writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
409     }
410     Ok(())
411 }
412
413 struct ExtraComments<'tcx> {
414     tcx: TyCtxt<'tcx>,
415     comments: Vec<String>,
416 }
417
418 impl<'tcx> ExtraComments<'tcx> {
419     fn push(&mut self, lines: &str) {
420         for line in lines.split('\n') {
421             self.comments.push(line.to_string());
422         }
423     }
424 }
425
426 fn use_verbose<'tcx>(ty: Ty<'tcx>, fn_def: bool) -> bool {
427     match *ty.kind() {
428         ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
429         // Unit type
430         ty::Tuple(g_args) if g_args.is_empty() => false,
431         ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
432         ty::Array(ty, _) => use_verbose(ty, fn_def),
433         ty::FnDef(..) => fn_def,
434         _ => true,
435     }
436 }
437
438 impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
439     fn visit_constant(&mut self, constant: &Constant<'tcx>, _location: Location) {
440         let Constant { span, user_ty, literal } = constant;
441         if use_verbose(literal.ty(), true) {
442             self.push("mir::Constant");
443             self.push(&format!(
444                 "+ span: {}",
445                 self.tcx.sess.source_map().span_to_embeddable_string(*span)
446             ));
447             if let Some(user_ty) = user_ty {
448                 self.push(&format!("+ user_ty: {:?}", user_ty));
449             }
450
451             // FIXME: this is a poor version of `pretty_print_const_value`.
452             let fmt_val = |val: &ConstValue<'tcx>| match val {
453                 ConstValue::ZeroSized => format!("<ZST>"),
454                 ConstValue::Scalar(s) => format!("Scalar({:?})", s),
455                 ConstValue::Slice { .. } => format!("Slice(..)"),
456                 ConstValue::ByRef { .. } => format!("ByRef(..)"),
457             };
458
459             let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree {
460                 ty::ValTree::Leaf(leaf) => format!("ValTree::Leaf({:?})", leaf),
461                 ty::ValTree::Branch(_) => format!("ValTree::Branch(..)"),
462             };
463
464             let val = match literal {
465                 ConstantKind::Ty(ct) => match ct.kind() {
466                     ty::ConstKind::Param(p) => format!("Param({})", p),
467                     ty::ConstKind::Unevaluated(uv) => {
468                         format!(
469                             "Unevaluated({}, {:?})",
470                             self.tcx.def_path_str(uv.def.did),
471                             uv.substs,
472                         )
473                     }
474                     ty::ConstKind::Value(val) => format!("Value({})", fmt_valtree(&val)),
475                     ty::ConstKind::Error(_) => "Error".to_string(),
476                     // These variants shouldn't exist in the MIR.
477                     ty::ConstKind::Placeholder(_)
478                     | ty::ConstKind::Infer(_)
479                     | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", literal),
480                 },
481                 ConstantKind::Unevaluated(uv, _) => {
482                     format!(
483                         "Unevaluated({}, {:?}, {:?})",
484                         self.tcx.def_path_str(uv.def.did),
485                         uv.substs,
486                         uv.promoted,
487                     )
488                 }
489                 // To keep the diffs small, we render this like we render `ty::Const::Value`.
490                 //
491                 // This changes once `ty::Const::Value` is represented using valtrees.
492                 ConstantKind::Val(val, _) => format!("Value({})", fmt_val(&val)),
493             };
494
495             // This reflects what `Const` looked liked before `val` was renamed
496             // as `kind`. We print it like this to avoid having to update
497             // expected output in a lot of tests.
498             self.push(&format!("+ literal: Const {{ ty: {}, val: {} }}", literal.ty(), val));
499         }
500     }
501
502     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
503         self.super_rvalue(rvalue, location);
504         if let Rvalue::Aggregate(kind, _) = rvalue {
505             match **kind {
506                 AggregateKind::Closure(def_id, substs) => {
507                     self.push("closure");
508                     self.push(&format!("+ def_id: {:?}", def_id));
509                     self.push(&format!("+ substs: {:#?}", substs));
510                 }
511
512                 AggregateKind::Generator(def_id, substs, movability) => {
513                     self.push("generator");
514                     self.push(&format!("+ def_id: {:?}", def_id));
515                     self.push(&format!("+ substs: {:#?}", substs));
516                     self.push(&format!("+ movability: {:?}", movability));
517                 }
518
519                 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
520                     self.push("adt");
521                     self.push(&format!("+ user_ty: {:?}", user_ty));
522                 }
523
524                 _ => {}
525             }
526         }
527     }
528 }
529
530 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo, function_span: Span) -> String {
531     let location = if tcx.sess.opts.unstable_opts.mir_pretty_relative_line_numbers {
532         tcx.sess.source_map().span_to_relative_line_string(span, function_span)
533     } else {
534         tcx.sess.source_map().span_to_embeddable_string(span)
535     };
536
537     format!("scope {} at {}", scope.index(), location,)
538 }
539
540 /// Prints local variables in a scope tree.
541 fn write_scope_tree(
542     tcx: TyCtxt<'_>,
543     body: &Body<'_>,
544     scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
545     w: &mut dyn Write,
546     parent: SourceScope,
547     depth: usize,
548 ) -> io::Result<()> {
549     let indent = depth * INDENT.len();
550
551     // Local variable debuginfo.
552     for var_debug_info in &body.var_debug_info {
553         if var_debug_info.source_info.scope != parent {
554             // Not declared in this scope.
555             continue;
556         }
557
558         let indented_debug_info = format!(
559             "{0:1$}debug {2} => {3:?};",
560             INDENT, indent, var_debug_info.name, var_debug_info.value,
561         );
562
563         writeln!(
564             w,
565             "{0:1$} // in {2}",
566             indented_debug_info,
567             ALIGN,
568             comment(tcx, var_debug_info.source_info, body.span),
569         )?;
570     }
571
572     // Local variable types.
573     for (local, local_decl) in body.local_decls.iter_enumerated() {
574         if (1..body.arg_count + 1).contains(&local.index()) {
575             // Skip over argument locals, they're printed in the signature.
576             continue;
577         }
578
579         if local_decl.source_info.scope != parent {
580             // Not declared in this scope.
581             continue;
582         }
583
584         let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
585
586         let mut indented_decl =
587             format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
588         if let Some(user_ty) = &local_decl.user_ty {
589             for user_ty in user_ty.projections() {
590                 write!(indented_decl, " as {:?}", user_ty).unwrap();
591             }
592         }
593         indented_decl.push(';');
594
595         let local_name = if local == RETURN_PLACE { " return place" } else { "" };
596
597         writeln!(
598             w,
599             "{0:1$} //{2} in {3}",
600             indented_decl,
601             ALIGN,
602             local_name,
603             comment(tcx, local_decl.source_info, body.span),
604         )?;
605     }
606
607     let Some(children) = scope_tree.get(&parent) else {
608         return Ok(());
609     };
610
611     for &child in children {
612         let child_data = &body.source_scopes[child];
613         assert_eq!(child_data.parent_scope, Some(parent));
614
615         let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
616             (
617                 format!(
618                     " (inlined {}{})",
619                     if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
620                     callee
621                 ),
622                 Some(callsite_span),
623             )
624         } else {
625             (String::new(), None)
626         };
627
628         let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
629
630         if let Some(span) = span {
631             writeln!(
632                 w,
633                 "{0:1$} // at {2}",
634                 indented_header,
635                 ALIGN,
636                 tcx.sess.source_map().span_to_embeddable_string(span),
637             )?;
638         } else {
639             writeln!(w, "{}", indented_header)?;
640         }
641
642         write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
643         writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
644     }
645
646     Ok(())
647 }
648
649 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
650 /// local variables (both user-defined bindings and compiler temporaries).
651 pub fn write_mir_intro<'tcx>(
652     tcx: TyCtxt<'tcx>,
653     body: &Body<'_>,
654     w: &mut dyn Write,
655 ) -> io::Result<()> {
656     write_mir_sig(tcx, body, w)?;
657     writeln!(w, "{{")?;
658
659     // construct a scope tree and write it out
660     let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
661     for (index, scope_data) in body.source_scopes.iter().enumerate() {
662         if let Some(parent) = scope_data.parent_scope {
663             scope_tree.entry(parent).or_default().push(SourceScope::new(index));
664         } else {
665             // Only the argument scope has no parent, because it's the root.
666             assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
667         }
668     }
669
670     write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
671
672     // Add an empty line before the first block is printed.
673     writeln!(w)?;
674
675     Ok(())
676 }
677
678 /// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
679 /// allocations.
680 pub fn write_allocations<'tcx>(
681     tcx: TyCtxt<'tcx>,
682     body: &Body<'_>,
683     w: &mut dyn Write,
684 ) -> io::Result<()> {
685     fn alloc_ids_from_alloc(
686         alloc: ConstAllocation<'_>,
687     ) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
688         alloc.inner().provenance().ptrs().values().map(|id| *id)
689     }
690
691     fn alloc_ids_from_const_val(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
692         match val {
693             ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => {
694                 Either::Left(Either::Left(std::iter::once(ptr.provenance)))
695             }
696             ConstValue::Scalar(interpret::Scalar::Int { .. }) => {
697                 Either::Left(Either::Right(std::iter::empty()))
698             }
699             ConstValue::ZeroSized => Either::Left(Either::Right(std::iter::empty())),
700             ConstValue::ByRef { alloc, .. } | ConstValue::Slice { data: alloc, .. } => {
701                 Either::Right(alloc_ids_from_alloc(alloc))
702             }
703         }
704     }
705     struct CollectAllocIds(BTreeSet<AllocId>);
706
707     impl<'tcx> Visitor<'tcx> for CollectAllocIds {
708         fn visit_constant(&mut self, c: &Constant<'tcx>, _: Location) {
709             match c.literal {
710                 ConstantKind::Ty(_) | ConstantKind::Unevaluated(..) => {}
711                 ConstantKind::Val(val, _) => {
712                     self.0.extend(alloc_ids_from_const_val(val));
713                 }
714             }
715         }
716     }
717
718     let mut visitor = CollectAllocIds(Default::default());
719     visitor.visit_body(body);
720
721     // `seen` contains all seen allocations, including the ones we have *not* printed yet.
722     // The protocol is to first `insert` into `seen`, and only if that returns `true`
723     // then push to `todo`.
724     let mut seen = visitor.0;
725     let mut todo: Vec<_> = seen.iter().copied().collect();
726     while let Some(id) = todo.pop() {
727         let mut write_allocation_track_relocs =
728             |w: &mut dyn Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
729                 // `.rev()` because we are popping them from the back of the `todo` vector.
730                 for id in alloc_ids_from_alloc(alloc).rev() {
731                     if seen.insert(id) {
732                         todo.push(id);
733                     }
734                 }
735                 write!(w, "{}", display_allocation(tcx, alloc.inner()))
736             };
737         write!(w, "\n{id:?}")?;
738         match tcx.try_get_global_alloc(id) {
739             // This can't really happen unless there are bugs, but it doesn't cost us anything to
740             // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
741             None => write!(w, " (deallocated)")?,
742             Some(GlobalAlloc::Function(inst)) => write!(w, " (fn: {inst})")?,
743             Some(GlobalAlloc::VTable(ty, Some(trait_ref))) => {
744                 write!(w, " (vtable: impl {trait_ref} for {ty})")?
745             }
746             Some(GlobalAlloc::VTable(ty, None)) => {
747                 write!(w, " (vtable: impl <auto trait> for {ty})")?
748             }
749             Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
750                 match tcx.eval_static_initializer(did) {
751                     Ok(alloc) => {
752                         write!(w, " (static: {}, ", tcx.def_path_str(did))?;
753                         write_allocation_track_relocs(w, alloc)?;
754                     }
755                     Err(_) => write!(
756                         w,
757                         " (static: {}, error during initializer evaluation)",
758                         tcx.def_path_str(did)
759                     )?,
760                 }
761             }
762             Some(GlobalAlloc::Static(did)) => {
763                 write!(w, " (extern static: {})", tcx.def_path_str(did))?
764             }
765             Some(GlobalAlloc::Memory(alloc)) => {
766                 write!(w, " (")?;
767                 write_allocation_track_relocs(w, alloc)?
768             }
769         }
770         writeln!(w)?;
771     }
772     Ok(())
773 }
774
775 /// Dumps the size and metadata and content of an allocation to the given writer.
776 /// The expectation is that the caller first prints other relevant metadata, so the exact
777 /// format of this function is (*without* leading or trailing newline):
778 ///
779 /// ```text
780 /// size: {}, align: {}) {
781 ///     <bytes>
782 /// }
783 /// ```
784 ///
785 /// The byte format is similar to how hex editors print bytes. Each line starts with the address of
786 /// the start of the line, followed by all bytes in hex format (space separated).
787 /// If the allocation is small enough to fit into a single line, no start address is given.
788 /// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
789 /// characters or characters whose value is larger than 127) with a `.`
790 /// This also prints provenance adequately.
791 pub fn display_allocation<'a, 'tcx, Prov, Extra>(
792     tcx: TyCtxt<'tcx>,
793     alloc: &'a Allocation<Prov, Extra>,
794 ) -> RenderAllocation<'a, 'tcx, Prov, Extra> {
795     RenderAllocation { tcx, alloc }
796 }
797
798 #[doc(hidden)]
799 pub struct RenderAllocation<'a, 'tcx, Prov, Extra> {
800     tcx: TyCtxt<'tcx>,
801     alloc: &'a Allocation<Prov, Extra>,
802 }
803
804 impl<'a, 'tcx, Prov: Provenance, Extra> std::fmt::Display
805     for RenderAllocation<'a, 'tcx, Prov, Extra>
806 {
807     fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
808         let RenderAllocation { tcx, alloc } = *self;
809         write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
810         if alloc.size() == Size::ZERO {
811             // We are done.
812             return write!(w, " {{}}");
813         }
814         // Write allocation bytes.
815         writeln!(w, " {{")?;
816         write_allocation_bytes(tcx, alloc, w, "    ")?;
817         write!(w, "}}")?;
818         Ok(())
819     }
820 }
821
822 fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
823     for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
824         write!(w, "   ")?;
825     }
826     writeln!(w, " │ {}", ascii)
827 }
828
829 /// Number of bytes to print per allocation hex dump line.
830 const BYTES_PER_LINE: usize = 16;
831
832 /// Prints the line start address and returns the new line start address.
833 fn write_allocation_newline(
834     w: &mut dyn std::fmt::Write,
835     mut line_start: Size,
836     ascii: &str,
837     pos_width: usize,
838     prefix: &str,
839 ) -> Result<Size, std::fmt::Error> {
840     write_allocation_endline(w, ascii)?;
841     line_start += Size::from_bytes(BYTES_PER_LINE);
842     write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
843     Ok(line_start)
844 }
845
846 /// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
847 /// is only one line). Note that your prefix should contain a trailing space as the lines are
848 /// printed directly after it.
849 fn write_allocation_bytes<'tcx, Prov: Provenance, Extra>(
850     tcx: TyCtxt<'tcx>,
851     alloc: &Allocation<Prov, Extra>,
852     w: &mut dyn std::fmt::Write,
853     prefix: &str,
854 ) -> std::fmt::Result {
855     let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
856     // Number of chars needed to represent all line numbers.
857     let pos_width = hex_number_length(alloc.size().bytes());
858
859     if num_lines > 0 {
860         write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
861     } else {
862         write!(w, "{}", prefix)?;
863     }
864
865     let mut i = Size::ZERO;
866     let mut line_start = Size::ZERO;
867
868     let ptr_size = tcx.data_layout.pointer_size;
869
870     let mut ascii = String::new();
871
872     let oversized_ptr = |target: &mut String, width| {
873         if target.len() > width {
874             write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
875         }
876     };
877
878     while i < alloc.size() {
879         // The line start already has a space. While we could remove that space from the line start
880         // printing and unconditionally print a space here, that would cause the single-line case
881         // to have a single space before it, which looks weird.
882         if i != line_start {
883             write!(w, " ")?;
884         }
885         if let Some(prov) = alloc.provenance().get_ptr(i) {
886             // Memory with provenance must be defined
887             assert!(alloc.init_mask().is_range_initialized(i, i + ptr_size).is_ok());
888             let j = i.bytes_usize();
889             let offset = alloc
890                 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
891             let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
892             let offset = Size::from_bytes(offset);
893             let provenance_width = |bytes| bytes * 3;
894             let ptr = Pointer::new(prov, offset);
895             let mut target = format!("{:?}", ptr);
896             if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
897                 // This is too long, try to save some space.
898                 target = format!("{:#?}", ptr);
899             }
900             if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
901                 // This branch handles the situation where a provenance starts in the current line
902                 // but ends in the next one.
903                 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
904                 let overflow = ptr_size - remainder;
905                 let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
906                 let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
907                 ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
908                 for _ in 1..remainder.bytes() {
909                     ascii.push('─'); // LIGHT HORIZONTAL
910                 }
911                 if overflow_width > remainder_width && overflow_width >= target.len() {
912                     // The case where the provenance fits into the part in the next line
913                     write!(w, "╾{0:─^1$}", "", remainder_width)?;
914                     line_start =
915                         write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
916                     ascii.clear();
917                     write!(w, "{0:─^1$}╼", target, overflow_width)?;
918                 } else {
919                     oversized_ptr(&mut target, remainder_width);
920                     write!(w, "╾{0:─^1$}", target, remainder_width)?;
921                     line_start =
922                         write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
923                     write!(w, "{0:─^1$}╼", "", overflow_width)?;
924                     ascii.clear();
925                 }
926                 for _ in 0..overflow.bytes() - 1 {
927                     ascii.push('─');
928                 }
929                 ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
930                 i += ptr_size;
931                 continue;
932             } else {
933                 // This branch handles a provenance that starts and ends in the current line.
934                 let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
935                 oversized_ptr(&mut target, provenance_width);
936                 ascii.push('╾');
937                 write!(w, "╾{0:─^1$}╼", target, provenance_width)?;
938                 for _ in 0..ptr_size.bytes() - 2 {
939                     ascii.push('─');
940                 }
941                 ascii.push('╼');
942                 i += ptr_size;
943             }
944         } else if let Some(prov) = alloc.provenance().get(i, &tcx) {
945             // Memory with provenance must be defined
946             assert!(alloc.init_mask().is_range_initialized(i, i + Size::from_bytes(1)).is_ok());
947             ascii.push('━'); // HEAVY HORIZONTAL
948             // We have two characters to display this, which is obviously not enough.
949             // Format is similar to "oversized" above.
950             let j = i.bytes_usize();
951             let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
952             write!(w, "╾{:02x}{:#?} (1 ptr byte)╼", c, prov)?;
953             i += Size::from_bytes(1);
954         } else if alloc.init_mask().is_range_initialized(i, i + Size::from_bytes(1)).is_ok() {
955             let j = i.bytes_usize();
956
957             // Checked definedness (and thus range) and provenance. This access also doesn't
958             // influence interpreter execution but is only for debugging.
959             let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
960             write!(w, "{:02x}", c)?;
961             if c.is_ascii_control() || c >= 0x80 {
962                 ascii.push('.');
963             } else {
964                 ascii.push(char::from(c));
965             }
966             i += Size::from_bytes(1);
967         } else {
968             write!(w, "__")?;
969             ascii.push('░');
970             i += Size::from_bytes(1);
971         }
972         // Print a new line header if the next line still has some bytes to print.
973         if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
974             line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
975             ascii.clear();
976         }
977     }
978     write_allocation_endline(w, &ascii)?;
979
980     Ok(())
981 }
982
983 fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
984     use rustc_hir::def::DefKind;
985
986     trace!("write_mir_sig: {:?}", body.source.instance);
987     let def_id = body.source.def_id();
988     let kind = tcx.def_kind(def_id);
989     let is_function = match kind {
990         DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) => true,
991         _ => tcx.is_closure(def_id),
992     };
993     match (kind, body.source.promoted) {
994         (_, Some(i)) => write!(w, "{:?} in ", i)?,
995         (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
996         (DefKind::Static(hir::Mutability::Not), _) => write!(w, "static ")?,
997         (DefKind::Static(hir::Mutability::Mut), _) => write!(w, "static mut ")?,
998         (_, _) if is_function => write!(w, "fn ")?,
999         (DefKind::AnonConst | DefKind::InlineConst, _) => {} // things like anon const, not an item
1000         _ => bug!("Unexpected def kind {:?}", kind),
1001     }
1002
1003     ty::print::with_forced_impl_filename_line! {
1004         // see notes on #41697 elsewhere
1005         write!(w, "{}", tcx.def_path_str(def_id))?
1006     }
1007
1008     if body.source.promoted.is_none() && is_function {
1009         write!(w, "(")?;
1010
1011         // fn argument types.
1012         for (i, arg) in body.args_iter().enumerate() {
1013             if i != 0 {
1014                 write!(w, ", ")?;
1015             }
1016             write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
1017         }
1018
1019         write!(w, ") -> {}", body.return_ty())?;
1020     } else {
1021         assert_eq!(body.arg_count, 0);
1022         write!(w, ": {} =", body.return_ty())?;
1023     }
1024
1025     if let Some(yield_ty) = body.yield_ty() {
1026         writeln!(w)?;
1027         writeln!(w, "yields {}", yield_ty)?;
1028     }
1029
1030     write!(w, " ")?;
1031     // Next thing that gets printed is the opening {
1032
1033     Ok(())
1034 }
1035
1036 fn write_user_type_annotations(
1037     tcx: TyCtxt<'_>,
1038     body: &Body<'_>,
1039     w: &mut dyn Write,
1040 ) -> io::Result<()> {
1041     if !body.user_type_annotations.is_empty() {
1042         writeln!(w, "| User Type Annotations")?;
1043     }
1044     for (index, annotation) in body.user_type_annotations.iter_enumerated() {
1045         writeln!(
1046             w,
1047             "| {:?}: user_ty: {:?}, span: {}, inferred_ty: {:?}",
1048             index.index(),
1049             annotation.user_ty,
1050             tcx.sess.source_map().span_to_embeddable_string(annotation.span),
1051             annotation.inferred_ty,
1052         )?;
1053     }
1054     if !body.user_type_annotations.is_empty() {
1055         writeln!(w, "|")?;
1056     }
1057     Ok(())
1058 }
1059
1060 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
1061     if let Some(i) = single {
1062         vec![i]
1063     } else {
1064         tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
1065     }
1066 }
1067
1068 /// Calc converted u64 decimal into hex and return it's length in chars
1069 ///
1070 /// ```ignore (cannot-test-private-function)
1071 /// assert_eq!(1, hex_number_length(0));
1072 /// assert_eq!(1, hex_number_length(1));
1073 /// assert_eq!(2, hex_number_length(16));
1074 /// ```
1075 fn hex_number_length(x: u64) -> usize {
1076     if x == 0 {
1077         return 1;
1078     }
1079     let mut length = 0;
1080     let mut x_left = x;
1081     while x_left > 0 {
1082         x_left /= 16;
1083         length += 1;
1084     }
1085     length
1086 }