flux_rustc_bridge/
mir.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! A simplified version of rust mir.

use std::fmt;

use flux_arc_interner::List;
use flux_common::index::{Idx, IndexVec};
use itertools::Itertools;
use rustc_ast::Mutability;
pub use rustc_borrowck::borrow_set::BorrowData;
use rustc_borrowck::consumers::{BodyWithBorrowckFacts, BorrowIndex};
use rustc_data_structures::{
    fx::FxIndexMap,
    graph::{self, dominators::Dominators, DirectedGraph, StartNode},
};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_index::IndexSlice;
use rustc_infer::infer::TyCtxtInferExt;
use rustc_macros::{TyDecodable, TyEncodable};
use rustc_middle::{
    mir,
    ty::{FloatTy, IntTy, ParamConst, TyCtxt, TypingMode, UintTy},
};
pub use rustc_middle::{
    mir::{
        BasicBlock, BorrowKind, FakeBorrowKind, FakeReadCause, Local, LocalKind, Location,
        SourceInfo, SwitchTargets, UnOp, UnwindAction, RETURN_PLACE, START_BLOCK,
    },
    ty::{UserTypeAnnotationIndex, Variance},
};
use rustc_span::{Span, Symbol};
pub use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT};

use super::ty::{Const, GenericArg, GenericArgs, Region, Ty};
use crate::{
    def_id_to_string,
    ty::{region_to_string, Binder, FnSig},
};

pub struct Body<'tcx> {
    pub basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
    pub local_decls: IndexVec<Local, LocalDecl>,
    /// During borrow checking, `rustc` generates fresh [region variable ids] for each structurally
    /// different position in a type. For example, given a function
    ///
    /// `fn foo<'a, 'b>(x: &'a S<'a>, y: &'b u32)`
    ///
    /// `rustc` will generate variables `?2` and `?3` for the universal regions `'a` and `'b` (the variable
    /// `?0` correspond to `'static` and `?1` to the implicit lifetime of the function body). Additionally,
    /// it will assign `x` type &'?4 S<'?5>` and `y` type `&'?6 u32` (together with some constraints relating
    /// region variables). Unfortunately, we cannot recover the exact region variables rustc used.
    ///
    /// The exact ids picked for `'a` and `'b` are not too relevant to us, the important part is the regions
    /// used in the types of `x` and `y`. To work around this, we generate fresh regions variables for
    /// the function signature, different from the ones sued by rustc. To recover the correct regions, whenever
    /// there's an assignment of a refinement type `T` to a variable with (unrefined) Rust type `S`, we _match_
    /// both types to infer a region substitution. For this to work, we need to give a different variable id to every
    /// position in `T`. To avoid clashes, we need to use fresh ids, so we start enumerating from the last id
    /// generated by borrow checking.
    ///
    /// To do that, we replicate the [`InferCtxt`] use for mir typeck by generating region variables for every
    /// region in the `RegionInferenceContext`. The [`InferCtxt`] is then used to generate new region variables.
    ///
    /// The ids generated during refinement type checking are purely instrumental and temporary, they should never
    /// appear in a type bound in the environment.
    ///
    /// Besides generating ids when checking a function's body, we also need to generate fresh ids at
    /// function calls.
    ///
    /// Additionally, the [`InferCtxt`] is used during type projection normalization.
    ///
    /// [region variable ids]: super::ty::RegionVid
    /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
    pub infcx: rustc_infer::infer::InferCtxt<'tcx>,
    pub dominator_order_rank: IndexVec<BasicBlock, u32>,
    /// See [`mk_fake_predecessors`]
    fake_predecessors: IndexVec<BasicBlock, usize>,
    body_with_facts: BodyWithBorrowckFacts<'tcx>,
}

#[derive(Debug)]
pub struct BasicBlockData<'tcx> {
    pub statements: Vec<Statement>,
    pub terminator: Option<Terminator<'tcx>>,
    pub is_cleanup: bool,
}

pub type LocalDecls = IndexSlice<Local, LocalDecl>;

#[derive(Clone, Debug)]
pub struct LocalDecl {
    pub ty: Ty,
    pub source_info: SourceInfo,
}

pub struct Terminator<'tcx> {
    pub kind: TerminatorKind<'tcx>,
    pub source_info: SourceInfo,
}

#[derive(Debug)]
pub struct CallArgs<'tcx> {
    pub orig: rustc_middle::ty::GenericArgsRef<'tcx>,
    pub lowered: List<GenericArg>,
}

