rustc_middle/mir/
pretty.rs

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 = "    ";
20/// Alignment for lining up comments following MIR statements
21pub(crate) const ALIGN: usize = 40;
22
23/// An indication of where we are in the control flow graph. Used for printing
24/// extra information in `dump_mir`
25#[derive(Clone, Copy)]
26pub enum PassWhere {
27    /// We have not started dumping the control flow graph, but we are about to.
28    BeforeCFG,
29
30    /// We just finished dumping the control flow graph. This is right before EOF
31    AfterCFG,
32
33    /// We are about to start dumping the given basic block.
34    BeforeBlock(BasicBlock),
35
36    /// We are just about to dump the given statement or terminator.
37    BeforeLocation(Location),
38
39    /// We just dumped the given statement or terminator.
40    AfterLocation(Location),
41
42    /// We just dumped the terminator for a block but not the closing `}`.
43    AfterTerminator(BasicBlock),
44}
45
46/// Cosmetic options for pretty-printing the MIR contents, gathered from the CLI. Each pass can
47/// override these when dumping its own specific MIR information with `dump_mir`.
48#[derive(Copy, Clone)]
49pub struct PrettyPrintMirOptions {
50    /// Whether to include extra comments, like span info. From `-Z mir-include-spans`.
51    pub include_extra_comments: bool,
52}
53
54impl PrettyPrintMirOptions {
55    /// Create the default set of MIR pretty-printing options from the CLI flags.
56    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/// Manages MIR dumping, which is MIR writing done to a file with a specific name. In particular,
62/// it makes it impossible to dump MIR to one of these files when it hasn't been requested from the
63/// command line. Layered on top of `MirWriter`, which does the actual writing.
64pub 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    // If dumping should be performed (e.g. because it was requested on the
73    // CLI), returns a `MirDumper` with default values for the following fields:
74    // - `show_pass_num`: `false`
75    // - `disambiguator`: `&0`
76    // - `writer.extra_data`: a no-op
77    // - `writer.options`: default options derived from CLI flags
78    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            // see notes on #41697 below
81            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    /// If the session is properly configured, dumps a human-readable representation of the MIR
136    /// (with default pretty-printing options) into:
137    ///
138    /// ```text
139    /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
140    /// ```
141    ///
142    /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
143    /// where `<filter>` takes the following forms:
144    ///
145    /// - `all` -- dump MIR for all fns, all passes, all everything
146    /// - a filter defined by a set of substrings combined with `&` and `|`
147    ///   (`&` has higher precedence). At least one of the `|`-separated groups
148    ///   must match; an `|`-separated group matches if all of its `&`-separated
149    ///   substrings are matched.
150    ///
151    /// Example:
152    ///
153    /// - `nll` == match if `nll` appears in the name
154    /// - `foo & nll` == match if `foo` and `nll` both appear in the name
155    /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
156    ///   or `typeck` appears in the name.
157    /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
158    ///   or `typeck` and `bar` both appear in the name.
159    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    // #41697 -- we use `with_forced_impl_filename_line()` because `def_path_str()` would otherwise
174    // trigger `type_of`, and this can run while we are already attempting to evaluate `type_of`.
175    pub fn dump_mir_to_writer(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
176        // see notes on #41697 above
177        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        // ignore-tidy-odd-backticks the literal below is fine
182        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    /// Returns the path to the filename where we should dump a given MIR.
199    /// Also used by other bits of code (e.g., NLL inference) that dump
200    /// graphviz data or other things.
201    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        // All drop shims have the same DefId, so we have to add the type
221        // to get unique file names.
222        let shim_disambiguator = match source.instance {
223            ty::InstanceKind::DropGlue(_, Some(ty)) => {
224                // Unfortunately, pretty-printed types are not very filename-friendly.
225                // We do some filtering.
226                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    /// Attempts to open a file where we should dump a given MIR or other
289    /// bit of MIR-related data. Used by `mir-dump`, but also by other
290    /// bits of code (e.g., NLL inference) that dump graphviz data or
291    /// other things, and hence takes the extension as an argument.
292    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
312///////////////////////////////////////////////////////////////////////////
313// Whole MIR bodies
314
315/// Write out a human-readable textual representation for the given MIR, with the default
316/// [PrettyPrintMirOptions].
317pub 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            // Put empty lines between all items
334            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        // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
348        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            // Do not use `render_body`, as that would render the promoteds again, but these
353            // are shared between mir_for_ctfe and optimized_mir
354            writer.write_mir_fn(tcx.mir_for_ctfe(def_id), w)?;
355        } else {
356            let instance_mir = tcx.instance_mir(ty::InstanceKind::Item(def_id));
357            render_body(w, instance_mir)?;
358        }
359    }
360    Ok(())
361}
362
363/// Does the writing of MIR to output, e.g. a file.
364pub struct MirWriter<'de, 'tcx> {
365    tcx: TyCtxt<'tcx>,
366    extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
367    options: PrettyPrintMirOptions,
368}
369
370impl<'de, 'tcx> MirWriter<'de, 'tcx> {
371    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
372        MirWriter { tcx, extra_data: &|_, _| Ok(()), options: PrettyPrintMirOptions::from_cli(tcx) }
373    }
374
375    /// Write out a human-readable textual representation for the given function.
376    pub fn write_mir_fn(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
377        write_mir_intro(self.tcx, body, w, self.options)?;
378        for block in body.basic_blocks.indices() {
379            (self.extra_data)(PassWhere::BeforeBlock(block), w)?;
380            self.write_basic_block(block, body, w)?;
381            if block.index() + 1 != body.basic_blocks.len() {
382                writeln!(w)?;
383            }
384        }
385
386        writeln!(w, "}}")?;
387
388        write_allocations(self.tcx, body, w)?;
389
390        Ok(())
391    }
392}
393
394/// Prints local variables in a scope tree.
395fn write_scope_tree(
396    tcx: TyCtxt<'_>,
397    body: &Body<'_>,
398    scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
399    w: &mut dyn io::Write,
400    parent: SourceScope,
401    depth: usize,
402    options: PrettyPrintMirOptions,
403) -> io::Result<()> {
404    let indent = depth * INDENT.len();
405
406    // Local variable debuginfo.
407    for var_debug_info in &body.var_debug_info {
408        if var_debug_info.source_info.scope != parent {
409            // Not declared in this scope.
410            continue;
411        }
412
413        let indented_debug_info = format!("{0:1$}debug {2:?};", INDENT, indent, var_debug_info);
414
415        if options.include_extra_comments {
416            writeln!(
417                w,
418                "{0:1$} // in {2}",
419                indented_debug_info,
420                ALIGN,
421                comment(tcx, var_debug_info.source_info),
422            )?;
423        } else {
424            writeln!(w, "{indented_debug_info}")?;
425        }
426    }
427
428    // Local variable types.
429    for (local, local_decl) in body.local_decls.iter_enumerated() {
430        if (1..body.arg_count + 1).contains(&local.index()) {
431            // Skip over argument locals, they're printed in the signature.
432            continue;
433        }
434
435        if local_decl.source_info.scope != parent {
436            // Not declared in this scope.
437            continue;
438        }
439
440        let mut_str = local_decl.mutability.prefix_str();
441
442        let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
443            "{0:1$}let {2}{3:?}: {4}",
444            INDENT, indent, mut_str, local, local_decl.ty
445        ));
446        if let Some(user_ty) = &local_decl.user_ty {
447            for user_ty in user_ty.projections() {
448                write!(indented_decl, " as {user_ty:?}").unwrap();
449            }
450        }
451        indented_decl.push(';');
452
453        let local_name = if local == RETURN_PLACE { " return place" } else { "" };
454
455        if options.include_extra_comments {
456            writeln!(
457                w,
458                "{0:1$} //{2} in {3}",
459                indented_decl,
460                ALIGN,
461                local_name,
462                comment(tcx, local_decl.source_info),
463            )?;
464        } else {
465            writeln!(w, "{indented_decl}",)?;
466        }
467    }
468
469    let Some(children) = scope_tree.get(&parent) else {
470        return Ok(());
471    };
472
473    for &child in children {
474        let child_data = &body.source_scopes[child];
475        assert_eq!(child_data.parent_scope, Some(parent));
476
477        let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
478            (
479                format!(
480                    " (inlined {}{})",
481                    if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
482                    callee
483                ),
484                Some(callsite_span),
485            )
486        } else {
487            (String::new(), None)
488        };
489
490        let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
491
492        if options.include_extra_comments {
493            if let Some(span) = span {
494                writeln!(
495                    w,
496                    "{0:1$} // at {2}",
497                    indented_header,
498                    ALIGN,
499                    tcx.sess.source_map().span_to_embeddable_string(span),
500                )?;
501            } else {
502                writeln!(w, "{indented_header}")?;
503            }
504        } else {
505            writeln!(w, "{indented_header}")?;
506        }
507
508        write_scope_tree(tcx, body, scope_tree, w, child, depth + 1, options)?;
509        writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
510    }
511
512    Ok(())
513}
514
515impl Debug for VarDebugInfo<'_> {
516    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
517        if let Some(box VarDebugInfoFragment { ty, ref projection }) = self.composite {
518            pre_fmt_projection(&projection[..], fmt)?;
519            write!(fmt, "({}: {})", self.name, ty)?;
520            post_fmt_projection(&projection[..], fmt)?;
521        } else {
522            write!(fmt, "{}", self.name)?;
523        }
524
525        write!(fmt, " => {:?}", self.value)
526    }
527}
528
529/// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
530/// local variables (both user-defined bindings and compiler temporaries).
531fn write_mir_intro<'tcx>(
532    tcx: TyCtxt<'tcx>,
533    body: &Body<'_>,
534    w: &mut dyn io::Write,
535    options: PrettyPrintMirOptions,
536) -> io::Result<()> {
537    write_mir_sig(tcx, body, w)?;
538    writeln!(w, "{{")?;
539
540    // construct a scope tree and write it out
541    let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
542    for (index, scope_data) in body.source_scopes.iter_enumerated() {
543        if let Some(parent) = scope_data.parent_scope {
544            scope_tree.entry(parent).or_default().push(index);
545        } else {
546            // Only the argument scope has no parent, because it's the root.
547            assert_eq!(index, OUTERMOST_SOURCE_SCOPE);
548        }
549    }
550
551    write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
552
553    // Add an empty line before the first block is printed.
554    writeln!(w)?;
555
556    if let Some(coverage_info_hi) = &body.coverage_info_hi {
557        write_coverage_info_hi(coverage_info_hi, w)?;
558    }
559    if let Some(function_coverage_info) = &body.function_coverage_info {
560        write_function_coverage_info(function_coverage_info, w)?;
561    }
562
563    Ok(())
564}
565
566fn write_coverage_info_hi(
567    coverage_info_hi: &coverage::CoverageInfoHi,
568    w: &mut dyn io::Write,
569) -> io::Result<()> {
570    let coverage::CoverageInfoHi { num_block_markers: _, branch_spans } = coverage_info_hi;
571
572    // Only add an extra trailing newline if we printed at least one thing.
573    let mut did_print = false;
574
575    for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
576        writeln!(
577            w,
578            "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
579        )?;
580        did_print = true;
581    }
582
583    if did_print {
584        writeln!(w)?;
585    }
586
587    Ok(())
588}
589
590fn write_function_coverage_info(
591    function_coverage_info: &coverage::FunctionCoverageInfo,
592    w: &mut dyn io::Write,
593) -> io::Result<()> {
594    let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
595
596    for coverage::Mapping { kind, span } in mappings {
597        writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
598    }
599    writeln!(w)?;
600
601    Ok(())
602}
603
604fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
605    use rustc_hir::def::DefKind;
606
607    trace!("write_mir_sig: {:?}", body.source.instance);
608    let def_id = body.source.def_id();
609    let kind = tcx.def_kind(def_id);
610    let is_function = match kind {
611        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
612            true
613        }
614        _ => tcx.is_closure_like(def_id),
615    };
616    match (kind, body.source.promoted) {
617        (_, Some(_)) => write!(w, "const ")?, // promoteds are the closest to consts
618        (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
619        (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
620            write!(w, "static ")?
621        }
622        (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
623            write!(w, "static mut ")?
624        }
625        (_, _) if is_function => write!(w, "fn ")?,
626        // things like anon const, not an item
627        (DefKind::AnonConst | DefKind::InlineConst, _) => {}
628        // `global_asm!` have fake bodies, which we may dump after mir-build
629        (DefKind::GlobalAsm, _) => {}
630        _ => bug!("Unexpected def kind {:?}", kind),
631    }
632
633    ty::print::with_forced_impl_filename_line! {
634        // see notes on #41697 elsewhere
635        write!(w, "{}", tcx.def_path_str(def_id))?
636    }
637    if let Some(p) = body.source.promoted {
638        write!(w, "::{p:?}")?;
639    }
640
641    if body.source.promoted.is_none() && is_function {
642        write!(w, "(")?;
643
644        // fn argument types.
645        for (i, arg) in body.args_iter().enumerate() {
646            if i != 0 {
647                write!(w, ", ")?;
648            }
649            write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
650        }
651
652        write!(w, ") -> {}", body.return_ty())?;
653    } else {
654        assert_eq!(body.arg_count, 0);
655        write!(w, ": {} =", body.return_ty())?;
656    }
657
658    if let Some(yield_ty) = body.yield_ty() {
659        writeln!(w)?;
660        writeln!(w, "yields {yield_ty}")?;
661    }
662
663    write!(w, " ")?;
664    // Next thing that gets printed is the opening {
665
666    Ok(())
667}
668
669fn write_user_type_annotations(
670    tcx: TyCtxt<'_>,
671    body: &Body<'_>,
672    w: &mut dyn io::Write,
673) -> io::Result<()> {
674    if !body.user_type_annotations.is_empty() {
675        writeln!(w, "| User Type Annotations")?;
676    }
677    for (index, annotation) in body.user_type_annotations.iter_enumerated() {
678        writeln!(
679            w,
680            "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
681            index.index(),
682            annotation.user_ty,
683            tcx.sess.source_map().span_to_embeddable_string(annotation.span),
684            with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
685        )?;
686    }
687    if !body.user_type_annotations.is_empty() {
688        writeln!(w, "|")?;
689    }
690    Ok(())
691}
692
693pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
694    if let Some(i) = single {
695        vec![i]
696    } else {
697        tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
698    }
699}
700
701///////////////////////////////////////////////////////////////////////////
702// Basic blocks and their parts (statements, terminators, ...)
703
704impl<'de, 'tcx> MirWriter<'de, 'tcx> {
705    /// Write out a human-readable textual representation for the given basic block.
706    fn write_basic_block(
707        &self,
708        block: BasicBlock,
709        body: &Body<'tcx>,
710        w: &mut dyn io::Write,
711    ) -> io::Result<()> {
712        let data = &body[block];
713
714        // Basic block label at the top.
715        let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
716        writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
717
718        // List of statements in the middle.
719        let mut current_location = Location { block, statement_index: 0 };
720        for statement in &data.statements {
721            (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
722
723            for debuginfo in statement.debuginfos.iter() {
724                writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
725            }
726
727            let indented_body = format!("{INDENT}{INDENT}{statement:?};");
728            if self.options.include_extra_comments {
729                writeln!(
730                    w,
731                    "{:A$} // {}{}",
732                    indented_body,
733                    if self.tcx.sess.verbose_internals() {
734                        format!("{current_location:?}: ")
735                    } else {
736                        String::new()
737                    },
738                    comment(self.tcx, statement.source_info),
739                    A = ALIGN,
740                )?;
741            } else {
742                writeln!(w, "{indented_body}")?;
743            }
744
745            write_extra(
746                self.tcx,
747                w,
748                &|visitor| visitor.visit_statement(statement, current_location),
749                self.options,
750            )?;
751
752            (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
753
754            current_location.statement_index += 1;
755        }
756
757        for debuginfo in data.after_last_stmt_debuginfos.iter() {
758            writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
759        }
760
761        // Terminator at the bottom.
762        (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
763        if data.terminator.is_some() {
764            let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
765            if self.options.include_extra_comments {
766                writeln!(
767                    w,
768                    "{:A$} // {}{}",
769                    indented_terminator,
770                    if self.tcx.sess.verbose_internals() {
771                        format!("{current_location:?}: ")
772                    } else {
773                        String::new()
774                    },
775                    comment(self.tcx, data.terminator().source_info),
776                    A = ALIGN,
777                )?;
778            } else {
779                writeln!(w, "{indented_terminator}")?;
780            }
781
782            write_extra(
783                self.tcx,
784                w,
785                &|visitor| visitor.visit_terminator(data.terminator(), current_location),
786                self.options,
787            )?;
788        }
789
790        (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
791        (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
792
793        writeln!(w, "{INDENT}}}")
794    }
795}
796
797impl Debug for Statement<'_> {
798    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
799        use self::StatementKind::*;
800        match self.kind {
801            Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
802            FakeRead(box (ref cause, ref place)) => {
803                write!(fmt, "FakeRead({cause:?}, {place:?})")
804            }
805            Retag(ref kind, ref place) => write!(
806                fmt,
807                "Retag({}{:?})",
808                match kind {
809                    RetagKind::FnEntry => "[fn entry] ",
810                    RetagKind::TwoPhase => "[2phase] ",
811                    RetagKind::Raw => "[raw] ",
812                    RetagKind::Default => "",
813                },
814                place,
815            ),
816            StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
817            StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
818            SetDiscriminant { ref place, variant_index } => {
819                write!(fmt, "discriminant({place:?}) = {variant_index:?}")
820            }
821            Deinit(ref place) => write!(fmt, "Deinit({place:?})"),
822            PlaceMention(ref place) => {
823                write!(fmt, "PlaceMention({place:?})")
824            }
825            AscribeUserType(box (ref place, ref c_ty), ref variance) => {
826                write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
827            }
828            Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
829            Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
830            ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
831            Nop => write!(fmt, "nop"),
832            BackwardIncompatibleDropHint { ref place, reason: _ } => {
833                // For now, we don't record the reason because there is only one use case,
834                // which is to report breaking change in drop order by Edition 2024
835                write!(fmt, "BackwardIncompatibleDropHint({place:?})")
836            }
837        }
838    }
839}
840
841impl Debug for StmtDebugInfo<'_> {
842    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
843        match self {
844            StmtDebugInfo::AssignRef(local, place) => {
845                write!(fmt, "{local:?} = &{place:?}")
846            }
847            StmtDebugInfo::InvalidAssign(local) => {
848                write!(fmt, "{local:?} = &?")
849            }
850        }
851    }
852}
853
854impl Display for NonDivergingIntrinsic<'_> {
855    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
856        match self {
857            Self::Assume(op) => write!(f, "assume({op:?})"),
858            Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
859                write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
860            }
861        }
862    }
863}
864
865impl<'tcx> Debug for TerminatorKind<'tcx> {
866    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
867        self.fmt_head(fmt)?;
868        let successor_count = self.successors().count();
869        let labels = self.fmt_successor_labels();
870        assert_eq!(successor_count, labels.len());
871
872        // `Cleanup` is already included in successors
873        let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
874        let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
875            write!(fmt, "unwind ")?;
876            match self.unwind() {
877                // Not needed or included in successors
878                None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
879                Some(UnwindAction::Continue) => write!(fmt, "continue"),
880                Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
881                Some(UnwindAction::Terminate(reason)) => {
882                    write!(fmt, "terminate({})", reason.as_short_str())
883                }
884            }
885        };
886
887        match (successor_count, show_unwind) {
888            (0, false) => Ok(()),
889            (0, true) => {
890                write!(fmt, " -> ")?;
891                fmt_unwind(fmt)
892            }
893            (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
894            _ => {
895                write!(fmt, " -> [")?;
896                for (i, target) in self.successors().enumerate() {
897                    if i > 0 {
898                        write!(fmt, ", ")?;
899                    }
900                    write!(fmt, "{}: {:?}", labels[i], target)?;
901                }
902                if show_unwind {
903                    write!(fmt, ", ")?;
904                    fmt_unwind(fmt)?;
905                }
906                write!(fmt, "]")
907            }
908        }
909    }
910}
911
912impl<'tcx> TerminatorKind<'tcx> {
913    /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
914    /// successor basic block, if any. The only information not included is the list of possible
915    /// successors, which may be rendered differently between the text and the graphviz format.
916    pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
917        use self::TerminatorKind::*;
918        match self {
919            Goto { .. } => write!(fmt, "goto"),
920            SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
921            Return => write!(fmt, "return"),
922            CoroutineDrop => write!(fmt, "coroutine_drop"),
923            UnwindResume => write!(fmt, "resume"),
924            UnwindTerminate(reason) => {
925                write!(fmt, "terminate({})", reason.as_short_str())
926            }
927            Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
928            Unreachable => write!(fmt, "unreachable"),
929            Drop { place, async_fut: None, .. } => write!(fmt, "drop({place:?})"),
930            Drop { place, async_fut: Some(async_fut), .. } => {
931                write!(fmt, "async drop({place:?}; poll={async_fut:?})")
932            }
933            Call { func, args, destination, .. } => {
934                write!(fmt, "{destination:?} = ")?;
935                write!(fmt, "{func:?}(")?;
936                for (index, arg) in args.iter().enumerate() {
937                    if index > 0 {
938                        write!(fmt, ", ")?;
939                    }
940                    write!(fmt, "{:?}", arg.node)?;
941                }
942                write!(fmt, ")")
943            }
944            TailCall { func, args, .. } => {
945                write!(fmt, "tailcall {func:?}(")?;
946                for (index, arg) in args.iter().enumerate() {
947                    if index > 0 {
948                        write!(fmt, ", ")?;
949                    }
950                    write!(fmt, "{:?}", arg.node)?;
951                }
952                write!(fmt, ")")
953            }
954            Assert { cond, expected, msg, .. } => {
955                write!(fmt, "assert(")?;
956                if !expected {
957                    write!(fmt, "!")?;
958                }
959                write!(fmt, "{cond:?}, ")?;
960                msg.fmt_assert_args(fmt)?;
961                write!(fmt, ")")
962            }
963            FalseEdge { .. } => write!(fmt, "falseEdge"),
964            FalseUnwind { .. } => write!(fmt, "falseUnwind"),
965            InlineAsm { template, operands, options, .. } => {
966                write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
967                for op in operands {
968                    write!(fmt, ", ")?;
969                    let print_late = |&late| if late { "late" } else { "" };
970                    match op {
971                        InlineAsmOperand::In { reg, value } => {
972                            write!(fmt, "in({reg}) {value:?}")?;
973                        }
974                        InlineAsmOperand::Out { reg, late, place: Some(place) } => {
975                            write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
976                        }
977                        InlineAsmOperand::Out { reg, late, place: None } => {
978                            write!(fmt, "{}out({}) _", print_late(late), reg)?;
979                        }
980                        InlineAsmOperand::InOut {
981                            reg,
982                            late,
983                            in_value,
984                            out_place: Some(out_place),
985                        } => {
986                            write!(
987                                fmt,
988                                "in{}out({}) {:?} => {:?}",
989                                print_late(late),
990                                reg,
991                                in_value,
992                                out_place
993                            )?;
994                        }
995                        InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
996                            write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
997                        }
998                        InlineAsmOperand::Const { value } => {
999                            write!(fmt, "const {value:?}")?;
1000                        }
1001                        InlineAsmOperand::SymFn { value } => {
1002                            write!(fmt, "sym_fn {value:?}")?;
1003                        }
1004                        InlineAsmOperand::SymStatic { def_id } => {
1005                            write!(fmt, "sym_static {def_id:?}")?;
1006                        }
1007                        InlineAsmOperand::Label { target_index } => {
1008                            write!(fmt, "label {target_index}")?;
1009                        }
1010                    }
1011                }
1012                write!(fmt, ", options({options:?}))")
1013            }
1014        }
1015    }
1016
1017    /// Returns the list of labels for the edges to the successor basic blocks.
1018    pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1019        use self::TerminatorKind::*;
1020        match *self {
1021            Return
1022            | TailCall { .. }
1023            | UnwindResume
1024            | UnwindTerminate(_)
1025            | Unreachable
1026            | CoroutineDrop => vec![],
1027            Goto { .. } => vec!["".into()],
1028            SwitchInt { ref targets, .. } => targets
1029                .values
1030                .iter()
1031                .map(|&u| Cow::Owned(u.to_string()))
1032                .chain(iter::once("otherwise".into()))
1033                .collect(),
1034            Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1035                vec!["return".into(), "unwind".into()]
1036            }
1037            Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1038            Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1039            Call { target: None, unwind: _, .. } => vec![],
1040            Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1041            Yield { drop: None, .. } => vec!["resume".into()],
1042            Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1043                vec!["return".into(), "unwind".into(), "drop".into()]
1044            }
1045            Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1046                vec!["return".into(), "unwind".into()]
1047            }
1048            Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1049            Drop { unwind: _, .. } => vec!["return".into()],
1050            Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1051                vec!["success".into(), "unwind".into()]
1052            }
1053            Assert { unwind: _, .. } => vec!["success".into()],
1054            FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1055            FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1056                vec!["real".into(), "unwind".into()]
1057            }
1058            FalseUnwind { unwind: _, .. } => vec!["real".into()],
1059            InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1060                let mut vec = Vec::with_capacity(targets.len() + 1);
1061                if !asm_macro.diverges(options) {
1062                    vec.push("return".into());
1063                }
1064                vec.resize(targets.len(), "label".into());
1065
1066                if let UnwindAction::Cleanup(_) = unwind {
1067                    vec.push("unwind".into());
1068                }
1069
1070                vec
1071            }
1072        }
1073    }
1074}
1075
1076impl<'tcx> Debug for Rvalue<'tcx> {
1077    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1078        use self::Rvalue::*;
1079
1080        match *self {
1081            Use(ref place) => write!(fmt, "{place:?}"),
1082            Repeat(ref a, b) => {
1083                write!(fmt, "[{a:?}; ")?;
1084                pretty_print_const(b, fmt, false)?;
1085                write!(fmt, "]")
1086            }
1087            Cast(ref kind, ref place, ref ty) => {
1088                with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1089            }
1090            BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1091            UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1092            Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1093            NullaryOp(ref op, ref t) => {
1094                let t = with_no_trimmed_paths!(format!("{}", t));
1095                match op {
1096                    NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
1097                    NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
1098                    NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
1099                    NullOp::UbChecks => write!(fmt, "UbChecks()"),
1100                    NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
1101                }
1102            }
1103            ThreadLocalRef(did) => ty::tls::with(|tcx| {
1104                let muta = tcx.static_mutability(did).unwrap().prefix_str();
1105                write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1106            }),
1107            Ref(region, borrow_kind, ref place) => {
1108                let kind_str = match borrow_kind {
1109                    BorrowKind::Shared => "",
1110                    BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1111                    BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1112                    BorrowKind::Mut { .. } => "mut ",
1113                };
1114
1115                // When printing regions, add trailing space if necessary.
1116                let print_region = ty::tls::with(|tcx| {
1117                    tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1118                });
1119                let region = if print_region {
1120                    let mut region = region.to_string();
1121                    if !region.is_empty() {
1122                        region.push(' ');
1123                    }
1124                    region
1125                } else {
1126                    // Do not even print 'static
1127                    String::new()
1128                };
1129                write!(fmt, "&{region}{kind_str}{place:?}")
1130            }
1131
1132            CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1133
1134            RawPtr(mutability, ref place) => {
1135                write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1136            }
1137
1138            Aggregate(ref kind, ref places) => {
1139                let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1140                    let mut tuple_fmt = fmt.debug_tuple(name);
1141                    for place in places {
1142                        tuple_fmt.field(place);
1143                    }
1144                    tuple_fmt.finish()
1145                };
1146
1147                match **kind {
1148                    AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1149
1150                    AggregateKind::Tuple => {
1151                        if places.is_empty() {
1152                            write!(fmt, "()")
1153                        } else {
1154                            fmt_tuple(fmt, "")
1155                        }
1156                    }
1157
1158                    AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1159                        ty::tls::with(|tcx| {
1160                            let variant_def = &tcx.adt_def(adt_did).variant(variant);
1161                            let args = tcx.lift(args).expect("could not lift for printing");
1162                            let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1163                                p.print_def_path(variant_def.def_id, args)
1164                            })?;
1165
1166                            match variant_def.ctor_kind() {
1167                                Some(CtorKind::Const) => fmt.write_str(&name),
1168                                Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1169                                None => {
1170                                    let mut struct_fmt = fmt.debug_struct(&name);
1171                                    for (field, place) in iter::zip(&variant_def.fields, places) {
1172                                        struct_fmt.field(field.name.as_str(), place);
1173                                    }
1174                                    struct_fmt.finish()
1175                                }
1176                            }
1177                        })
1178                    }
1179
1180                    AggregateKind::Closure(def_id, args)
1181                    | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1182                        let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1183                            let args = tcx.lift(args).unwrap();
1184                            format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1185                        } else {
1186                            let span = tcx.def_span(def_id);
1187                            format!(
1188                                "{{closure@{}}}",
1189                                tcx.sess.source_map().span_to_diagnostic_string(span)
1190                            )
1191                        };
1192                        let mut struct_fmt = fmt.debug_struct(&name);
1193
1194                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1195                        if let Some(def_id) = def_id.as_local()
1196                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1197                        {
1198                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1199                                let var_name = tcx.hir_name(var_id);
1200                                struct_fmt.field(var_name.as_str(), place);
1201                            }
1202                        } else {
1203                            for (index, place) in places.iter().enumerate() {
1204                                struct_fmt.field(&format!("{index}"), place);
1205                            }
1206                        }
1207
1208                        struct_fmt.finish()
1209                    }),
1210
1211                    AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1212                        let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1213                        let mut struct_fmt = fmt.debug_struct(&name);
1214
1215                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1216                        if let Some(def_id) = def_id.as_local()
1217                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1218                        {
1219                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1220                                let var_name = tcx.hir_name(var_id);
1221                                struct_fmt.field(var_name.as_str(), place);
1222                            }
1223                        } else {
1224                            for (index, place) in places.iter().enumerate() {
1225                                struct_fmt.field(&format!("{index}"), place);
1226                            }
1227                        }
1228
1229                        struct_fmt.finish()
1230                    }),
1231
1232                    AggregateKind::RawPtr(pointee_ty, mutability) => {
1233                        let kind_str = match mutability {
1234                            Mutability::Mut => "mut",
1235                            Mutability::Not => "const",
1236                        };
1237                        with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1238                        fmt_tuple(fmt, "")
1239                    }
1240                }
1241            }
1242
1243            ShallowInitBox(ref place, ref ty) => {
1244                with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1245            }
1246
1247            WrapUnsafeBinder(ref op, ty) => {
1248                with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1249            }
1250        }
1251    }
1252}
1253
1254impl<'tcx> Debug for Operand<'tcx> {
1255    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1256        use self::Operand::*;
1257        match *self {
1258            Constant(ref a) => write!(fmt, "{a:?}"),
1259            Copy(ref place) => write!(fmt, "copy {place:?}"),
1260            Move(ref place) => write!(fmt, "move {place:?}"),
1261        }
1262    }
1263}
1264
1265impl<'tcx> Debug for ConstOperand<'tcx> {
1266    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1267        write!(fmt, "{self}")
1268    }
1269}
1270
1271impl<'tcx> Display for ConstOperand<'tcx> {
1272    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1273        match self.ty().kind() {
1274            ty::FnDef(..) => {}
1275            _ => write!(fmt, "const ")?,
1276        }
1277        Display::fmt(&self.const_, fmt)
1278    }
1279}
1280
1281impl Debug for Place<'_> {
1282    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1283        self.as_ref().fmt(fmt)
1284    }
1285}
1286
1287impl Debug for PlaceRef<'_> {
1288    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1289        pre_fmt_projection(self.projection, fmt)?;
1290        write!(fmt, "{:?}", self.local)?;
1291        post_fmt_projection(self.projection, fmt)
1292    }
1293}
1294
1295fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1296    for &elem in projection.iter().rev() {
1297        match elem {
1298            ProjectionElem::OpaqueCast(_)
1299            | ProjectionElem::Downcast(_, _)
1300            | ProjectionElem::Field(_, _) => {
1301                write!(fmt, "(")?;
1302            }
1303            ProjectionElem::Deref => {
1304                write!(fmt, "(*")?;
1305            }
1306            ProjectionElem::Index(_)
1307            | ProjectionElem::ConstantIndex { .. }
1308            | ProjectionElem::Subslice { .. } => {}
1309            ProjectionElem::UnwrapUnsafeBinder(_) => {
1310                write!(fmt, "unwrap_binder!(")?;
1311            }
1312        }
1313    }
1314
1315    Ok(())
1316}
1317
1318fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1319    for &elem in projection.iter() {
1320        match elem {
1321            ProjectionElem::OpaqueCast(ty) => {
1322                write!(fmt, " as {ty})")?;
1323            }
1324            ProjectionElem::Downcast(Some(name), _index) => {
1325                write!(fmt, " as {name})")?;
1326            }
1327            ProjectionElem::Downcast(None, index) => {
1328                write!(fmt, " as variant#{index:?})")?;
1329            }
1330            ProjectionElem::Deref => {
1331                write!(fmt, ")")?;
1332            }
1333            ProjectionElem::Field(field, ty) => {
1334                with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1335            }
1336            ProjectionElem::Index(ref index) => {
1337                write!(fmt, "[{index:?}]")?;
1338            }
1339            ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1340                write!(fmt, "[{offset:?} of {min_length:?}]")?;
1341            }
1342            ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1343                write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1344            }
1345            ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1346                write!(fmt, "[{from:?}:]")?;
1347            }
1348            ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1349                write!(fmt, "[:-{to:?}]")?;
1350            }
1351            ProjectionElem::Subslice { from, to, from_end: true } => {
1352                write!(fmt, "[{from:?}:-{to:?}]")?;
1353            }
1354            ProjectionElem::Subslice { from, to, from_end: false } => {
1355                write!(fmt, "[{from:?}..{to:?}]")?;
1356            }
1357            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1358                write!(fmt, "; {ty})")?;
1359            }
1360        }
1361    }
1362
1363    Ok(())
1364}
1365
1366/// After we print the main statement, we sometimes dump extra
1367/// information. There's often a lot of little things "nuzzled up" in
1368/// a statement.
1369fn write_extra<'tcx>(
1370    tcx: TyCtxt<'tcx>,
1371    write: &mut dyn io::Write,
1372    visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1373    options: PrettyPrintMirOptions,
1374) -> io::Result<()> {
1375    if options.include_extra_comments {
1376        let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1377        visit_op(&mut extra_comments);
1378        for comment in extra_comments.comments {
1379            writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1380        }
1381    }
1382    Ok(())
1383}
1384
1385struct ExtraComments<'tcx> {
1386    tcx: TyCtxt<'tcx>,
1387    comments: Vec<String>,
1388}
1389
1390impl<'tcx> ExtraComments<'tcx> {
1391    fn push(&mut self, lines: &str) {
1392        for line in lines.split('\n') {
1393            self.comments.push(line.to_string());
1394        }
1395    }
1396}
1397
1398fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1399    match *ty.kind() {
1400        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1401        // Unit type
1402        ty::Tuple(g_args) if g_args.is_empty() => false,
1403        ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1404        ty::Array(ty, _) => use_verbose(ty, fn_def),
1405        ty::FnDef(..) => fn_def,
1406        _ => true,
1407    }
1408}
1409
1410impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1411    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1412        let ConstOperand { span, user_ty, const_ } = constant;
1413        if use_verbose(const_.ty(), true) {
1414            self.push("mir::ConstOperand");
1415            self.push(&format!(
1416                "+ span: {}",
1417                self.tcx.sess.source_map().span_to_embeddable_string(*span)
1418            ));
1419            if let Some(user_ty) = user_ty {
1420                self.push(&format!("+ user_ty: {user_ty:?}"));
1421            }
1422
1423            let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1424                let tcx = self.tcx;
1425                rustc_data_structures::make_display(move |fmt| {
1426                    pretty_print_const_value_tcx(tcx, val, ty, fmt)
1427                })
1428            };
1429
1430            let fmt_valtree = |cv: &ty::Value<'tcx>| {
1431                let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1432                p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1433                p.into_buffer()
1434            };
1435
1436            let val = match const_ {
1437                Const::Ty(_, ct) => match ct.kind() {
1438                    ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1439                    ty::ConstKind::Unevaluated(uv) => {
1440                        format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1441                    }
1442                    ty::ConstKind::Value(cv) => {
1443                        format!("ty::Valtree({})", fmt_valtree(&cv))
1444                    }
1445                    // No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`.
1446                    ty::ConstKind::Error(_) => "Error".to_string(),
1447                    // These variants shouldn't exist in the MIR.
1448                    ty::ConstKind::Placeholder(_)
1449                    | ty::ConstKind::Infer(_)
1450                    | ty::ConstKind::Expr(_)
1451                    | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1452                },
1453                Const::Unevaluated(uv, _) => {
1454                    format!(
1455                        "Unevaluated({}, {:?}, {:?})",
1456                        self.tcx.def_path_str(uv.def),
1457                        uv.args,
1458                        uv.promoted,
1459                    )
1460                }
1461                Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1462            };
1463
1464            // This reflects what `Const` looked liked before `val` was renamed
1465            // as `kind`. We print it like this to avoid having to update
1466            // expected output in a lot of tests.
1467            self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1468        }
1469    }
1470
1471    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1472        self.super_rvalue(rvalue, location);
1473        if let Rvalue::Aggregate(kind, _) = rvalue {
1474            match **kind {
1475                AggregateKind::Closure(def_id, args) => {
1476                    self.push("closure");
1477                    self.push(&format!("+ def_id: {def_id:?}"));
1478                    self.push(&format!("+ args: {args:#?}"));
1479                }
1480
1481                AggregateKind::Coroutine(def_id, args) => {
1482                    self.push("coroutine");
1483                    self.push(&format!("+ def_id: {def_id:?}"));
1484                    self.push(&format!("+ args: {args:#?}"));
1485                    self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1486                }
1487
1488                AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1489                    self.push("adt");
1490                    self.push(&format!("+ user_ty: {user_ty:?}"));
1491                }
1492
1493                _ => {}
1494            }
1495        }
1496    }
1497}
1498
1499fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1500    let location = tcx.sess.source_map().span_to_embeddable_string(span);
1501    format!("scope {} at {}", scope.index(), location,)
1502}
1503
1504///////////////////////////////////////////////////////////////////////////
1505// Allocations
1506
1507/// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
1508/// allocations.
1509pub fn write_allocations<'tcx>(
1510    tcx: TyCtxt<'tcx>,
1511    body: &Body<'_>,
1512    w: &mut dyn io::Write,
1513) -> io::Result<()> {
1514    fn alloc_ids_from_alloc(
1515        alloc: ConstAllocation<'_>,
1516    ) -> impl DoubleEndedIterator<Item = AllocId> {
1517        alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1518    }
1519
1520    fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1521        match val {
1522            ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1523            ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1524            ConstValue::ZeroSized => None,
1525            ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1526                // FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR.
1527                // Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor.
1528                Some(alloc_id)
1529            }
1530        }
1531    }
1532    struct CollectAllocIds(BTreeSet<AllocId>);
1533
1534    impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1535        fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1536            match c.const_ {
1537                Const::Ty(_, _) | Const::Unevaluated(..) => {}
1538                Const::Val(val, _) => {
1539                    if let Some(id) = alloc_id_from_const_val(val) {
1540                        self.0.insert(id);
1541                    }
1542                }
1543            }
1544        }
1545    }
1546
1547    let mut visitor = CollectAllocIds(Default::default());
1548    visitor.visit_body(body);
1549
1550    // `seen` contains all seen allocations, including the ones we have *not* printed yet.
1551    // The protocol is to first `insert` into `seen`, and only if that returns `true`
1552    // then push to `todo`.
1553    let mut seen = visitor.0;
1554    let mut todo: Vec<_> = seen.iter().copied().collect();
1555    while let Some(id) = todo.pop() {
1556        let mut write_allocation_track_relocs =
1557            |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1558                // `.rev()` because we are popping them from the back of the `todo` vector.
1559                for id in alloc_ids_from_alloc(alloc).rev() {
1560                    if seen.insert(id) {
1561                        todo.push(id);
1562                    }
1563                }
1564                write!(w, "{}", display_allocation(tcx, alloc.inner()))
1565            };
1566        write!(w, "\n{id:?}")?;
1567        match tcx.try_get_global_alloc(id) {
1568            // This can't really happen unless there are bugs, but it doesn't cost us anything to
1569            // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
1570            None => write!(w, " (deallocated)")?,
1571            Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1572            Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1573                write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1574            }
1575            Some(GlobalAlloc::TypeId { ty }) => write!(w, " (typeid for {ty})")?,
1576            Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1577                write!(w, " (static: {}", tcx.def_path_str(did))?;
1578                if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1579                    && body
1580                        .source
1581                        .def_id()
1582                        .as_local()
1583                        .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1584                {
1585                    // Statics may be cyclic and evaluating them too early
1586                    // in the MIR pipeline may cause cycle errors even though
1587                    // normal compilation is fine.
1588                    write!(w, ")")?;
1589                } else {
1590                    match tcx.eval_static_initializer(did) {
1591                        Ok(alloc) => {
1592                            write!(w, ", ")?;
1593                            write_allocation_track_relocs(w, alloc)?;
1594                        }
1595                        Err(_) => write!(w, ", error during initializer evaluation)")?,
1596                    }
1597                }
1598            }
1599            Some(GlobalAlloc::Static(did)) => {
1600                write!(w, " (extern static: {})", tcx.def_path_str(did))?
1601            }
1602            Some(GlobalAlloc::Memory(alloc)) => {
1603                write!(w, " (")?;
1604                write_allocation_track_relocs(w, alloc)?
1605            }
1606        }
1607        writeln!(w)?;
1608    }
1609    Ok(())
1610}
1611
1612/// Dumps the size and metadata and content of an allocation to the given writer.
1613/// The expectation is that the caller first prints other relevant metadata, so the exact
1614/// format of this function is (*without* leading or trailing newline):
1615///
1616/// ```text
1617/// size: {}, align: {}) {
1618///     <bytes>
1619/// }
1620/// ```
1621///
1622/// The byte format is similar to how hex editors print bytes. Each line starts with the address of
1623/// the start of the line, followed by all bytes in hex format (space separated).
1624/// If the allocation is small enough to fit into a single line, no start address is given.
1625/// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
1626/// characters or characters whose value is larger than 127) with a `.`
1627/// This also prints provenance adequately.
1628pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1629    tcx: TyCtxt<'tcx>,
1630    alloc: &'a Allocation<Prov, Extra, Bytes>,
1631) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1632    RenderAllocation { tcx, alloc }
1633}
1634
1635#[doc(hidden)]
1636pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1637    tcx: TyCtxt<'tcx>,
1638    alloc: &'a Allocation<Prov, Extra, Bytes>,
1639}
1640
1641impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1642    for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1643{
1644    fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1645        let RenderAllocation { tcx, alloc } = *self;
1646        write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1647        if alloc.size() == Size::ZERO {
1648            // We are done.
1649            return write!(w, " {{}}");
1650        }
1651        if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1652            return write!(w, " {{ .. }}");
1653        }
1654        // Write allocation bytes.
1655        writeln!(w, " {{")?;
1656        write_allocation_bytes(tcx, alloc, w, "    ")?;
1657        write!(w, "}}")?;
1658        Ok(())
1659    }
1660}
1661
1662fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1663    for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1664        write!(w, "   ")?;
1665    }
1666    writeln!(w, " │ {ascii}")
1667}
1668
1669/// Number of bytes to print per allocation hex dump line.
1670const BYTES_PER_LINE: usize = 16;
1671
1672/// Prints the line start address and returns the new line start address.
1673fn write_allocation_newline(
1674    w: &mut dyn std::fmt::Write,
1675    mut line_start: Size,
1676    ascii: &str,
1677    pos_width: usize,
1678    prefix: &str,
1679) -> Result<Size, std::fmt::Error> {
1680    write_allocation_endline(w, ascii)?;
1681    line_start += Size::from_bytes(BYTES_PER_LINE);
1682    write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1683    Ok(line_start)
1684}
1685
1686/// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
1687/// is only one line). Note that your prefix should contain a trailing space as the lines are
1688/// printed directly after it.
1689pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1690    tcx: TyCtxt<'tcx>,
1691    alloc: &Allocation<Prov, Extra, Bytes>,
1692    w: &mut dyn std::fmt::Write,
1693    prefix: &str,
1694) -> std::fmt::Result {
1695    let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1696    // Number of chars needed to represent all line numbers.
1697    let pos_width = hex_number_length(alloc.size().bytes());
1698
1699    if num_lines > 0 {
1700        write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1701    } else {
1702        write!(w, "{prefix}")?;
1703    }
1704
1705    let mut i = Size::ZERO;
1706    let mut line_start = Size::ZERO;
1707
1708    let ptr_size = tcx.data_layout.pointer_size();
1709
1710    let mut ascii = String::new();
1711
1712    let oversized_ptr = |target: &mut String, width| {
1713        if target.len() > width {
1714            write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1715        }
1716    };
1717
1718    while i < alloc.size() {
1719        // The line start already has a space. While we could remove that space from the line start
1720        // printing and unconditionally print a space here, that would cause the single-line case
1721        // to have a single space before it, which looks weird.
1722        if i != line_start {
1723            write!(w, " ")?;
1724        }
1725        if let Some(prov) = alloc.provenance().get_ptr(i) {
1726            // Memory with provenance must be defined
1727            assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1728            let j = i.bytes_usize();
1729            let offset = alloc
1730                .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1731            let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1732            let offset = Size::from_bytes(offset);
1733            let provenance_width = |bytes| bytes * 3;
1734            let ptr = Pointer::new(prov, offset);
1735            let mut target = format!("{ptr:?}");
1736            if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1737                // This is too long, try to save some space.
1738                target = format!("{ptr:#?}");
1739            }
1740            if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1741                // This branch handles the situation where a provenance starts in the current line
1742                // but ends in the next one.
1743                let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1744                let overflow = ptr_size - remainder;
1745                let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1746                let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1747                ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
1748                for _ in 1..remainder.bytes() {
1749                    ascii.push('─'); // LIGHT HORIZONTAL
1750                }
1751                if overflow_width > remainder_width && overflow_width >= target.len() {
1752                    // The case where the provenance fits into the part in the next line
1753                    write!(w, "╾{0:─^1$}", "", remainder_width)?;
1754                    line_start =
1755                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1756                    ascii.clear();
1757                    write!(w, "{target:─^overflow_width$}╼")?;
1758                } else {
1759                    oversized_ptr(&mut target, remainder_width);
1760                    write!(w, "╾{target:─^remainder_width$}")?;
1761                    line_start =
1762                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1763                    write!(w, "{0:─^1$}╼", "", overflow_width)?;
1764                    ascii.clear();
1765                }
1766                for _ in 0..overflow.bytes() - 1 {
1767                    ascii.push('─');
1768                }
1769                ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
1770                i += ptr_size;
1771                continue;
1772            } else {
1773                // This branch handles a provenance that starts and ends in the current line.
1774                let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1775                oversized_ptr(&mut target, provenance_width);
1776                ascii.push('╾');
1777                write!(w, "╾{target:─^provenance_width$}╼")?;
1778                for _ in 0..ptr_size.bytes() - 2 {
1779                    ascii.push('─');
1780                }
1781                ascii.push('╼');
1782                i += ptr_size;
1783            }
1784        } else if let Some((prov, idx)) = alloc.provenance().get_byte(i, &tcx) {
1785            // Memory with provenance must be defined
1786            assert!(
1787                alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1788            );
1789            ascii.push('━'); // HEAVY HORIZONTAL
1790            // We have two characters to display this, which is obviously not enough.
1791            // Format is similar to "oversized" above.
1792            let j = i.bytes_usize();
1793            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1794            write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼")?;
1795            i += Size::from_bytes(1);
1796        } else if alloc
1797            .init_mask()
1798            .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1799            .is_ok()
1800        {
1801            let j = i.bytes_usize();
1802
1803            // Checked definedness (and thus range) and provenance. This access also doesn't
1804            // influence interpreter execution but is only for debugging.
1805            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1806            write!(w, "{c:02x}")?;
1807            if c.is_ascii_control() || c >= 0x80 {
1808                ascii.push('.');
1809            } else {
1810                ascii.push(char::from(c));
1811            }
1812            i += Size::from_bytes(1);
1813        } else {
1814            write!(w, "__")?;
1815            ascii.push('░');
1816            i += Size::from_bytes(1);
1817        }
1818        // Print a new line header if the next line still has some bytes to print.
1819        if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1820            line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1821            ascii.clear();
1822        }
1823    }
1824    write_allocation_endline(w, &ascii)?;
1825
1826    Ok(())
1827}
1828
1829///////////////////////////////////////////////////////////////////////////
1830// Constants
1831
1832fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1833    write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1834}
1835
1836fn comma_sep<'tcx>(
1837    tcx: TyCtxt<'tcx>,
1838    fmt: &mut Formatter<'_>,
1839    elems: Vec<(ConstValue, Ty<'tcx>)>,
1840) -> fmt::Result {
1841    let mut first = true;
1842    for (ct, ty) in elems {
1843        if !first {
1844            fmt.write_str(", ")?;
1845        }
1846        pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1847        first = false;
1848    }
1849    Ok(())
1850}
1851
1852fn pretty_print_const_value_tcx<'tcx>(
1853    tcx: TyCtxt<'tcx>,
1854    ct: ConstValue,
1855    ty: Ty<'tcx>,
1856    fmt: &mut Formatter<'_>,
1857) -> fmt::Result {
1858    use crate::ty::print::PrettyPrinter;
1859
1860    if tcx.sess.verbose_internals() {
1861        fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1862        return Ok(());
1863    }
1864
1865    let u8_type = tcx.types.u8;
1866    match (ct, ty.kind()) {
1867        // Byte/string slices, printed as (byte) string literals.
1868        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1869            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1870                fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1871                return Ok(());
1872            }
1873        }
1874        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1875            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1876                pretty_print_byte_str(fmt, data)?;
1877                return Ok(());
1878            }
1879        }
1880        (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1881            let n = n.try_to_target_usize(tcx).unwrap();
1882            let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1883            // cast is ok because we already checked for pointer size (32 or 64 bit) above
1884            let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1885            let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1886            fmt.write_str("*")?;
1887            pretty_print_byte_str(fmt, byte_str)?;
1888            return Ok(());
1889        }
1890        // Aggregates, printed as array/tuple/struct/variant construction syntax.
1891        //
1892        // NB: the `has_non_region_param` check ensures that we can use
1893        // the `destructure_const` query with an empty `ty::ParamEnv` without
1894        // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1895        // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1896        // to be able to destructure the tuple into `(0u8, *mut T)`
1897        (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1898            let ct = tcx.lift(ct).unwrap();
1899            let ty = tcx.lift(ty).unwrap();
1900            if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1901                let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1902                match *ty.kind() {
1903                    ty::Array(..) => {
1904                        fmt.write_str("[")?;
1905                        comma_sep(tcx, fmt, fields)?;
1906                        fmt.write_str("]")?;
1907                    }
1908                    ty::Tuple(..) => {
1909                        fmt.write_str("(")?;
1910                        comma_sep(tcx, fmt, fields)?;
1911                        if contents.fields.len() == 1 {
1912                            fmt.write_str(",")?;
1913                        }
1914                        fmt.write_str(")")?;
1915                    }
1916                    ty::Adt(def, _) if def.variants().is_empty() => {
1917                        fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1918                    }
1919                    ty::Adt(def, args) => {
1920                        let variant_idx = contents
1921                            .variant
1922                            .expect("destructed mir constant of adt without variant idx");
1923                        let variant_def = &def.variant(variant_idx);
1924                        let args = tcx.lift(args).unwrap();
1925                        let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1926                        p.print_alloc_ids = true;
1927                        p.pretty_print_value_path(variant_def.def_id, args)?;
1928                        fmt.write_str(&p.into_buffer())?;
1929
1930                        match variant_def.ctor_kind() {
1931                            Some(CtorKind::Const) => {}
1932                            Some(CtorKind::Fn) => {
1933                                fmt.write_str("(")?;
1934                                comma_sep(tcx, fmt, fields)?;
1935                                fmt.write_str(")")?;
1936                            }
1937                            None => {
1938                                fmt.write_str(" {{ ")?;
1939                                let mut first = true;
1940                                for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1941                                {
1942                                    if !first {
1943                                        fmt.write_str(", ")?;
1944                                    }
1945                                    write!(fmt, "{}: ", field_def.name)?;
1946                                    pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1947                                    first = false;
1948                                }
1949                                fmt.write_str(" }}")?;
1950                            }
1951                        }
1952                    }
1953                    _ => unreachable!(),
1954                }
1955                return Ok(());
1956            }
1957        }
1958        (ConstValue::Scalar(scalar), _) => {
1959            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1960            p.print_alloc_ids = true;
1961            let ty = tcx.lift(ty).unwrap();
1962            p.pretty_print_const_scalar(scalar, ty)?;
1963            fmt.write_str(&p.into_buffer())?;
1964            return Ok(());
1965        }
1966        (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
1967            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1968            p.print_alloc_ids = true;
1969            p.pretty_print_value_path(*d, s)?;
1970            fmt.write_str(&p.into_buffer())?;
1971            return Ok(());
1972        }
1973        // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1974        // their fields instead of just dumping the memory.
1975        _ => {}
1976    }
1977    // Fall back to debug pretty printing for invalid constants.
1978    write!(fmt, "{ct:?}: {ty}")
1979}
1980
1981pub(crate) fn pretty_print_const_value<'tcx>(
1982    ct: ConstValue,
1983    ty: Ty<'tcx>,
1984    fmt: &mut Formatter<'_>,
1985) -> fmt::Result {
1986    ty::tls::with(|tcx| {
1987        let ct = tcx.lift(ct).unwrap();
1988        let ty = tcx.lift(ty).unwrap();
1989        pretty_print_const_value_tcx(tcx, ct, ty, fmt)
1990    })
1991}
1992
1993///////////////////////////////////////////////////////////////////////////
1994// Miscellaneous
1995
1996/// Calc converted u64 decimal into hex and return its length in chars.
1997///
1998/// ```ignore (cannot-test-private-function)
1999/// assert_eq!(1, hex_number_length(0));
2000/// assert_eq!(1, hex_number_length(1));
2001/// assert_eq!(2, hex_number_length(16));
2002/// ```
2003fn hex_number_length(x: u64) -> usize {
2004    if x == 0 {
2005        return 1;
2006    }
2007    let mut length = 0;
2008    let mut x_left = x;
2009    while x_left > 0 {
2010        x_left /= 16;
2011        length += 1;
2012    }
2013    length
2014}