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