/// An `Instance` is the resolved call-target at a particular trait-call-site
#[derive(Debug)]
pub struct Instance {
    pub impl_f: DefId,
    pub args: GenericArgs,
}

pub enum CallKind<'tcx> {
    FnDef {
        def_id: DefId,
        generic_args: CallArgs<'tcx>,
        resolved_id: DefId,
        resolved_args: CallArgs<'tcx>,
    },
    FnPtr {
        fn_sig: Binder<FnSig>,
        operand: Operand,
    },
}

#[derive(Debug)]
pub enum TerminatorKind<'tcx> {
    Return,
    Call {
        kind: CallKind<'tcx>,
        args: Vec<Operand>,
        destination: Place,
        target: Option<BasicBlock>,
        unwind: UnwindAction,
    },
    SwitchInt {
        discr: Operand,
        targets: SwitchTargets,
    },
    Goto {
        target: BasicBlock,
    },
    Drop {
        place: Place,
        target: BasicBlock,
        unwind: UnwindAction,
    },
    Assert {
        cond: Operand,
        expected: bool,
        target: BasicBlock,
        msg: AssertKind,
    },
    Unreachable,
    FalseEdge {
        real_target: BasicBlock,
        imaginary_target: BasicBlock,
    },
    FalseUnwind {
        real_target: BasicBlock,
        unwind: UnwindAction,
    },
    Yield {
        value: Operand,
        resume: BasicBlock,
        resume_arg: Place,
        drop: Option<BasicBlock>,
    },
    CoroutineDrop,
    UnwindResume,
}

#[derive(Debug)]
pub enum AssertKind {
    BoundsCheck,
    RemainderByZero,
    Overflow(BinOp),
    DivisionByZero,
    // OverflowNeg(O),
    // ResumedAfterReturn(GeneratorKind),
    // ResumedAfterPanic(GeneratorKind),
}

pub struct Statement {
    pub kind: StatementKind,
    pub source_info: SourceInfo,
}

#[derive(Debug)]
pub enum NonDivergingIntrinsic {
    Assume(Operand),
}

#[derive(Debug)]
pub enum StatementKind {
    Assign(Place, Rvalue),
    SetDiscriminant(Place, VariantIdx),
    FakeRead(Box<(FakeReadCause, Place)>),
    AscribeUserType(Place, Variance),
    Intrinsic(NonDivergingIntrinsic),
    PlaceMention(Place),
    Nop,
}

/// Corresponds to <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.Rvalue.html>
pub enum Rvalue {
    Use(Operand),
    Repeat(Operand, Const),
    Ref(Region, BorrowKind, Place),
    RawPtr(Mutability, Place),
    Len(Place),
    Cast(CastKind, Operand, Ty),
    BinaryOp(BinOp, Operand, Operand),
    NullaryOp(NullOp, Ty),
    UnaryOp(UnOp, Operand),
    Discriminant(Place),
    Aggregate(AggregateKind, Vec<Operand>),
    ShallowInitBox(Operand, Ty),
}

#[derive(Copy, Clone)]
pub enum CastKind {
    IntToInt,
    FloatToInt,
    IntToFloat,
    PtrToPtr,
    PointerCoercion(PointerCast),
    PointerExposeProvenance,
    PointerWithExposedProvenance,
}

#[derive(Copy, Clone)]
pub enum PointerCast {
    MutToConstPointer,
    Unsize,
    ClosureFnPointer,
    ReifyFnPointer,
}

#[derive(Debug)]
pub enum AggregateKind {
    Adt(DefId, VariantIdx, GenericArgs, Option<UserTypeAnnotationIndex>, Option<FieldIdx>),
    Array(Ty),
    Tuple,
    Closure(DefId, GenericArgs),
    Coroutine(DefId, GenericArgs),
}

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum BinOp {
    Gt,
    Ge,
    Lt,
    Le,
    Eq,
    Ne,
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
}

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum NullOp {
    SizeOf,
    AlignOf,
}

pub enum Operand {
    Copy(Place),
    Move(Place),
    Constant(Constant),
}

#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
pub struct Place {
    /// the "root" of the place, e.g. `_1` in `*_1.f.g.h`
    pub local: Local,
    /// path taken to "get" the place e.g. `*.f.g.h` in `*_1.f.g.h` (except also have derefs)
    pub projection: Vec<PlaceElem>,
}

impl Place {
    pub const RETURN: &'static Place = &Place { local: RETURN_PLACE, projection: vec![] };

