1use std::collections::BTreeSet;
2use std::fmt::{Display, Write as _};
3use std::path::{Path, PathBuf};
4use std::{fs, io};
5
6use rustc_abi::Size;
7use rustc_ast::InlineAsmTemplatePiece;
8use tracing::trace;
9use ty::print::PrettyPrinter;
10
11use super::graphviz::write_mir_fn_graphviz;
12use crate::mir::interpret::{
13 AllocBytes, AllocId, Allocation, ConstAllocation, GlobalAlloc, Pointer, Provenance,
14 alloc_range, read_target_uint,
15};
16use crate::mir::visit::Visitor;
17use crate::mir::*;
18
19const INDENT: &str = " ";
20pub(crate) const ALIGN: usize = 40;
22
23#[derive(Clone, Copy)]
26pub enum PassWhere {
27 BeforeCFG,
29
30 AfterCFG,
32
33 BeforeBlock(BasicBlock),
35
36 BeforeLocation(Location),
38
39 AfterLocation(Location),
41
42 AfterTerminator(BasicBlock),
44}
45
46#[derive(Copy, Clone)]
49pub struct PrettyPrintMirOptions {
50 pub include_extra_comments: bool,
52}
53
54impl PrettyPrintMirOptions {
55 pub fn from_cli(tcx: TyCtxt<'_>) -> Self {
57 Self { include_extra_comments: tcx.sess.opts.unstable_opts.mir_include_spans.is_enabled() }
58 }
59}
60
61pub struct MirDumper<'dis, 'de, 'tcx> {
65 show_pass_num: bool,
66 pass_name: &'static str,
67 disambiguator: &'dis dyn Display,
68 writer: MirWriter<'de, 'tcx>,
69}
70
71impl<'dis, 'de, 'tcx> MirDumper<'dis, 'de, 'tcx> {
72 pub fn new(tcx: TyCtxt<'tcx>, pass_name: &'static str, body: &Body<'tcx>) -> Option<Self> {
79 let dump_enabled = if let Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir {
80 let node_path = ty::print::with_no_trimmed_paths!(
82 ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()))
83 );
84 filters.split('|').any(|or_filter| {
85 or_filter.split('&').all(|and_filter| {
86 let and_filter_trimmed = and_filter.trim();
87 and_filter_trimmed == "all"
88 || pass_name.contains(and_filter_trimmed)
89 || node_path.contains(and_filter_trimmed)
90 })
91 })
92 } else {
93 false
94 };
95
96 dump_enabled.then_some(MirDumper {
97 show_pass_num: false,
98 pass_name,
99 disambiguator: &0,
100 writer: MirWriter::new(tcx),
101 })
102 }
103
104 pub fn tcx(&self) -> TyCtxt<'tcx> {
105 self.writer.tcx
106 }
107
108 #[must_use]
109 pub fn set_show_pass_num(mut self) -> Self {
110 self.show_pass_num = true;
111 self
112 }
113
114 #[must_use]
115 pub fn set_disambiguator(mut self, disambiguator: &'dis dyn Display) -> Self {
116 self.disambiguator = disambiguator;
117 self
118 }
119
120 #[must_use]
121 pub fn set_extra_data(
122 mut self,
123 extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
124 ) -> Self {
125 self.writer.extra_data = extra_data;
126 self
127 }
128
129 #[must_use]
130 pub fn set_options(mut self, options: PrettyPrintMirOptions) -> Self {
131 self.writer.options = options;
132 self
133 }
134
135 pub fn dump_mir(&self, body: &Body<'tcx>) {
160 let _: io::Result<()> = try {
161 let mut file = self.create_dump_file("mir", body)?;
162 self.dump_mir_to_writer(body, &mut file)?;
163 };
164
165 if self.tcx().sess.opts.unstable_opts.dump_mir_graphviz {
166 let _: io::Result<()> = try {
167 let mut file = self.create_dump_file("dot", body)?;
168 write_mir_fn_graphviz(self.tcx(), body, false, &mut file)?;
169 };
170 }
171 }
172
173 pub fn dump_mir_to_writer(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
176 let def_path =
178 ty::print::with_no_trimmed_paths!(ty::print::with_forced_impl_filename_line!(
179 self.tcx().def_path_str(body.source.def_id())
180 ));
181 write!(w, "// MIR for `{def_path}")?;
183 match body.source.promoted {
184 None => write!(w, "`")?,
185 Some(promoted) => write!(w, "::{promoted:?}`")?,
186 }
187 writeln!(w, " {} {}", self.disambiguator, self.pass_name)?;
188 if let Some(ref layout) = body.coroutine_layout_raw() {
189 writeln!(w, "/* coroutine_layout = {layout:#?} */")?;
190 }
191 writeln!(w)?;
192 (self.writer.extra_data)(PassWhere::BeforeCFG, w)?;
193 write_user_type_annotations(self.tcx(), body, w)?;
194 self.writer.write_mir_fn(body, w)?;
195 (self.writer.extra_data)(PassWhere::AfterCFG, w)
196 }
197
198 fn dump_path(&self, extension: &str, body: &Body<'tcx>) -> PathBuf {
202 let tcx = self.tcx();
203 let source = body.source;
204 let promotion_id = match source.promoted {
205 Some(id) => format!("-{id:?}"),
206 None => String::new(),
207 };
208
209 let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
210 String::new()
211 } else if self.show_pass_num {
212 let (dialect_index, phase_index) = body.phase.index();
213 format!(".{}-{}-{:03}", dialect_index, phase_index, body.pass_count)
214 } else {
215 ".-------".to_string()
216 };
217
218 let crate_name = tcx.crate_name(source.def_id().krate);
219 let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
220 let shim_disambiguator = match source.instance {
223 ty::InstanceKind::DropGlue(_, Some(ty)) => {
224 let mut s = ".".to_owned();
227 s.extend(ty.to_string().chars().filter_map(|c| match c {
228 ' ' => None,
229 ':' | '<' | '>' => Some('_'),
230 c => Some(c),
231 }));
232 s
233 }
234 ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
235 let mut s = ".".to_owned();
236 s.extend(ty.to_string().chars().filter_map(|c| match c {
237 ' ' => None,
238 ':' | '<' | '>' => Some('_'),
239 c => Some(c),
240 }));
241 s
242 }
243 ty::InstanceKind::AsyncDropGlue(_, ty) => {
244 let ty::Coroutine(_, args) = ty.kind() else {
245 bug!();
246 };
247 let ty = args.first().unwrap().expect_ty();
248 let mut s = ".".to_owned();
249 s.extend(ty.to_string().chars().filter_map(|c| match c {
250 ' ' => None,
251 ':' | '<' | '>' => Some('_'),
252 c => Some(c),
253 }));
254 s
255 }
256 ty::InstanceKind::FutureDropPollShim(_, proxy_cor, impl_cor) => {
257 let mut s = ".".to_owned();
258 s.extend(proxy_cor.to_string().chars().filter_map(|c| match c {
259 ' ' => None,
260 ':' | '<' | '>' => Some('_'),
261 c => Some(c),
262 }));
263 s.push('.');
264 s.extend(impl_cor.to_string().chars().filter_map(|c| match c {
265 ' ' => None,
266 ':' | '<' | '>' => Some('_'),
267 c => Some(c),
268 }));
269 s
270 }
271 _ => String::new(),
272 };
273
274 let mut file_path = PathBuf::new();
275 file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
276
277 let pass_name = self.pass_name;
278 let disambiguator = self.disambiguator;
279 let file_name = format!(
280 "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}.{extension}",
281 );
282
283 file_path.push(&file_name);
284
285 file_path
286 }
287
288 pub fn create_dump_file(
293 &self,
294 extension: &str,
295 body: &Body<'tcx>,
296 ) -> io::Result<io::BufWriter<fs::File>> {
297 let file_path = self.dump_path(extension, body);
298 if let Some(parent) = file_path.parent() {
299 fs::create_dir_all(parent).map_err(|e| {
300 io::Error::new(
301 e.kind(),
302 format!("IO error creating MIR dump directory: {parent:?}; {e}"),
303 )
304 })?;
305 }
306 fs::File::create_buffered(&file_path).map_err(|e| {
307 io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}"))
308 })
309 }
310}
311
312pub fn write_mir_pretty<'tcx>(
318 tcx: TyCtxt<'tcx>,
319 single: Option<DefId>,
320 w: &mut dyn io::Write,
321) -> io::Result<()> {
322 let writer = MirWriter::new(tcx);
323
324 writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
325 writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
326 writeln!(w, "// HINT: See also -Z dump-mir for MIR at specific points during compilation.")?;
327
328 let mut first = true;
329 for def_id in dump_mir_def_ids(tcx, single) {
330 if first {
331 first = false;
332 } else {
333 writeln!(w)?;
335 }
336
337 let render_body = |w: &mut dyn io::Write, body| -> io::Result<()> {
338 writer.write_mir_fn(body, w)?;
339
340 for body in tcx.promoted_mir(def_id) {
341 writeln!(w)?;
342 writer.write_mir_fn(body, w)?;
343 }
344 Ok(())
345 };
346
347 if tcx.is_const_fn(def_id) {
349 render_body(w, tcx.optimized_mir(def_id))?;
350 writeln!(w)?;
351 writeln!(w, "// MIR FOR CTFE")?;
352 writer.write_mir_fn(tcx.mir_for_ctfe(def_id), w)?;
355 } else {
356 if let Some((val, ty)) = tcx.trivial_const(def_id) {
357 ty::print::with_forced_impl_filename_line! {
358 write!(w, "const {}", tcx.def_path_str(def_id))?
360 }
361 writeln!(w, ": {} = const {};", ty, Const::Val(val, ty))?;
362 } else {
363 let instance_mir = tcx.instance_mir(ty::InstanceKind::Item(def_id));
364 render_body(w, instance_mir)?;
365 }
366 }
367 }
368 Ok(())
369}
370
371pub struct MirWriter<'de, 'tcx> {
373 tcx: TyCtxt<'tcx>,
374 extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
375 options: PrettyPrintMirOptions,
376}
377
378impl<'de, 'tcx> MirWriter<'de, 'tcx> {
379 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
380 MirWriter { tcx, extra_data: &|_, _| Ok(()), options: PrettyPrintMirOptions::from_cli(tcx) }
381 }
382
383 pub fn write_mir_fn(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
385 write_mir_intro(self.tcx, body, w, self.options)?;
386 for block in body.basic_blocks.indices() {
387 (self.extra_data)(PassWhere::BeforeBlock(block), w)?;
388 self.write_basic_block(block, body, w)?;
389 if block.index() + 1 != body.basic_blocks.len() {
390 writeln!(w)?;
391 }
392 }
393
394 writeln!(w, "}}")?;
395
396 write_allocations(self.tcx, body, w)?;
397
398 Ok(())
399 }
400}
401
402fn write_scope_tree(
404 tcx: TyCtxt<'_>,
405 body: &Body<'_>,
406 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
407 w: &mut dyn io::Write,
408 parent: SourceScope,
409 depth: usize,
410 options: PrettyPrintMirOptions,
411) -> io::Result<()> {
412 let indent = depth * INDENT.len();
413
414 for var_debug_info in &body.var_debug_info {
416 if var_debug_info.source_info.scope != parent {
417 continue;
419 }
420
421 let indented_debug_info = format!("{0:1$}debug {2:?};", INDENT, indent, var_debug_info);
422
423 if options.include_extra_comments {
424 writeln!(
425 w,
426 "{0:1$} // in {2}",
427 indented_debug_info,
428 ALIGN,
429 comment(tcx, var_debug_info.source_info),
430 )?;
431 } else {
432 writeln!(w, "{indented_debug_info}")?;
433 }
434 }
435
436 for (local, local_decl) in body.local_decls.iter_enumerated() {
438 if (1..body.arg_count + 1).contains(&local.index()) {
439 continue;
441 }
442
443 if local_decl.source_info.scope != parent {
444 continue;
446 }
447
448 let mut_str = local_decl.mutability.prefix_str();
449
450 let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
451 "{0:1$}let {2}{3:?}: {4}",
452 INDENT, indent, mut_str, local, local_decl.ty
453 ));
454 if let Some(user_ty) = &local_decl.user_ty {
455 for user_ty in user_ty.projections() {
456 write!(indented_decl, " as {user_ty:?}").unwrap();
457 }
458 }
459 indented_decl.push(';');
460
461 let local_name = if local == RETURN_PLACE { " return place" } else { "" };
462
463 if options.include_extra_comments {
464 writeln!(
465 w,
466 "{0:1$} //{2} in {3}",
467 indented_decl,
468 ALIGN,
469 local_name,
470 comment(tcx, local_decl.source_info),
471 )?;
472 } else {
473 writeln!(w, "{indented_decl}",)?;
474 }
475 }
476
477 let Some(children) = scope_tree.get(&parent) else {
478 return Ok(());
479 };
480
481 for &child in children {
482 let child_data = &body.source_scopes[child];
483 assert_eq!(child_data.parent_scope, Some(parent));
484
485 let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
486 (
487 format!(
488 " (inlined {}{})",
489 if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
490 callee
491 ),
492 Some(callsite_span),
493 )
494 } else {
495 (String::new(), None)
496 };
497
498 let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
499
500 if options.include_extra_comments {
501 if let Some(span) = span {
502 writeln!(
503 w,
504 "{0:1$} // at {2}",
505 indented_header,
506 ALIGN,
507 tcx.sess.source_map().span_to_embeddable_string(span),
508 )?;
509 } else {
510 writeln!(w, "{indented_header}")?;
511 }
512 } else {
513 writeln!(w, "{indented_header}")?;
514 }
515
516 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1, options)?;
517 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
518 }
519
520 Ok(())
521}
522
523impl Debug for VarDebugInfo<'_> {
524 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
525 if let Some(box VarDebugInfoFragment { ty, ref projection }) = self.composite {
526 pre_fmt_projection(&projection[..], fmt)?;
527 write!(fmt, "({}: {})", self.name, ty)?;
528 post_fmt_projection(&projection[..], fmt)?;
529 } else {
530 write!(fmt, "{}", self.name)?;
531 }
532
533 write!(fmt, " => {:?}", self.value)
534 }
535}
536
537fn write_mir_intro<'tcx>(
540 tcx: TyCtxt<'tcx>,
541 body: &Body<'_>,
542 w: &mut dyn io::Write,
543 options: PrettyPrintMirOptions,
544) -> io::Result<()> {
545 write_mir_sig(tcx, body, w)?;
546 writeln!(w, "{{")?;
547
548 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
550 for (index, scope_data) in body.source_scopes.iter_enumerated() {
551 if let Some(parent) = scope_data.parent_scope {
552 scope_tree.entry(parent).or_default().push(index);
553 } else {
554 assert_eq!(index, OUTERMOST_SOURCE_SCOPE);
556 }
557 }
558
559 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
560
561 writeln!(w)?;
563
564 if let Some(coverage_info_hi) = &body.coverage_info_hi {
565 write_coverage_info_hi(coverage_info_hi, w)?;
566 }
567 if let Some(function_coverage_info) = &body.function_coverage_info {
568 write_function_coverage_info(function_coverage_info, w)?;
569 }
570
571 Ok(())
572}
573
574fn write_coverage_info_hi(
575 coverage_info_hi: &coverage::CoverageInfoHi,
576 w: &mut dyn io::Write,
577) -> io::Result<()> {
578 let coverage::CoverageInfoHi { num_block_markers: _, branch_spans } = coverage_info_hi;
579
580 let mut did_print = false;
582
583 for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
584 writeln!(
585 w,
586 "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
587 )?;
588 did_print = true;
589 }
590
591 if did_print {
592 writeln!(w)?;
593 }
594
595 Ok(())
596}
597
598fn write_function_coverage_info(
599 function_coverage_info: &coverage::FunctionCoverageInfo,
600 w: &mut dyn io::Write,
601) -> io::Result<()> {
602 let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
603
604 for coverage::Mapping { kind, span } in mappings {
605 writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
606 }
607 writeln!(w)?;
608
609 Ok(())
610}
611
612fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
613 use rustc_hir::def::DefKind;
614
615 trace!("write_mir_sig: {:?}", body.source.instance);
616 let def_id = body.source.def_id();
617 let kind = tcx.def_kind(def_id);
618 let is_function = match kind {
619 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
620 true
621 }
622 _ => tcx.is_closure_like(def_id),
623 };
624 match (kind, body.source.promoted) {
625 (_, Some(_)) => write!(w, "const ")?, (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
627 (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
628 write!(w, "static ")?
629 }
630 (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
631 write!(w, "static mut ")?
632 }
633 (_, _) if is_function => write!(w, "fn ")?,
634 (DefKind::AnonConst | DefKind::InlineConst, _) => {}
636 (DefKind::GlobalAsm, _) => {}
638 _ => bug!("Unexpected def kind {:?}", kind),
639 }
640
641 ty::print::with_forced_impl_filename_line! {
642 write!(w, "{}", tcx.def_path_str(def_id))?
644 }
645 if let Some(p) = body.source.promoted {
646 write!(w, "::{p:?}")?;
647 }
648
649 if body.source.promoted.is_none() && is_function {
650 write!(w, "(")?;
651
652 for (i, arg) in body.args_iter().enumerate() {
654 if i != 0 {
655 write!(w, ", ")?;
656 }
657 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
658 }
659
660 write!(w, ") -> {}", body.return_ty())?;
661 } else {
662 assert_eq!(body.arg_count, 0);
663 write!(w, ": {} =", body.return_ty())?;
664 }
665
666 if let Some(yield_ty) = body.yield_ty() {
667 writeln!(w)?;
668 writeln!(w, "yields {yield_ty}")?;
669 }
670
671 write!(w, " ")?;
672 Ok(())
675}
676
677fn write_user_type_annotations(
678 tcx: TyCtxt<'_>,
679 body: &Body<'_>,
680 w: &mut dyn io::Write,
681) -> io::Result<()> {
682 if !body.user_type_annotations.is_empty() {
683 writeln!(w, "| User Type Annotations")?;
684 }
685 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
686 writeln!(
687 w,
688 "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
689 index.index(),
690 annotation.user_ty,
691 tcx.sess.source_map().span_to_embeddable_string(annotation.span),
692 with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
693 )?;
694 }
695 if !body.user_type_annotations.is_empty() {
696 writeln!(w, "|")?;
697 }
698 Ok(())
699}
700
701pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
702 if let Some(i) = single {
703 vec![i]
704 } else {
705 tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
706 }
707}
708
709impl<'de, 'tcx> MirWriter<'de, 'tcx> {
713 fn write_basic_block(
715 &self,
716 block: BasicBlock,
717 body: &Body<'tcx>,
718 w: &mut dyn io::Write,
719 ) -> io::Result<()> {
720 let data = &body[block];
721
722 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
724 writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
725
726 let mut current_location = Location { block, statement_index: 0 };
728 for statement in &data.statements {
729 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
730
731 for debuginfo in statement.debuginfos.iter() {
732 writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
733 }
734
735 let indented_body = format!("{INDENT}{INDENT}{statement:?};");
736 if self.options.include_extra_comments {
737 writeln!(
738 w,
739 "{:A$} // {}{}",
740 indented_body,
741 if self.tcx.sess.verbose_internals() {
742 format!("{current_location:?}: ")
743 } else {
744 String::new()
745 },
746 comment(self.tcx, statement.source_info),
747 A = ALIGN,
748 )?;
749 } else {
750 writeln!(w, "{indented_body}")?;
751 }
752
753 write_extra(
754 self.tcx,
755 w,
756 &|visitor| visitor.visit_statement(statement, current_location),
757 self.options,
758 )?;
759
760 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
761
762 current_location.statement_index += 1;
763 }
764
765 for debuginfo in data.after_last_stmt_debuginfos.iter() {
766 writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
767 }
768
769 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
771 if data.terminator.is_some() {
772 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
773 if self.options.include_extra_comments {
774 writeln!(
775 w,
776 "{:A$} // {}{}",
777 indented_terminator,
778 if self.tcx.sess.verbose_internals() {
779 format!("{current_location:?}: ")
780 } else {
781 String::new()
782 },
783 comment(self.tcx, data.terminator().source_info),
784 A = ALIGN,
785 )?;
786 } else {
787 writeln!(w, "{indented_terminator}")?;
788 }
789
790 write_extra(
791 self.tcx,
792 w,
793 &|visitor| visitor.visit_terminator(data.terminator(), current_location),
794 self.options,
795 )?;
796 }
797
798 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
799 (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
800
801 writeln!(w, "{INDENT}}}")
802 }
803}
804
805impl Debug for Statement<'_> {
806 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
807 use self::StatementKind::*;
808 match self.kind {
809 Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
810 FakeRead(box (ref cause, ref place)) => {
811 write!(fmt, "FakeRead({cause:?}, {place:?})")
812 }
813 Retag(ref kind, ref place) => write!(
814 fmt,
815 "Retag({}{:?})",
816 match kind {
817 RetagKind::FnEntry => "[fn entry] ",
818 RetagKind::TwoPhase => "[2phase] ",
819 RetagKind::Raw => "[raw] ",
820 RetagKind::Default => "",
821 },
822 place,
823 ),
824 StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
825 StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
826 SetDiscriminant { ref place, variant_index } => {
827 write!(fmt, "discriminant({place:?}) = {variant_index:?}")
828 }
829 PlaceMention(ref place) => {
830 write!(fmt, "PlaceMention({place:?})")
831 }
832 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
833 write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
834 }
835 Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
836 Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
837 ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
838 Nop => write!(fmt, "nop"),
839 BackwardIncompatibleDropHint { ref place, reason: _ } => {
840 write!(fmt, "BackwardIncompatibleDropHint({place:?})")
843 }
844 }
845 }
846}
847
848impl Debug for StmtDebugInfo<'_> {
849 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
850 match self {
851 StmtDebugInfo::AssignRef(local, place) => {
852 write!(fmt, "{local:?} = &{place:?}")
853 }
854 StmtDebugInfo::InvalidAssign(local) => {
855 write!(fmt, "{local:?} = &?")
856 }
857 }
858 }
859}
860
861impl Display for NonDivergingIntrinsic<'_> {
862 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
863 match self {
864 Self::Assume(op) => write!(f, "assume({op:?})"),
865 Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
866 write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
867 }
868 }
869 }
870}
871
872impl<'tcx> Debug for TerminatorKind<'tcx> {
873 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
874 self.fmt_head(fmt)?;
875 let successor_count = self.successors().count();
876 let labels = self.fmt_successor_labels();
877 assert_eq!(successor_count, labels.len());
878
879 let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
881 let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
882 write!(fmt, "unwind ")?;
883 match self.unwind() {
884 None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
886 Some(UnwindAction::Continue) => write!(fmt, "continue"),
887 Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
888 Some(UnwindAction::Terminate(reason)) => {
889 write!(fmt, "terminate({})", reason.as_short_str())
890 }
891 }
892 };
893
894 match (successor_count, show_unwind) {
895 (0, false) => Ok(()),
896 (0, true) => {
897 write!(fmt, " -> ")?;
898 fmt_unwind(fmt)
899 }
900 (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
901 _ => {
902 write!(fmt, " -> [")?;
903 for (i, target) in self.successors().enumerate() {
904 if i > 0 {
905 write!(fmt, ", ")?;
906 }
907 write!(fmt, "{}: {:?}", labels[i], target)?;
908 }
909 if show_unwind {
910 write!(fmt, ", ")?;
911 fmt_unwind(fmt)?;
912 }
913 write!(fmt, "]")
914 }
915 }
916 }
917}
918
919impl<'tcx> TerminatorKind<'tcx> {
920 pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
924 use self::TerminatorKind::*;
925 match self {
926 Goto { .. } => write!(fmt, "goto"),
927 SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
928 Return => write!(fmt, "return"),
929 CoroutineDrop => write!(fmt, "coroutine_drop"),
930 UnwindResume => write!(fmt, "resume"),
931 UnwindTerminate(reason) => {
932 write!(fmt, "terminate({})", reason.as_short_str())
933 }
934 Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
935 Unreachable => write!(fmt, "unreachable"),
936 Drop { place, async_fut: None, .. } => write!(fmt, "drop({place:?})"),
937 Drop { place, async_fut: Some(async_fut), .. } => {
938 write!(fmt, "async drop({place:?}; poll={async_fut:?})")
939 }
940 Call { func, args, destination, .. } => {
941 write!(fmt, "{destination:?} = ")?;
942 write!(fmt, "{func:?}(")?;
943 for (index, arg) in args.iter().enumerate() {
944 if index > 0 {
945 write!(fmt, ", ")?;
946 }
947 write!(fmt, "{:?}", arg.node)?;
948 }
949 write!(fmt, ")")
950 }
951 TailCall { func, args, .. } => {
952 write!(fmt, "tailcall {func:?}(")?;
953 for (index, arg) in args.iter().enumerate() {
954 if index > 0 {
955 write!(fmt, ", ")?;
956 }
957 write!(fmt, "{:?}", arg.node)?;
958 }
959 write!(fmt, ")")
960 }
961 Assert { cond, expected, msg, .. } => {
962 write!(fmt, "assert(")?;
963 if !expected {
964 write!(fmt, "!")?;
965 }
966 write!(fmt, "{cond:?}, ")?;
967 msg.fmt_assert_args(fmt)?;
968 write!(fmt, ")")
969 }
970 FalseEdge { .. } => write!(fmt, "falseEdge"),
971 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
972 InlineAsm { template, operands, options, .. } => {
973 write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
974 for op in operands {
975 write!(fmt, ", ")?;
976 let print_late = |&late| if late { "late" } else { "" };
977 match op {
978 InlineAsmOperand::In { reg, value } => {
979 write!(fmt, "in({reg}) {value:?}")?;
980 }
981 InlineAsmOperand::Out { reg, late, place: Some(place) } => {
982 write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
983 }
984 InlineAsmOperand::Out { reg, late, place: None } => {
985 write!(fmt, "{}out({}) _", print_late(late), reg)?;
986 }
987 InlineAsmOperand::InOut {
988 reg,
989 late,
990 in_value,
991 out_place: Some(out_place),
992 } => {
993 write!(
994 fmt,
995 "in{}out({}) {:?} => {:?}",
996 print_late(late),
997 reg,
998 in_value,
999 out_place
1000 )?;
1001 }
1002 InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
1003 write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
1004 }
1005 InlineAsmOperand::Const { value } => {
1006 write!(fmt, "const {value:?}")?;
1007 }
1008 InlineAsmOperand::SymFn { value } => {
1009 write!(fmt, "sym_fn {value:?}")?;
1010 }
1011 InlineAsmOperand::SymStatic { def_id } => {
1012 write!(fmt, "sym_static {def_id:?}")?;
1013 }
1014 InlineAsmOperand::Label { target_index } => {
1015 write!(fmt, "label {target_index}")?;
1016 }
1017 }
1018 }
1019 write!(fmt, ", options({options:?}))")
1020 }
1021 }
1022 }
1023
1024 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1026 use self::TerminatorKind::*;
1027 match *self {
1028 Return
1029 | TailCall { .. }
1030 | UnwindResume
1031 | UnwindTerminate(_)
1032 | Unreachable
1033 | CoroutineDrop => vec![],
1034 Goto { .. } => vec!["".into()],
1035 SwitchInt { ref targets, .. } => targets
1036 .values
1037 .iter()
1038 .map(|&u| Cow::Owned(u.to_string()))
1039 .chain(iter::once("otherwise".into()))
1040 .collect(),
1041 Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1042 vec!["return".into(), "unwind".into()]
1043 }
1044 Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1045 Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1046 Call { target: None, unwind: _, .. } => vec![],
1047 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1048 Yield { drop: None, .. } => vec!["resume".into()],
1049 Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1050 vec!["return".into(), "unwind".into(), "drop".into()]
1051 }
1052 Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1053 vec!["return".into(), "unwind".into()]
1054 }
1055 Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1056 Drop { unwind: _, .. } => vec!["return".into()],
1057 Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1058 vec!["success".into(), "unwind".into()]
1059 }
1060 Assert { unwind: _, .. } => vec!["success".into()],
1061 FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1062 FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1063 vec!["real".into(), "unwind".into()]
1064 }
1065 FalseUnwind { unwind: _, .. } => vec!["real".into()],
1066 InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1067 let mut vec = Vec::with_capacity(targets.len() + 1);
1068 if !asm_macro.diverges(options) {
1069 vec.push("return".into());
1070 }
1071 vec.resize(targets.len(), "label".into());
1072
1073 if let UnwindAction::Cleanup(_) = unwind {
1074 vec.push("unwind".into());
1075 }
1076
1077 vec
1078 }
1079 }
1080 }
1081}
1082
1083impl<'tcx> Debug for Rvalue<'tcx> {
1084 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1085 use self::Rvalue::*;
1086
1087 match *self {
1088 Use(ref place) => write!(fmt, "{place:?}"),
1089 Repeat(ref a, b) => {
1090 write!(fmt, "[{a:?}; ")?;
1091 pretty_print_const(b, fmt, false)?;
1092 write!(fmt, "]")
1093 }
1094 Cast(ref kind, ref place, ref ty) => {
1095 with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1096 }
1097 BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1098 UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1099 Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1100 NullaryOp(ref op) => match op {
1101 NullOp::RuntimeChecks(RuntimeChecks::UbChecks) => write!(fmt, "UbChecks()"),
1102 NullOp::RuntimeChecks(RuntimeChecks::ContractChecks) => {
1103 write!(fmt, "ContractChecks()")
1104 }
1105 NullOp::RuntimeChecks(RuntimeChecks::OverflowChecks) => {
1106 write!(fmt, "OverflowChecks()")
1107 }
1108 },
1109 ThreadLocalRef(did) => ty::tls::with(|tcx| {
1110 let muta = tcx.static_mutability(did).unwrap().prefix_str();
1111 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1112 }),
1113 Ref(region, borrow_kind, ref place) => {
1114 let kind_str = match borrow_kind {
1115 BorrowKind::Shared => "",
1116 BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1117 BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1118 BorrowKind::Mut { .. } => "mut ",
1119 };
1120
1121 let print_region = ty::tls::with(|tcx| {
1123 tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1124 });
1125 let region = if print_region {
1126 let mut region = region.to_string();
1127 if !region.is_empty() {
1128 region.push(' ');
1129 }
1130 region
1131 } else {
1132 String::new()
1134 };
1135 write!(fmt, "&{region}{kind_str}{place:?}")
1136 }
1137
1138 CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1139
1140 RawPtr(mutability, ref place) => {
1141 write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1142 }
1143
1144 Aggregate(ref kind, ref places) => {
1145 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1146 let mut tuple_fmt = fmt.debug_tuple(name);
1147 for place in places {
1148 tuple_fmt.field(place);
1149 }
1150 tuple_fmt.finish()
1151 };
1152
1153 match **kind {
1154 AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1155
1156 AggregateKind::Tuple => {
1157 if places.is_empty() {
1158 write!(fmt, "()")
1159 } else {
1160 fmt_tuple(fmt, "")
1161 }
1162 }
1163
1164 AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1165 ty::tls::with(|tcx| {
1166 let variant_def = &tcx.adt_def(adt_did).variant(variant);
1167 let args = tcx.lift(args).expect("could not lift for printing");
1168 let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1169 p.print_def_path(variant_def.def_id, args)
1170 })?;
1171
1172 match variant_def.ctor_kind() {
1173 Some(CtorKind::Const) => fmt.write_str(&name),
1174 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1175 None => {
1176 let mut struct_fmt = fmt.debug_struct(&name);
1177 for (field, place) in iter::zip(&variant_def.fields, places) {
1178 struct_fmt.field(field.name.as_str(), place);
1179 }
1180 struct_fmt.finish()
1181 }
1182 }
1183 })
1184 }
1185
1186 AggregateKind::Closure(def_id, args)
1187 | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1188 let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1189 let args = tcx.lift(args).unwrap();
1190 format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1191 } else {
1192 let span = tcx.def_span(def_id);
1193 format!(
1194 "{{closure@{}}}",
1195 tcx.sess.source_map().span_to_diagnostic_string(span)
1196 )
1197 };
1198 let mut struct_fmt = fmt.debug_struct(&name);
1199
1200 if let Some(def_id) = def_id.as_local()
1202 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1203 {
1204 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1205 let var_name = tcx.hir_name(var_id);
1206 struct_fmt.field(var_name.as_str(), place);
1207 }
1208 } else {
1209 for (index, place) in places.iter().enumerate() {
1210 struct_fmt.field(&format!("{index}"), place);
1211 }
1212 }
1213
1214 struct_fmt.finish()
1215 }),
1216
1217 AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1218 let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1219 let mut struct_fmt = fmt.debug_struct(&name);
1220
1221 if let Some(def_id) = def_id.as_local()
1223 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1224 {
1225 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1226 let var_name = tcx.hir_name(var_id);
1227 struct_fmt.field(var_name.as_str(), place);
1228 }
1229 } else {
1230 for (index, place) in places.iter().enumerate() {
1231 struct_fmt.field(&format!("{index}"), place);
1232 }
1233 }
1234
1235 struct_fmt.finish()
1236 }),
1237
1238 AggregateKind::RawPtr(pointee_ty, mutability) => {
1239 let kind_str = match mutability {
1240 Mutability::Mut => "mut",
1241 Mutability::Not => "const",
1242 };
1243 with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1244 fmt_tuple(fmt, "")
1245 }
1246 }
1247 }
1248
1249 ShallowInitBox(ref place, ref ty) => {
1250 with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1251 }
1252
1253 WrapUnsafeBinder(ref op, ty) => {
1254 with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1255 }
1256 }
1257 }
1258}
1259
1260impl<'tcx> Debug for Operand<'tcx> {
1261 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1262 use self::Operand::*;
1263 match *self {
1264 Constant(ref a) => write!(fmt, "{a:?}"),
1265 Copy(ref place) => write!(fmt, "copy {place:?}"),
1266 Move(ref place) => write!(fmt, "move {place:?}"),
1267 }
1268 }
1269}
1270
1271impl<'tcx> Debug for ConstOperand<'tcx> {
1272 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1273 write!(fmt, "{self}")
1274 }
1275}
1276
1277impl<'tcx> Display for ConstOperand<'tcx> {
1278 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1279 match self.ty().kind() {
1280 ty::FnDef(..) => {}
1281 _ => write!(fmt, "const ")?,
1282 }
1283 Display::fmt(&self.const_, fmt)
1284 }
1285}
1286
1287impl Debug for Place<'_> {
1288 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1289 self.as_ref().fmt(fmt)
1290 }
1291}
1292
1293impl Debug for PlaceRef<'_> {
1294 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1295 pre_fmt_projection(self.projection, fmt)?;
1296 write!(fmt, "{:?}", self.local)?;
1297 post_fmt_projection(self.projection, fmt)
1298 }
1299}
1300
1301fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1302 for &elem in projection.iter().rev() {
1303 match elem {
1304 ProjectionElem::OpaqueCast(_)
1305 | ProjectionElem::Downcast(_, _)
1306 | ProjectionElem::Field(_, _) => {
1307 write!(fmt, "(")?;
1308 }
1309 ProjectionElem::Deref => {
1310 write!(fmt, "(*")?;
1311 }
1312 ProjectionElem::Index(_)
1313 | ProjectionElem::ConstantIndex { .. }
1314 | ProjectionElem::Subslice { .. } => {}
1315 ProjectionElem::UnwrapUnsafeBinder(_) => {
1316 write!(fmt, "unwrap_binder!(")?;
1317 }
1318 }
1319 }
1320
1321 Ok(())
1322}
1323
1324fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1325 for &elem in projection.iter() {
1326 match elem {
1327 ProjectionElem::OpaqueCast(ty) => {
1328 write!(fmt, " as {ty})")?;
1329 }
1330 ProjectionElem::Downcast(Some(name), _index) => {
1331 write!(fmt, " as {name})")?;
1332 }
1333 ProjectionElem::Downcast(None, index) => {
1334 write!(fmt, " as variant#{index:?})")?;
1335 }
1336 ProjectionElem::Deref => {
1337 write!(fmt, ")")?;
1338 }
1339 ProjectionElem::Field(field, ty) => {
1340 with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1341 }
1342 ProjectionElem::Index(ref index) => {
1343 write!(fmt, "[{index:?}]")?;
1344 }
1345 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1346 write!(fmt, "[{offset:?} of {min_length:?}]")?;
1347 }
1348 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1349 write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1350 }
1351 ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1352 write!(fmt, "[{from:?}:]")?;
1353 }
1354 ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1355 write!(fmt, "[:-{to:?}]")?;
1356 }
1357 ProjectionElem::Subslice { from, to, from_end: true } => {
1358 write!(fmt, "[{from:?}:-{to:?}]")?;
1359 }
1360 ProjectionElem::Subslice { from, to, from_end: false } => {
1361 write!(fmt, "[{from:?}..{to:?}]")?;
1362 }
1363 ProjectionElem::UnwrapUnsafeBinder(ty) => {
1364 write!(fmt, "; {ty})")?;
1365 }
1366 }
1367 }
1368
1369 Ok(())
1370}
1371
1372fn write_extra<'tcx>(
1376 tcx: TyCtxt<'tcx>,
1377 write: &mut dyn io::Write,
1378 visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1379 options: PrettyPrintMirOptions,
1380) -> io::Result<()> {
1381 if options.include_extra_comments {
1382 let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1383 visit_op(&mut extra_comments);
1384 for comment in extra_comments.comments {
1385 writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1386 }
1387 }
1388 Ok(())
1389}
1390
1391struct ExtraComments<'tcx> {
1392 tcx: TyCtxt<'tcx>,
1393 comments: Vec<String>,
1394}
1395
1396impl<'tcx> ExtraComments<'tcx> {
1397 fn push(&mut self, lines: &str) {
1398 for line in lines.split('\n') {
1399 self.comments.push(line.to_string());
1400 }
1401 }
1402}
1403
1404fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1405 match *ty.kind() {
1406 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1407 ty::Tuple(g_args) if g_args.is_empty() => false,
1409 ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1410 ty::Array(ty, _) => use_verbose(ty, fn_def),
1411 ty::FnDef(..) => fn_def,
1412 _ => true,
1413 }
1414}
1415
1416impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1417 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1418 let ConstOperand { span, user_ty, const_ } = constant;
1419 if use_verbose(const_.ty(), true) {
1420 self.push("mir::ConstOperand");
1421 self.push(&format!(
1422 "+ span: {}",
1423 self.tcx.sess.source_map().span_to_embeddable_string(*span)
1424 ));
1425 if let Some(user_ty) = user_ty {
1426 self.push(&format!("+ user_ty: {user_ty:?}"));
1427 }
1428
1429 let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1430 let tcx = self.tcx;
1431 rustc_data_structures::make_display(move |fmt| {
1432 pretty_print_const_value_tcx(tcx, val, ty, fmt)
1433 })
1434 };
1435
1436 let fmt_valtree = |cv: &ty::Value<'tcx>| {
1437 let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1438 p.pretty_print_const_valtree(*cv, true).unwrap();
1439 p.into_buffer()
1440 };
1441
1442 let val = match const_ {
1443 Const::Ty(_, ct) => match ct.kind() {
1444 ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1445 ty::ConstKind::Unevaluated(uv) => {
1446 format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1447 }
1448 ty::ConstKind::Value(cv) => {
1449 format!("ty::Valtree({})", fmt_valtree(&cv))
1450 }
1451 ty::ConstKind::Error(_) => "Error".to_string(),
1453 ty::ConstKind::Placeholder(_)
1455 | ty::ConstKind::Infer(_)
1456 | ty::ConstKind::Expr(_)
1457 | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1458 },
1459 Const::Unevaluated(uv, _) => {
1460 format!(
1461 "Unevaluated({}, {:?}, {:?})",
1462 self.tcx.def_path_str(uv.def),
1463 uv.args,
1464 uv.promoted,
1465 )
1466 }
1467 Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1468 };
1469
1470 self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1474 }
1475 }
1476
1477 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1478 self.super_rvalue(rvalue, location);
1479 if let Rvalue::Aggregate(kind, _) = rvalue {
1480 match **kind {
1481 AggregateKind::Closure(def_id, args) => {
1482 self.push("closure");
1483 self.push(&format!("+ def_id: {def_id:?}"));
1484 self.push(&format!("+ args: {args:#?}"));
1485 }
1486
1487 AggregateKind::Coroutine(def_id, args) => {
1488 self.push("coroutine");
1489 self.push(&format!("+ def_id: {def_id:?}"));
1490 self.push(&format!("+ args: {args:#?}"));
1491 self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1492 }
1493
1494 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1495 self.push("adt");
1496 self.push(&format!("+ user_ty: {user_ty:?}"));
1497 }
1498
1499 _ => {}
1500 }
1501 }
1502 }
1503}
1504
1505fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1506 let location = tcx.sess.source_map().span_to_embeddable_string(span);
1507 format!("scope {} at {}", scope.index(), location,)
1508}
1509
1510pub fn write_allocations<'tcx>(
1516 tcx: TyCtxt<'tcx>,
1517 body: &Body<'_>,
1518 w: &mut dyn io::Write,
1519) -> io::Result<()> {
1520 fn alloc_ids_from_alloc(
1521 alloc: ConstAllocation<'_>,
1522 ) -> impl DoubleEndedIterator<Item = AllocId> {
1523 alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1524 }
1525
1526 fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1527 match val {
1528 ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1529 ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1530 ConstValue::ZeroSized => None,
1531 ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1532 Some(alloc_id)
1535 }
1536 }
1537 }
1538 struct CollectAllocIds(BTreeSet<AllocId>);
1539
1540 impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1541 fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1542 match c.const_ {
1543 Const::Ty(_, _) | Const::Unevaluated(..) => {}
1544 Const::Val(val, _) => {
1545 if let Some(id) = alloc_id_from_const_val(val) {
1546 self.0.insert(id);
1547 }
1548 }
1549 }
1550 }
1551 }
1552
1553 let mut visitor = CollectAllocIds(Default::default());
1554 visitor.visit_body(body);
1555
1556 let mut seen = visitor.0;
1560 let mut todo: Vec<_> = seen.iter().copied().collect();
1561 while let Some(id) = todo.pop() {
1562 let mut write_allocation_track_relocs =
1563 |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1564 for id in alloc_ids_from_alloc(alloc).rev() {
1566 if seen.insert(id) {
1567 todo.push(id);
1568 }
1569 }
1570 write!(w, "{}", display_allocation(tcx, alloc.inner()))
1571 };
1572 write!(w, "\n{id:?}")?;
1573 match tcx.try_get_global_alloc(id) {
1574 None => write!(w, " (deallocated)")?,
1577 Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1578 Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1579 write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1580 }
1581 Some(GlobalAlloc::TypeId { ty }) => write!(w, " (typeid for {ty})")?,
1582 Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1583 write!(w, " (static: {}", tcx.def_path_str(did))?;
1584 if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1585 && body
1586 .source
1587 .def_id()
1588 .as_local()
1589 .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1590 {
1591 write!(w, ")")?;
1595 } else {
1596 match tcx.eval_static_initializer(did) {
1597 Ok(alloc) => {
1598 write!(w, ", ")?;
1599 write_allocation_track_relocs(w, alloc)?;
1600 }
1601 Err(_) => write!(w, ", error during initializer evaluation)")?,
1602 }
1603 }
1604 }
1605 Some(GlobalAlloc::Static(did)) => {
1606 write!(w, " (extern static: {})", tcx.def_path_str(did))?
1607 }
1608 Some(GlobalAlloc::Memory(alloc)) => {
1609 write!(w, " (")?;
1610 write_allocation_track_relocs(w, alloc)?
1611 }
1612 }
1613 writeln!(w)?;
1614 }
1615 Ok(())
1616}
1617
1618pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1635 tcx: TyCtxt<'tcx>,
1636 alloc: &'a Allocation<Prov, Extra, Bytes>,
1637) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1638 RenderAllocation { tcx, alloc }
1639}
1640
1641#[doc(hidden)]
1642pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1643 tcx: TyCtxt<'tcx>,
1644 alloc: &'a Allocation<Prov, Extra, Bytes>,
1645}
1646
1647impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1648 for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1649{
1650 fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1651 let RenderAllocation { tcx, alloc } = *self;
1652 write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1653 if alloc.size() == Size::ZERO {
1654 return write!(w, " {{}}");
1656 }
1657 if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1658 return write!(w, " {{ .. }}");
1659 }
1660 writeln!(w, " {{")?;
1662 write_allocation_bytes(tcx, alloc, w, " ")?;
1663 write!(w, "}}")?;
1664 Ok(())
1665 }
1666}
1667
1668fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1669 for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1670 write!(w, " ")?;
1671 }
1672 writeln!(w, " │ {ascii}")
1673}
1674
1675const BYTES_PER_LINE: usize = 16;
1677
1678fn write_allocation_newline(
1680 w: &mut dyn std::fmt::Write,
1681 mut line_start: Size,
1682 ascii: &str,
1683 pos_width: usize,
1684 prefix: &str,
1685) -> Result<Size, std::fmt::Error> {
1686 write_allocation_endline(w, ascii)?;
1687 line_start += Size::from_bytes(BYTES_PER_LINE);
1688 write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1689 Ok(line_start)
1690}
1691
1692pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1696 tcx: TyCtxt<'tcx>,
1697 alloc: &Allocation<Prov, Extra, Bytes>,
1698 w: &mut dyn std::fmt::Write,
1699 prefix: &str,
1700) -> std::fmt::Result {
1701 let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1702 let pos_width = hex_number_length(alloc.size().bytes());
1704
1705 if num_lines > 0 {
1706 write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1707 } else {
1708 write!(w, "{prefix}")?;
1709 }
1710
1711 let mut i = Size::ZERO;
1712 let mut line_start = Size::ZERO;
1713
1714 let ptr_size = tcx.data_layout.pointer_size();
1715
1716 let mut ascii = String::new();
1717
1718 let oversized_ptr = |target: &mut String, width| {
1719 if target.len() > width {
1720 write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1721 }
1722 };
1723
1724 while i < alloc.size() {
1725 if i != line_start {
1729 write!(w, " ")?;
1730 }
1731 if let Some(prov) = alloc.provenance().get_ptr(i) {
1732 assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1734 let j = i.bytes_usize();
1735 let offset = alloc
1736 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1737 let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1738 let offset = Size::from_bytes(offset);
1739 let provenance_width = |bytes| bytes * 3;
1740 let ptr = Pointer::new(prov, offset);
1741 let mut target = format!("{ptr:?}");
1742 if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1743 target = format!("{ptr:#?}");
1745 }
1746 if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1747 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1750 let overflow = ptr_size - remainder;
1751 let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1752 let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1753 ascii.push('╾'); for _ in 1..remainder.bytes() {
1755 ascii.push('─'); }
1757 if overflow_width > remainder_width && overflow_width >= target.len() {
1758 write!(w, "╾{0:─^1$}", "", remainder_width)?;
1760 line_start =
1761 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1762 ascii.clear();
1763 write!(w, "{target:─^overflow_width$}╼")?;
1764 } else {
1765 oversized_ptr(&mut target, remainder_width);
1766 write!(w, "╾{target:─^remainder_width$}")?;
1767 line_start =
1768 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1769 write!(w, "{0:─^1$}╼", "", overflow_width)?;
1770 ascii.clear();
1771 }
1772 for _ in 0..overflow.bytes() - 1 {
1773 ascii.push('─');
1774 }
1775 ascii.push('╼'); i += ptr_size;
1777 continue;
1778 } else {
1779 let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1781 oversized_ptr(&mut target, provenance_width);
1782 ascii.push('╾');
1783 write!(w, "╾{target:─^provenance_width$}╼")?;
1784 for _ in 0..ptr_size.bytes() - 2 {
1785 ascii.push('─');
1786 }
1787 ascii.push('╼');
1788 i += ptr_size;
1789 }
1790 } else if let Some(frag) = alloc.provenance().get_byte(i, &tcx) {
1791 assert!(
1793 alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1794 );
1795 ascii.push('━'); let j = i.bytes_usize();
1799 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1800 write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼", prov = frag.prov, idx = frag.idx)?;
1802 i += Size::from_bytes(1);
1803 } else if alloc
1804 .init_mask()
1805 .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1806 .is_ok()
1807 {
1808 let j = i.bytes_usize();
1809
1810 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1813 write!(w, "{c:02x}")?;
1814 if c.is_ascii_control() || c >= 0x80 {
1815 ascii.push('.');
1816 } else {
1817 ascii.push(char::from(c));
1818 }
1819 i += Size::from_bytes(1);
1820 } else {
1821 write!(w, "__")?;
1822 ascii.push('░');
1823 i += Size::from_bytes(1);
1824 }
1825 if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1827 line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1828 ascii.clear();
1829 }
1830 }
1831 write_allocation_endline(w, &ascii)?;
1832
1833 Ok(())
1834}
1835
1836fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1840 write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1841}
1842
1843fn comma_sep<'tcx>(
1844 tcx: TyCtxt<'tcx>,
1845 fmt: &mut Formatter<'_>,
1846 elems: Vec<(ConstValue, Ty<'tcx>)>,
1847) -> fmt::Result {
1848 let mut first = true;
1849 for (ct, ty) in elems {
1850 if !first {
1851 fmt.write_str(", ")?;
1852 }
1853 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1854 first = false;
1855 }
1856 Ok(())
1857}
1858
1859fn pretty_print_const_value_tcx<'tcx>(
1860 tcx: TyCtxt<'tcx>,
1861 ct: ConstValue,
1862 ty: Ty<'tcx>,
1863 fmt: &mut Formatter<'_>,
1864) -> fmt::Result {
1865 use crate::ty::print::PrettyPrinter;
1866
1867 if tcx.sess.verbose_internals() {
1868 fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1869 return Ok(());
1870 }
1871
1872 if ct.all_bytes_uninit(tcx) {
1875 fmt.write_str("<uninit>")?;
1876 return Ok(());
1877 }
1878
1879 let u8_type = tcx.types.u8;
1880 match (ct, ty.kind()) {
1881 (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1883 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1884 fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1885 return Ok(());
1886 }
1887 }
1888 (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1889 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1890 pretty_print_byte_str(fmt, data)?;
1891 return Ok(());
1892 }
1893 }
1894 (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1895 let n = n.try_to_target_usize(tcx).unwrap();
1896 let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1897 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1899 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1900 fmt.write_str("*")?;
1901 pretty_print_byte_str(fmt, byte_str)?;
1902 return Ok(());
1903 }
1904 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1912 let ct = tcx.lift(ct).unwrap();
1913 let ty = tcx.lift(ty).unwrap();
1914 if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1915 let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1916 match *ty.kind() {
1917 ty::Array(..) => {
1918 fmt.write_str("[")?;
1919 comma_sep(tcx, fmt, fields)?;
1920 fmt.write_str("]")?;
1921 }
1922 ty::Tuple(..) => {
1923 fmt.write_str("(")?;
1924 comma_sep(tcx, fmt, fields)?;
1925 if contents.fields.len() == 1 {
1926 fmt.write_str(",")?;
1927 }
1928 fmt.write_str(")")?;
1929 }
1930 ty::Adt(def, _) if def.variants().is_empty() => {
1931 fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1932 }
1933 ty::Adt(def, args) => {
1934 let variant_idx = contents
1935 .variant
1936 .expect("destructed mir constant of adt without variant idx");
1937 let variant_def = &def.variant(variant_idx);
1938 let args = tcx.lift(args).unwrap();
1939 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1940 p.print_alloc_ids = true;
1941 p.pretty_print_value_path(variant_def.def_id, args)?;
1942 fmt.write_str(&p.into_buffer())?;
1943
1944 match variant_def.ctor_kind() {
1945 Some(CtorKind::Const) => {}
1946 Some(CtorKind::Fn) => {
1947 fmt.write_str("(")?;
1948 comma_sep(tcx, fmt, fields)?;
1949 fmt.write_str(")")?;
1950 }
1951 None => {
1952 fmt.write_str(" {{ ")?;
1953 let mut first = true;
1954 for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1955 {
1956 if !first {
1957 fmt.write_str(", ")?;
1958 }
1959 write!(fmt, "{}: ", field_def.name)?;
1960 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1961 first = false;
1962 }
1963 fmt.write_str(" }}")?;
1964 }
1965 }
1966 }
1967 _ => unreachable!(),
1968 }
1969 return Ok(());
1970 }
1971 }
1972 (ConstValue::Scalar(scalar), _) => {
1973 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1974 p.print_alloc_ids = true;
1975 let ty = tcx.lift(ty).unwrap();
1976 p.pretty_print_const_scalar(scalar, ty)?;
1977 fmt.write_str(&p.into_buffer())?;
1978 return Ok(());
1979 }
1980 (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
1981 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1982 p.print_alloc_ids = true;
1983 p.pretty_print_value_path(*d, s)?;
1984 fmt.write_str(&p.into_buffer())?;
1985 return Ok(());
1986 }
1987 _ => {}
1990 }
1991 write!(fmt, "{ct:?}: {ty}")
1993}
1994
1995pub(crate) fn pretty_print_const_value<'tcx>(
1996 ct: ConstValue,
1997 ty: Ty<'tcx>,
1998 fmt: &mut Formatter<'_>,
1999) -> fmt::Result {
2000 ty::tls::with(|tcx| {
2001 let ct = tcx.lift(ct).unwrap();
2002 let ty = tcx.lift(ty).unwrap();
2003 pretty_print_const_value_tcx(tcx, ct, ty, fmt)
2004 })
2005}
2006
2007fn hex_number_length(x: u64) -> usize {
2018 if x == 0 {
2019 return 1;
2020 }
2021 let mut length = 0;
2022 let mut x_left = x;
2023 while x_left > 0 {
2024 x_left /= 16;
2025 length += 1;
2026 }
2027 length
2028}