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