    pub fn new(local: Local, projection: Vec<PlaceElem>) -> Place {
        Place { local, projection }
    }

    pub fn as_ref(&self) -> PlaceRef {
        PlaceRef { local: self.local, projection: &self.projection[..] }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
pub enum PlaceElem {
    Deref,
    Field(FieldIdx),
    Downcast(Option<Symbol>, VariantIdx),
    Index(Local),
    ConstantIndex {
        /// index or -index (in Python terms), depending on from_end
        offset: u64,
        /// The thing being indexed must be at least this long. For arrays this
        /// is always the exact length.
        min_length: u64,
        /// Counting backwards from end? This is always false when indexing an
        /// array.
        from_end: bool,
    },
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PlaceRef<'a> {
    pub local: Local,
    pub projection: &'a [PlaceElem],
}

impl<'a> PlaceRef<'a> {
    pub fn truncate(self, i: usize) -> PlaceRef<'a> {
        Self { local: self.local, projection: &self.projection[..i] }
    }

    pub fn to_place(self) -> Place {
        Place { local: self.local, projection: self.projection.to_vec() }
    }

    pub fn last_projection(self) -> Option<(PlaceRef<'a>, PlaceElem)> {
        if let [base @ .., elem] = self.projection {
            Some((PlaceRef { local: self.local, projection: base }, *elem))
        } else {
            None
        }
    }
}

pub enum Constant {
    Int(i128, IntTy),
    Uint(u128, UintTy),
    Float(u128, FloatTy),
    Bool(bool),
    Str(Symbol),
    Char(char),
    Unit,
    Param(ParamConst, Ty),
    /// General catch-all for constants of a given Ty
    Opaque(Ty),
}

impl Terminator<'_> {
    pub fn is_return(&self) -> bool {
        matches!(self.kind, TerminatorKind::Return)
    }
}

impl Statement {
    pub fn is_nop(&self) -> bool {
        matches!(self.kind, StatementKind::Nop)
    }
}

impl<'tcx> Body<'tcx> {
    pub fn new(
        basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
        local_decls: IndexVec<Local, LocalDecl>,
        body_with_facts: BodyWithBorrowckFacts<'tcx>,
        infcx: rustc_infer::infer::InferCtxt<'tcx>,
    ) -> Self {
        let fake_predecessors = mk_fake_predecessors(&basic_blocks);

        // The dominator rank of each node is just its index in a reverse-postorder traversal.
        let graph = &body_with_facts.body.basic_blocks;
        let mut dominator_order_rank = IndexVec::from_elem_n(0, graph.num_nodes());
        let reverse_post_order = graph::iterate::reverse_post_order(graph, graph.start_node());
        assert_eq!(reverse_post_order.len(), graph.num_nodes());
        for (rank, bb) in (0u32..).zip(reverse_post_order) {
            dominator_order_rank[bb] = rank;
        }

        Self {
            basic_blocks,
            local_decls,
            infcx,
            fake_predecessors,
            body_with_facts,
            dominator_order_rank,
        }
    }

    pub fn def_id(&self) -> DefId {
        self.inner().source.def_id()
    }

    pub fn span(&self) -> Span {
        self.body_with_facts.body.span
    }

    pub fn inner(&self) -> &mir::Body<'tcx> {
        &self.body_with_facts.body
    }

    #[inline]
    pub fn args_iter(&self) -> impl ExactSizeIterator<Item = Local> {
        (1..self.body_with_facts.body.arg_count + 1).map(Local::new)
    }

    #[inline]
    pub fn vars_and_temps_iter(&self) -> impl ExactSizeIterator<Item = Local> {
        (self.body_with_facts.body.arg_count + 1..self.local_decls.len()).map(Local::new)
    }

    #[inline]
    pub fn is_join_point(&self, bb: BasicBlock) -> bool {
        let total_preds = self.body_with_facts.body.basic_blocks.predecessors()[bb].len();
        let real_preds = total_preds - self.fake_predecessors[bb];
        // The entry block is a joint point if it has at least one predecessor because there's
        // an implicit goto from the environment at the beginning of the function.
        real_preds > usize::from(bb != START_BLOCK)
    }

    #[inline]
    pub fn dominators(&self) -> &Dominators<BasicBlock> {
        self.body_with_facts.body.basic_blocks.dominators()
    }

    pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
        Location { block: bb, statement_index: self.basic_blocks[bb].statements.len() }
    }

    pub fn calculate_borrows_out_of_scope_at_location(
        &self,
    ) -> FxIndexMap<Location, Vec<BorrowIndex>> {
        rustc_borrowck::consumers::calculate_borrows_out_of_scope_at_location(
            &self.body_with_facts.body,
            &self.body_with_facts.region_inference_context,
            &self.body_with_facts.borrow_set,
        )
    }

    pub fn borrow_data(&self, idx: BorrowIndex) -> &BorrowData<'tcx> {
        self.body_with_facts
            .borrow_set
            .location_map
            .get_index(idx.as_usize())
            .unwrap()
            .1
    }

    pub fn rustc_body(&self) -> &mir::Body<'tcx> {
        &self.body_with_facts.body
    }

    pub fn local_kind(&self, local: Local) -> LocalKind {
        self.body_with_facts.body.local_kind(local)
    }
}

