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