/// Replicate the [`InferCtxt`] used for mir typeck by generating region variables for every region in
/// the `RegionInferenceContext`
///
/// [`InferCtxt`]: rustc_infer::infer::InferCtxt
pub(crate) fn replicate_infer_ctxt<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: LocalDefId,
    body_with_facts: &BodyWithBorrowckFacts<'tcx>,
) -> rustc_infer::infer::InferCtxt<'tcx> {
    let infcx = tcx
        .infer_ctxt()
        .build(TypingMode::analysis_in_body(tcx, def_id));
    for info in &body_with_facts.region_inference_context.var_infos {
        infcx.next_region_var(info.origin);
    }
    infcx
}

/// The `FalseEdge/imaginary_target` edges mess up the `is_join_point` computation which creates spurious
/// join points that lose information e.g. in match arms, the k+1-th arm has the k-th arm as a "fake"
/// predecessor so we lose the assumptions specific to the k+1-th arm due to a spurious join. This code
/// corrects for this problem by computing the number of "fake" predecessors and decreasing them from
/// the total number of "predecessors" returned by `rustc`.  The option is to recompute "predecessors"
/// from scratch but we may miss some cases there. (see also [`is_join_point`])
///
/// [`is_join_point`]: crate::mir::Body::is_join_point
fn mk_fake_predecessors(
    basic_blocks: &IndexVec<BasicBlock, BasicBlockData>,
) -> IndexVec<BasicBlock, usize> {
    let mut res: IndexVec<BasicBlock, usize> = basic_blocks.iter().map(|_| 0).collect();

    for bb in basic_blocks {
        if let Some(terminator) = &bb.terminator {
            if let TerminatorKind::FalseEdge { imaginary_target, .. } = terminator.kind {
                res[imaginary_target] += 1;
            }
        }
    }
    res
}

impl fmt::Debug for Body<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (bb, data) in self.basic_blocks.iter_enumerated() {
            writeln!(
                f,
                "{bb:?}: {{{}",
                data.statements
                    .iter()
                    .filter(|stmt| !matches!(stmt.kind, StatementKind::Nop))
                    .format_with("", |stmt, f| f(&format_args!("\n    {stmt:?};")))
            )?;
            if let Some(terminator) = &data.terminator {
                writeln!(f, "    {terminator:?}")?;
            }
            writeln!(f, "}}\n")?;
        }
        Ok(())
    }
}

impl fmt::Debug for Statement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            StatementKind::Assign(place, rvalue) => write!(f, "{place:?} = {rvalue:?}"),
            StatementKind::Nop => write!(f, "nop"),
            StatementKind::PlaceMention(place) => {
                write!(f, "PlaceMention({place:?})")
            }
            StatementKind::SetDiscriminant(place, variant_idx) => {
                write!(f, "discriminant({place:?}) = {variant_idx:?}")
            }
            StatementKind::FakeRead(box (cause, place)) => {
                write!(f, "FakeRead({cause:?}, {place:?})")
            }
            StatementKind::AscribeUserType(place, variance) => {
                write!(f, "AscribeUserType({place:?}, {variance:?})")
            }
            StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op)) => {
                write!(f, "Assume({op:?})")
            }
        }
    }
}

impl fmt::Debug for CallKind<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CallKind::FnDef { resolved_id, resolved_args, .. } => {
                let fname = rustc_middle::ty::tls::with(|tcx| {
                    let path = tcx.def_path(*resolved_id);
                    path.data.iter().join("::")
                });
                write!(f, "call {fname}")?;
                if !resolved_args.lowered.is_empty() {
                    write!(f, "<{:?}>", resolved_args.lowered.iter().format(", "))?;
                }
                Ok(())
            }
            CallKind::FnPtr { fn_sig, operand } => write!(f, "FnPtr[{operand:?}]({fn_sig:?})"),
        }
    }
}

impl fmt::Debug for Terminator<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            TerminatorKind::Return => write!(f, "return"),
            TerminatorKind::Unreachable => write!(f, "unreachable"),
            TerminatorKind::Call { kind, args, destination, target, unwind, .. } => {
                write!(
                    f,
                    "{destination:?} = call {kind:?}({args:?}) -> [return: {target}, unwind: {unwind:?}]",
                    args = args.iter().format(", "),
                    target = opt_bb_to_str(*target),
                )
            }
            TerminatorKind::SwitchInt { discr, targets } => {
                write!(
                    f,
                    "switchInt({discr:?}) -> [{}, otherwise: {:?}]",
                    targets
                        .iter()
                        .format_with(", ", |(val, bb), f| f(&format_args!("{val:?}: {bb:?}"))),
                    targets.otherwise()
                )
            }
            TerminatorKind::Goto { target } => {
                write!(f, "goto -> {target:?}")
            }
            TerminatorKind::Drop { place, target, unwind } => {
                write!(f, "drop({place:?}) -> [{target:?}, unwind: {unwind:?}]",)
            }
            TerminatorKind::Assert { cond, target, expected, msg } => {
                write!(
                    f,
                    "assert({cond:?} is expected to be {expected:?}, \"{msg:?}\") -> {target:?}"
                )
            }
            TerminatorKind::FalseEdge { real_target, imaginary_target } => {
                write!(f, "falseEdge -> [real: {real_target:?}, imaginary: {imaginary_target:?}]")
            }
            TerminatorKind::FalseUnwind { real_target, unwind } => {
                write!(f, "falseUnwind -> [real: {real_target:?}, cleanup: {unwind:?}]")
            }
            TerminatorKind::UnwindResume => write!(f, "resume"),
            TerminatorKind::CoroutineDrop => write!(f, "generator_drop"),
            TerminatorKind::Yield { value, resume, drop, resume_arg } => {
                write!(
                    f,
                    "{resume_arg:?} = yield({value:?}) -> [resume: {resume:?}, drop: {drop:?}]"
                )
            }
        }
    }
}

impl fmt::Debug for Place {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.as_ref())
    }
}

impl fmt::Debug for PlaceRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut p = format!("{:?}", self.local);
        let mut need_parens = false;
        for elem in self.projection {
            match elem {
                PlaceElem::Field(f) => {
                    if need_parens {
                        p = format!("({p}).{}", u32::from(*f));
                        need_parens = false;
                    } else {
                        p = format!("{p}.{}", u32::from(*f));
                    }
                }
                PlaceElem::Deref => {
                    p = format!("*{p}");
                    need_parens = true;
                }
                PlaceElem::Downcast(variant_name, variant_idx) => {
                    if let Some(variant_name) = variant_name {
                        p = format!("{p} as {variant_name}");
                    } else {
                        p = format!("{p} as {variant_idx:?}");
                    }
                    need_parens = true;
                }
                PlaceElem::Index(v) => {
                    p = format!("{p}[{v:?}]");
                    need_parens = false;
                }
                PlaceElem::ConstantIndex { offset, min_length, .. } => {
                    p = format!("{p}[{offset:?} of {min_length:?}]");
                    need_parens = false;
                }
            }
        }
        write!(f, "{p}")
    }
}

impl fmt::Debug for Rvalue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Rvalue::Use(op) => write!(f, "{op:?}"),
            Rvalue::Ref(r, BorrowKind::Mut { .. }, place) => {
                write!(f, "&{} mut {place:?}", region_to_string(*r))
            }
            Rvalue::Ref(r, BorrowKind::Shared, place) => {
                write!(f, "&{} {place:?}", region_to_string(*r))
            }
            Rvalue::Ref(r, BorrowKind::Fake(FakeBorrowKind::Shallow), place) => {
                write!(f, "&{} fake shallow {place:?}", region_to_string(*r))
            }
            Rvalue::Ref(r, BorrowKind::Fake(FakeBorrowKind::Deep), place) => {
                write!(f, "&{} fake deep {place:?}", region_to_string(*r))
            }
            Rvalue::RawPtr(mutbl, place) => write!(f, "&raw {} {place:?}", mutbl.ptr_str()),
            Rvalue::Discriminant(place) => write!(f, "discriminant({place:?})"),
            Rvalue::BinaryOp(bin_op, op1, op2) => write!(f, "{bin_op:?}({op1:?}, {op2:?})"),
            Rvalue::NullaryOp(null_op, ty) => write!(f, "{null_op:?}({ty:?})"),
            Rvalue::UnaryOp(un_op, op) => write!(f, "{un_op:?}({op:?})"),
            Rvalue::Aggregate(AggregateKind::Adt(def_id, variant_idx, args, _, _), operands) => {
                let (fname, variant_name) = rustc_middle::ty::tls::with(|tcx| {
                    let variant_name = tcx.adt_def(*def_id).variant(*variant_idx).name;
                    let fname = tcx.def_path(*def_id).data.iter().join("::");
                    (fname, variant_name)
                });
                write!(f, "{fname}::{variant_name}")?;
                if !args.is_empty() {
                    write!(f, "<{:?}>", args.iter().format(", "),)?;
                }
                if !operands.is_empty() {
                    write!(f, "({:?})", operands.iter().format(", "))?;
                }
                Ok(())
            }
            Rvalue::Aggregate(AggregateKind::Closure(def_id, args), operands) => {
                write!(
                    f,
                    "closure({}, {args:?}, {:?})",
                    def_id_to_string(*def_id),
                    operands.iter().format(", ")
                )
            }
            Rvalue::Aggregate(AggregateKind::Coroutine(def_id, args), operands) => {
                write!(
                    f,
                    "generator({}, {args:?}, {:?})",
                    def_id_to_string(*def_id),
                    operands.iter().format(", ")
                )
            }
            Rvalue::Aggregate(AggregateKind::Array(_), args) => {
                write!(f, "[{:?}]", args.iter().format(", "))
            }
            Rvalue::Aggregate(AggregateKind::Tuple, args) => {
                write!(f, "({:?})", args.iter().format(", "))
            }
            Rvalue::Len(place) => write!(f, "Len({place:?})"),
            Rvalue::Cast(kind, op, ty) => write!(f, "{op:?} as {ty:?} [{kind:?}]"),
            Rvalue::Repeat(op, c) => write!(f, "[{op:?}; {c:?}]"),
            Rvalue::ShallowInitBox(op, ty) => write!(f, "ShallowInitBox({op:?}, {ty:?})"),
        }
    }
}

impl fmt::Debug for PointerCast {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PointerCast::MutToConstPointer => write!(f, "MutToConstPointer"),
            PointerCast::Unsize => write!(f, "Unsize"),
            PointerCast::ClosureFnPointer => write!(f, "ClosureFnPointer"),
            PointerCast::ReifyFnPointer => write!(f, "ReifyFnPointer"),
        }
    }
}

impl fmt::Debug for CastKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CastKind::IntToInt => write!(f, "IntToInt"),
            CastKind::FloatToInt => write!(f, "FloatToInt"),
            CastKind::IntToFloat => write!(f, "IntToFloat"),
            CastKind::PtrToPtr => write!(f, "PtrToPtr"),
            CastKind::PointerCoercion(c) => write!(f, "Pointer({c:?})"),
            CastKind::PointerExposeProvenance => write!(f, "PointerExposeProvenance"),
            CastKind::PointerWithExposedProvenance => write!(f, "PointerWithExposedProvenance"),
        }
    }
}

impl fmt::Debug for Operand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Copy(place) => write!(f, "copy {place:?}"),
            Self::Move(place) => write!(f, "move {place:?}"),
            Self::Constant(c) => write!(f, "{c:?}"),
        }
    }
}

impl fmt::Debug for Constant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Constant::Int(n, int_ty) => write!(f, "{n}{}", int_ty.name_str()),
            Constant::Uint(n, uint_ty) => write!(f, "{n}{}", uint_ty.name_str()),
            Constant::Float(bits, float_ty) => write!(f, "{bits}{}", float_ty.name_str()),
            Constant::Bool(b) => write!(f, "{b}"),
            Constant::Unit => write!(f, "()"),
            Constant::Str(s) => write!(f, "\"{s:?}\""),
            Constant::Char(c) => write!(f, "\'{c}\'"),
            Constant::Opaque(ty) => write!(f, "<opaque {:?}>", ty),
            Constant::Param(p, _) => write!(f, "{:?}", p),
        }
    }
}

fn opt_bb_to_str(bb: Option<BasicBlock>) -> String {
    match bb {
        Some(bb) => format!("{bb:?}"),
        None => "None".to_string(),
    }
}