rustc_public/unstable/convert/stable/
mir.rs

1//! Conversion of internal Rust compiler `mir` items to stable ones.
2
3use rustc_middle::mir::mono::MonoItem;
4use rustc_middle::{bug, mir};
5use rustc_public_bridge::context::CompilerCtxt;
6use rustc_public_bridge::{Tables, bridge};
7
8use crate::compiler_interface::BridgeTys;
9use crate::mir::alloc::GlobalAlloc;
10use crate::mir::{ConstOperand, Statement, UserTypeProjection, VarDebugInfoFragment};
11use crate::ty::{Allocation, ConstantKind, MirConst};
12use crate::unstable::Stable;
13use crate::{Error, alloc, opaque};
14
15impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
16    type T = crate::mir::Body;
17
18    fn stable<'cx>(
19        &self,
20        tables: &mut Tables<'cx, BridgeTys>,
21        cx: &CompilerCtxt<'cx, BridgeTys>,
22    ) -> Self::T {
23        crate::mir::Body::new(
24            self.basic_blocks
25                .iter()
26                .map(|block| crate::mir::BasicBlock {
27                    terminator: block.terminator().stable(tables, cx),
28                    statements: block
29                        .statements
30                        .iter()
31                        .map(|statement| statement.stable(tables, cx))
32                        .collect(),
33                })
34                .collect(),
35            self.local_decls
36                .iter()
37                .map(|decl| crate::mir::LocalDecl {
38                    ty: decl.ty.stable(tables, cx),
39                    span: decl.source_info.span.stable(tables, cx),
40                    mutability: decl.mutability.stable(tables, cx),
41                })
42                .collect(),
43            self.arg_count,
44            self.var_debug_info.iter().map(|info| info.stable(tables, cx)).collect(),
45            self.spread_arg.stable(tables, cx),
46            self.span.stable(tables, cx),
47        )
48    }
49}
50
51impl<'tcx> Stable<'tcx> for mir::VarDebugInfo<'tcx> {
52    type T = crate::mir::VarDebugInfo;
53    fn stable<'cx>(
54        &self,
55        tables: &mut Tables<'cx, BridgeTys>,
56        cx: &CompilerCtxt<'cx, BridgeTys>,
57    ) -> Self::T {
58        crate::mir::VarDebugInfo {
59            name: self.name.to_string(),
60            source_info: self.source_info.stable(tables, cx),
61            composite: self.composite.as_ref().map(|composite| composite.stable(tables, cx)),
62            value: self.value.stable(tables, cx),
63            argument_index: self.argument_index,
64        }
65    }
66}
67
68impl<'tcx> Stable<'tcx> for mir::Statement<'tcx> {
69    type T = crate::mir::Statement;
70    fn stable<'cx>(
71        &self,
72        tables: &mut Tables<'cx, BridgeTys>,
73        cx: &CompilerCtxt<'cx, BridgeTys>,
74    ) -> Self::T {
75        Statement {
76            kind: self.kind.stable(tables, cx),
77            span: self.source_info.span.stable(tables, cx),
78        }
79    }
80}
81
82impl<'tcx> Stable<'tcx> for mir::SourceInfo {
83    type T = crate::mir::SourceInfo;
84    fn stable<'cx>(
85        &self,
86        tables: &mut Tables<'cx, BridgeTys>,
87        cx: &CompilerCtxt<'cx, BridgeTys>,
88    ) -> Self::T {
89        crate::mir::SourceInfo { span: self.span.stable(tables, cx), scope: self.scope.into() }
90    }
91}
92
93impl<'tcx> Stable<'tcx> for mir::VarDebugInfoFragment<'tcx> {
94    type T = crate::mir::VarDebugInfoFragment;
95    fn stable<'cx>(
96        &self,
97        tables: &mut Tables<'cx, BridgeTys>,
98        cx: &CompilerCtxt<'cx, BridgeTys>,
99    ) -> Self::T {
100        VarDebugInfoFragment {
101            ty: self.ty.stable(tables, cx),
102            projection: self.projection.iter().map(|e| e.stable(tables, cx)).collect(),
103        }
104    }
105}
106
107impl<'tcx> Stable<'tcx> for mir::VarDebugInfoContents<'tcx> {
108    type T = crate::mir::VarDebugInfoContents;
109    fn stable<'cx>(
110        &self,
111        tables: &mut Tables<'cx, BridgeTys>,
112        cx: &CompilerCtxt<'cx, BridgeTys>,
113    ) -> Self::T {
114        match self {
115            mir::VarDebugInfoContents::Place(place) => {
116                crate::mir::VarDebugInfoContents::Place(place.stable(tables, cx))
117            }
118            mir::VarDebugInfoContents::Const(const_operand) => {
119                let op = ConstOperand {
120                    span: const_operand.span.stable(tables, cx),
121                    user_ty: const_operand.user_ty.map(|index| index.as_usize()),
122                    const_: const_operand.const_.stable(tables, cx),
123                };
124                crate::mir::VarDebugInfoContents::Const(op)
125            }
126        }
127    }
128}
129
130impl<'tcx> Stable<'tcx> for mir::StatementKind<'tcx> {
131    type T = crate::mir::StatementKind;
132    fn stable<'cx>(
133        &self,
134        tables: &mut Tables<'cx, BridgeTys>,
135        cx: &CompilerCtxt<'cx, BridgeTys>,
136    ) -> Self::T {
137        match self {
138            mir::StatementKind::Assign(assign) => crate::mir::StatementKind::Assign(
139                assign.0.stable(tables, cx),
140                assign.1.stable(tables, cx),
141            ),
142            mir::StatementKind::FakeRead(fake_read_place) => crate::mir::StatementKind::FakeRead(
143                fake_read_place.0.stable(tables, cx),
144                fake_read_place.1.stable(tables, cx),
145            ),
146            mir::StatementKind::SetDiscriminant { place, variant_index } => {
147                crate::mir::StatementKind::SetDiscriminant {
148                    place: place.as_ref().stable(tables, cx),
149                    variant_index: variant_index.stable(tables, cx),
150                }
151            }
152
153            mir::StatementKind::StorageLive(place) => {
154                crate::mir::StatementKind::StorageLive(place.stable(tables, cx))
155            }
156
157            mir::StatementKind::StorageDead(place) => {
158                crate::mir::StatementKind::StorageDead(place.stable(tables, cx))
159            }
160            mir::StatementKind::Retag(retag, place) => {
161                crate::mir::StatementKind::Retag(retag.stable(tables, cx), place.stable(tables, cx))
162            }
163            mir::StatementKind::PlaceMention(place) => {
164                crate::mir::StatementKind::PlaceMention(place.stable(tables, cx))
165            }
166            mir::StatementKind::AscribeUserType(place_projection, variance) => {
167                crate::mir::StatementKind::AscribeUserType {
168                    place: place_projection.as_ref().0.stable(tables, cx),
169                    projections: place_projection.as_ref().1.stable(tables, cx),
170                    variance: variance.stable(tables, cx),
171                }
172            }
173            mir::StatementKind::Coverage(coverage) => {
174                crate::mir::StatementKind::Coverage(opaque(coverage))
175            }
176            mir::StatementKind::Intrinsic(intrinstic) => {
177                crate::mir::StatementKind::Intrinsic(intrinstic.stable(tables, cx))
178            }
179            mir::StatementKind::ConstEvalCounter => crate::mir::StatementKind::ConstEvalCounter,
180            // BackwardIncompatibleDropHint has no semantics, so it is translated to Nop.
181            mir::StatementKind::BackwardIncompatibleDropHint { .. } => {
182                crate::mir::StatementKind::Nop
183            }
184            mir::StatementKind::Nop => crate::mir::StatementKind::Nop,
185        }
186    }
187}
188
189impl<'tcx> Stable<'tcx> for mir::Rvalue<'tcx> {
190    type T = crate::mir::Rvalue;
191    fn stable<'cx>(
192        &self,
193        tables: &mut Tables<'cx, BridgeTys>,
194        cx: &CompilerCtxt<'cx, BridgeTys>,
195    ) -> Self::T {
196        use rustc_middle::mir::Rvalue::*;
197        match self {
198            Use(op) => crate::mir::Rvalue::Use(op.stable(tables, cx)),
199            Repeat(op, len) => {
200                let len = len.stable(tables, cx);
201                crate::mir::Rvalue::Repeat(op.stable(tables, cx), len)
202            }
203            Ref(region, kind, place) => crate::mir::Rvalue::Ref(
204                region.stable(tables, cx),
205                kind.stable(tables, cx),
206                place.stable(tables, cx),
207            ),
208            ThreadLocalRef(def_id) => {
209                crate::mir::Rvalue::ThreadLocalRef(tables.crate_item(*def_id))
210            }
211            RawPtr(mutability, place) => crate::mir::Rvalue::AddressOf(
212                mutability.stable(tables, cx),
213                place.stable(tables, cx),
214            ),
215            Cast(cast_kind, op, ty) => crate::mir::Rvalue::Cast(
216                cast_kind.stable(tables, cx),
217                op.stable(tables, cx),
218                ty.stable(tables, cx),
219            ),
220            BinaryOp(bin_op, ops) => {
221                if let Some(bin_op) = bin_op.overflowing_to_wrapping() {
222                    crate::mir::Rvalue::CheckedBinaryOp(
223                        bin_op.stable(tables, cx),
224                        ops.0.stable(tables, cx),
225                        ops.1.stable(tables, cx),
226                    )
227                } else {
228                    crate::mir::Rvalue::BinaryOp(
229                        bin_op.stable(tables, cx),
230                        ops.0.stable(tables, cx),
231                        ops.1.stable(tables, cx),
232                    )
233                }
234            }
235            NullaryOp(null_op) => crate::mir::Rvalue::NullaryOp(null_op.stable(tables, cx)),
236            UnaryOp(un_op, op) => {
237                crate::mir::Rvalue::UnaryOp(un_op.stable(tables, cx), op.stable(tables, cx))
238            }
239            Discriminant(place) => crate::mir::Rvalue::Discriminant(place.stable(tables, cx)),
240            Aggregate(agg_kind, operands) => {
241                let operands = operands.iter().map(|op| op.stable(tables, cx)).collect();
242                crate::mir::Rvalue::Aggregate(agg_kind.stable(tables, cx), operands)
243            }
244            ShallowInitBox(op, ty) => {
245                crate::mir::Rvalue::ShallowInitBox(op.stable(tables, cx), ty.stable(tables, cx))
246            }
247            CopyForDeref(place) => crate::mir::Rvalue::CopyForDeref(place.stable(tables, cx)),
248            WrapUnsafeBinder(..) => todo!("FIXME(unsafe_binders):"),
249        }
250    }
251}
252
253impl<'tcx> Stable<'tcx> for mir::Mutability {
254    type T = crate::mir::Mutability;
255    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
256        use rustc_hir::Mutability::*;
257        match *self {
258            Not => crate::mir::Mutability::Not,
259            Mut => crate::mir::Mutability::Mut,
260        }
261    }
262}
263
264impl<'tcx> Stable<'tcx> for mir::RawPtrKind {
265    type T = crate::mir::RawPtrKind;
266    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
267        use mir::RawPtrKind::*;
268        match *self {
269            Const => crate::mir::RawPtrKind::Const,
270            Mut => crate::mir::RawPtrKind::Mut,
271            FakeForPtrMetadata => crate::mir::RawPtrKind::FakeForPtrMetadata,
272        }
273    }
274}
275
276impl<'tcx> Stable<'tcx> for mir::BorrowKind {
277    type T = crate::mir::BorrowKind;
278    fn stable<'cx>(
279        &self,
280        tables: &mut Tables<'cx, BridgeTys>,
281        cx: &CompilerCtxt<'cx, BridgeTys>,
282    ) -> Self::T {
283        use rustc_middle::mir::BorrowKind::*;
284        match *self {
285            Shared => crate::mir::BorrowKind::Shared,
286            Fake(kind) => crate::mir::BorrowKind::Fake(kind.stable(tables, cx)),
287            Mut { kind } => crate::mir::BorrowKind::Mut { kind: kind.stable(tables, cx) },
288        }
289    }
290}
291
292impl<'tcx> Stable<'tcx> for mir::MutBorrowKind {
293    type T = crate::mir::MutBorrowKind;
294    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
295        use rustc_middle::mir::MutBorrowKind::*;
296        match *self {
297            Default => crate::mir::MutBorrowKind::Default,
298            TwoPhaseBorrow => crate::mir::MutBorrowKind::TwoPhaseBorrow,
299            ClosureCapture => crate::mir::MutBorrowKind::ClosureCapture,
300        }
301    }
302}
303
304impl<'tcx> Stable<'tcx> for mir::FakeBorrowKind {
305    type T = crate::mir::FakeBorrowKind;
306    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
307        use rustc_middle::mir::FakeBorrowKind::*;
308        match *self {
309            Deep => crate::mir::FakeBorrowKind::Deep,
310            Shallow => crate::mir::FakeBorrowKind::Shallow,
311        }
312    }
313}
314
315impl<'tcx> Stable<'tcx> for mir::NullOp {
316    type T = crate::mir::NullOp;
317    fn stable<'cx>(
318        &self,
319        _: &mut Tables<'cx, BridgeTys>,
320        _: &CompilerCtxt<'cx, BridgeTys>,
321    ) -> Self::T {
322        use rustc_middle::mir::NullOp::*;
323        use rustc_middle::mir::RuntimeChecks::*;
324        match self {
325            RuntimeChecks(op) => crate::mir::NullOp::RuntimeChecks(match op {
326                UbChecks => crate::mir::RuntimeChecks::UbChecks,
327                ContractChecks => crate::mir::RuntimeChecks::ContractChecks,
328                OverflowChecks => crate::mir::RuntimeChecks::OverflowChecks,
329            }),
330        }
331    }
332}
333
334impl<'tcx> Stable<'tcx> for mir::CastKind {
335    type T = crate::mir::CastKind;
336    fn stable<'cx>(
337        &self,
338        tables: &mut Tables<'cx, BridgeTys>,
339        cx: &CompilerCtxt<'cx, BridgeTys>,
340    ) -> Self::T {
341        use rustc_middle::mir::CastKind::*;
342        match self {
343            PointerExposeProvenance => crate::mir::CastKind::PointerExposeAddress,
344            PointerWithExposedProvenance => crate::mir::CastKind::PointerWithExposedProvenance,
345            PointerCoercion(c, _) => crate::mir::CastKind::PointerCoercion(c.stable(tables, cx)),
346            IntToInt => crate::mir::CastKind::IntToInt,
347            FloatToInt => crate::mir::CastKind::FloatToInt,
348            FloatToFloat => crate::mir::CastKind::FloatToFloat,
349            IntToFloat => crate::mir::CastKind::IntToFloat,
350            PtrToPtr => crate::mir::CastKind::PtrToPtr,
351            FnPtrToPtr => crate::mir::CastKind::FnPtrToPtr,
352            Transmute => crate::mir::CastKind::Transmute,
353            Subtype => crate::mir::CastKind::Subtype,
354        }
355    }
356}
357
358impl<'tcx> Stable<'tcx> for mir::FakeReadCause {
359    type T = crate::mir::FakeReadCause;
360    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
361        use rustc_middle::mir::FakeReadCause::*;
362        match self {
363            ForMatchGuard => crate::mir::FakeReadCause::ForMatchGuard,
364            ForMatchedPlace(local_def_id) => {
365                crate::mir::FakeReadCause::ForMatchedPlace(opaque(local_def_id))
366            }
367            ForGuardBinding => crate::mir::FakeReadCause::ForGuardBinding,
368            ForLet(local_def_id) => crate::mir::FakeReadCause::ForLet(opaque(local_def_id)),
369            ForIndex => crate::mir::FakeReadCause::ForIndex,
370        }
371    }
372}
373
374impl<'tcx> Stable<'tcx> for mir::Operand<'tcx> {
375    type T = crate::mir::Operand;
376    fn stable<'cx>(
377        &self,
378        tables: &mut Tables<'cx, BridgeTys>,
379        cx: &CompilerCtxt<'cx, BridgeTys>,
380    ) -> Self::T {
381        use rustc_middle::mir::Operand::*;
382        match self {
383            Copy(place) => crate::mir::Operand::Copy(place.stable(tables, cx)),
384            Move(place) => crate::mir::Operand::Move(place.stable(tables, cx)),
385            Constant(c) => crate::mir::Operand::Constant(c.stable(tables, cx)),
386        }
387    }
388}
389
390impl<'tcx> Stable<'tcx> for mir::ConstOperand<'tcx> {
391    type T = crate::mir::ConstOperand;
392
393    fn stable<'cx>(
394        &self,
395        tables: &mut Tables<'cx, BridgeTys>,
396        cx: &CompilerCtxt<'cx, BridgeTys>,
397    ) -> Self::T {
398        crate::mir::ConstOperand {
399            span: self.span.stable(tables, cx),
400            user_ty: self.user_ty.map(|u| u.as_usize()).or(None),
401            const_: self.const_.stable(tables, cx),
402        }
403    }
404}
405
406impl<'tcx> Stable<'tcx> for mir::Place<'tcx> {
407    type T = crate::mir::Place;
408    fn stable<'cx>(
409        &self,
410        tables: &mut Tables<'cx, BridgeTys>,
411        cx: &CompilerCtxt<'cx, BridgeTys>,
412    ) -> Self::T {
413        crate::mir::Place {
414            local: self.local.as_usize(),
415            projection: self.projection.iter().map(|e| e.stable(tables, cx)).collect(),
416        }
417    }
418}
419
420impl<'tcx> Stable<'tcx> for mir::PlaceElem<'tcx> {
421    type T = crate::mir::ProjectionElem;
422    fn stable<'cx>(
423        &self,
424        tables: &mut Tables<'cx, BridgeTys>,
425        cx: &CompilerCtxt<'cx, BridgeTys>,
426    ) -> Self::T {
427        use rustc_middle::mir::ProjectionElem::*;
428        match self {
429            Deref => crate::mir::ProjectionElem::Deref,
430            Field(idx, ty) => {
431                crate::mir::ProjectionElem::Field(idx.stable(tables, cx), ty.stable(tables, cx))
432            }
433            Index(local) => crate::mir::ProjectionElem::Index(local.stable(tables, cx)),
434            ConstantIndex { offset, min_length, from_end } => {
435                crate::mir::ProjectionElem::ConstantIndex {
436                    offset: *offset,
437                    min_length: *min_length,
438                    from_end: *from_end,
439                }
440            }
441            Subslice { from, to, from_end } => {
442                crate::mir::ProjectionElem::Subslice { from: *from, to: *to, from_end: *from_end }
443            }
444            // MIR includes an `Option<Symbol>` argument for `Downcast` that is the name of the
445            // variant, used for printing MIR. However this information should also be accessible
446            // via a lookup using the `VariantIdx`. The `Option<Symbol>` argument is therefore
447            // dropped when converting to Stable MIR. A brief justification for this decision can be
448            // found at https://github.com/rust-lang/rust/pull/117517#issuecomment-1811683486
449            Downcast(_, idx) => crate::mir::ProjectionElem::Downcast(idx.stable(tables, cx)),
450            OpaqueCast(ty) => crate::mir::ProjectionElem::OpaqueCast(ty.stable(tables, cx)),
451            UnwrapUnsafeBinder(..) => todo!("FIXME(unsafe_binders):"),
452        }
453    }
454}
455
456impl<'tcx> Stable<'tcx> for mir::UserTypeProjection {
457    type T = crate::mir::UserTypeProjection;
458
459    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
460        UserTypeProjection { base: self.base.as_usize(), projection: opaque(&self.projs) }
461    }
462}
463
464impl<'tcx> Stable<'tcx> for mir::Local {
465    type T = crate::mir::Local;
466    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
467        self.as_usize()
468    }
469}
470
471impl<'tcx> Stable<'tcx> for mir::RetagKind {
472    type T = crate::mir::RetagKind;
473    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
474        use rustc_middle::mir::RetagKind;
475        match self {
476            RetagKind::FnEntry => crate::mir::RetagKind::FnEntry,
477            RetagKind::TwoPhase => crate::mir::RetagKind::TwoPhase,
478            RetagKind::Raw => crate::mir::RetagKind::Raw,
479            RetagKind::Default => crate::mir::RetagKind::Default,
480        }
481    }
482}
483
484impl<'tcx> Stable<'tcx> for mir::UnwindAction {
485    type T = crate::mir::UnwindAction;
486    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
487        use rustc_middle::mir::UnwindAction;
488        match self {
489            UnwindAction::Continue => crate::mir::UnwindAction::Continue,
490            UnwindAction::Unreachable => crate::mir::UnwindAction::Unreachable,
491            UnwindAction::Terminate(_) => crate::mir::UnwindAction::Terminate,
492            UnwindAction::Cleanup(bb) => crate::mir::UnwindAction::Cleanup(bb.as_usize()),
493        }
494    }
495}
496
497impl<'tcx> Stable<'tcx> for mir::NonDivergingIntrinsic<'tcx> {
498    type T = crate::mir::NonDivergingIntrinsic;
499
500    fn stable<'cx>(
501        &self,
502        tables: &mut Tables<'cx, BridgeTys>,
503        cx: &CompilerCtxt<'cx, BridgeTys>,
504    ) -> Self::T {
505        use rustc_middle::mir::NonDivergingIntrinsic;
506
507        use crate::mir::CopyNonOverlapping;
508        match self {
509            NonDivergingIntrinsic::Assume(op) => {
510                crate::mir::NonDivergingIntrinsic::Assume(op.stable(tables, cx))
511            }
512            NonDivergingIntrinsic::CopyNonOverlapping(copy_non_overlapping) => {
513                crate::mir::NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
514                    src: copy_non_overlapping.src.stable(tables, cx),
515                    dst: copy_non_overlapping.dst.stable(tables, cx),
516                    count: copy_non_overlapping.count.stable(tables, cx),
517                })
518            }
519        }
520    }
521}
522
523impl<'tcx> Stable<'tcx> for mir::AssertMessage<'tcx> {
524    type T = crate::mir::AssertMessage;
525    fn stable<'cx>(
526        &self,
527        tables: &mut Tables<'cx, BridgeTys>,
528        cx: &CompilerCtxt<'cx, BridgeTys>,
529    ) -> Self::T {
530        use rustc_middle::mir::AssertKind;
531        match self {
532            AssertKind::BoundsCheck { len, index } => crate::mir::AssertMessage::BoundsCheck {
533                len: len.stable(tables, cx),
534                index: index.stable(tables, cx),
535            },
536            AssertKind::Overflow(bin_op, op1, op2) => crate::mir::AssertMessage::Overflow(
537                bin_op.stable(tables, cx),
538                op1.stable(tables, cx),
539                op2.stable(tables, cx),
540            ),
541            AssertKind::OverflowNeg(op) => {
542                crate::mir::AssertMessage::OverflowNeg(op.stable(tables, cx))
543            }
544            AssertKind::DivisionByZero(op) => {
545                crate::mir::AssertMessage::DivisionByZero(op.stable(tables, cx))
546            }
547            AssertKind::RemainderByZero(op) => {
548                crate::mir::AssertMessage::RemainderByZero(op.stable(tables, cx))
549            }
550            AssertKind::ResumedAfterReturn(coroutine) => {
551                crate::mir::AssertMessage::ResumedAfterReturn(coroutine.stable(tables, cx))
552            }
553            AssertKind::ResumedAfterPanic(coroutine) => {
554                crate::mir::AssertMessage::ResumedAfterPanic(coroutine.stable(tables, cx))
555            }
556            AssertKind::ResumedAfterDrop(coroutine) => {
557                crate::mir::AssertMessage::ResumedAfterDrop(coroutine.stable(tables, cx))
558            }
559            AssertKind::MisalignedPointerDereference { required, found } => {
560                crate::mir::AssertMessage::MisalignedPointerDereference {
561                    required: required.stable(tables, cx),
562                    found: found.stable(tables, cx),
563                }
564            }
565            AssertKind::NullPointerDereference => crate::mir::AssertMessage::NullPointerDereference,
566            AssertKind::InvalidEnumConstruction(source) => {
567                crate::mir::AssertMessage::InvalidEnumConstruction(source.stable(tables, cx))
568            }
569        }
570    }
571}
572
573impl<'tcx> Stable<'tcx> for mir::BinOp {
574    type T = crate::mir::BinOp;
575    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
576        use rustc_middle::mir::BinOp;
577        match self {
578            BinOp::Add => crate::mir::BinOp::Add,
579            BinOp::AddUnchecked => crate::mir::BinOp::AddUnchecked,
580            BinOp::AddWithOverflow => bug!("AddWithOverflow should have been translated already"),
581            BinOp::Sub => crate::mir::BinOp::Sub,
582            BinOp::SubUnchecked => crate::mir::BinOp::SubUnchecked,
583            BinOp::SubWithOverflow => bug!("AddWithOverflow should have been translated already"),
584            BinOp::Mul => crate::mir::BinOp::Mul,
585            BinOp::MulUnchecked => crate::mir::BinOp::MulUnchecked,
586            BinOp::MulWithOverflow => bug!("AddWithOverflow should have been translated already"),
587            BinOp::Div => crate::mir::BinOp::Div,
588            BinOp::Rem => crate::mir::BinOp::Rem,
589            BinOp::BitXor => crate::mir::BinOp::BitXor,
590            BinOp::BitAnd => crate::mir::BinOp::BitAnd,
591            BinOp::BitOr => crate::mir::BinOp::BitOr,
592            BinOp::Shl => crate::mir::BinOp::Shl,
593            BinOp::ShlUnchecked => crate::mir::BinOp::ShlUnchecked,
594            BinOp::Shr => crate::mir::BinOp::Shr,
595            BinOp::ShrUnchecked => crate::mir::BinOp::ShrUnchecked,
596            BinOp::Eq => crate::mir::BinOp::Eq,
597            BinOp::Lt => crate::mir::BinOp::Lt,
598            BinOp::Le => crate::mir::BinOp::Le,
599            BinOp::Ne => crate::mir::BinOp::Ne,
600            BinOp::Ge => crate::mir::BinOp::Ge,
601            BinOp::Gt => crate::mir::BinOp::Gt,
602            BinOp::Cmp => crate::mir::BinOp::Cmp,
603            BinOp::Offset => crate::mir::BinOp::Offset,
604        }
605    }
606}
607
608impl<'tcx> Stable<'tcx> for mir::UnOp {
609    type T = crate::mir::UnOp;
610    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
611        use rustc_middle::mir::UnOp;
612        match self {
613            UnOp::Not => crate::mir::UnOp::Not,
614            UnOp::Neg => crate::mir::UnOp::Neg,
615            UnOp::PtrMetadata => crate::mir::UnOp::PtrMetadata,
616        }
617    }
618}
619
620impl<'tcx> Stable<'tcx> for mir::AggregateKind<'tcx> {
621    type T = crate::mir::AggregateKind;
622    fn stable<'cx>(
623        &self,
624        tables: &mut Tables<'cx, BridgeTys>,
625        cx: &CompilerCtxt<'cx, BridgeTys>,
626    ) -> Self::T {
627        match self {
628            mir::AggregateKind::Array(ty) => {
629                crate::mir::AggregateKind::Array(ty.stable(tables, cx))
630            }
631            mir::AggregateKind::Tuple => crate::mir::AggregateKind::Tuple,
632            mir::AggregateKind::Adt(def_id, var_idx, generic_arg, user_ty_index, field_idx) => {
633                crate::mir::AggregateKind::Adt(
634                    tables.adt_def(*def_id),
635                    var_idx.stable(tables, cx),
636                    generic_arg.stable(tables, cx),
637                    user_ty_index.map(|idx| idx.index()),
638                    field_idx.map(|idx| idx.index()),
639                )
640            }
641            mir::AggregateKind::Closure(def_id, generic_arg) => crate::mir::AggregateKind::Closure(
642                tables.closure_def(*def_id),
643                generic_arg.stable(tables, cx),
644            ),
645            mir::AggregateKind::Coroutine(def_id, generic_arg) => {
646                crate::mir::AggregateKind::Coroutine(
647                    tables.coroutine_def(*def_id),
648                    generic_arg.stable(tables, cx),
649                )
650            }
651            mir::AggregateKind::CoroutineClosure(def_id, generic_args) => {
652                crate::mir::AggregateKind::CoroutineClosure(
653                    tables.coroutine_closure_def(*def_id),
654                    generic_args.stable(tables, cx),
655                )
656            }
657            mir::AggregateKind::RawPtr(ty, mutability) => crate::mir::AggregateKind::RawPtr(
658                ty.stable(tables, cx),
659                mutability.stable(tables, cx),
660            ),
661        }
662    }
663}
664
665impl<'tcx> Stable<'tcx> for mir::InlineAsmOperand<'tcx> {
666    type T = crate::mir::InlineAsmOperand;
667    fn stable<'cx>(
668        &self,
669        tables: &mut Tables<'cx, BridgeTys>,
670        cx: &CompilerCtxt<'cx, BridgeTys>,
671    ) -> Self::T {
672        use rustc_middle::mir::InlineAsmOperand;
673
674        let (in_value, out_place) = match self {
675            InlineAsmOperand::In { value, .. } => (Some(value.stable(tables, cx)), None),
676            InlineAsmOperand::Out { place, .. } => {
677                (None, place.map(|place| place.stable(tables, cx)))
678            }
679            InlineAsmOperand::InOut { in_value, out_place, .. } => {
680                (Some(in_value.stable(tables, cx)), out_place.map(|place| place.stable(tables, cx)))
681            }
682            InlineAsmOperand::Const { .. }
683            | InlineAsmOperand::SymFn { .. }
684            | InlineAsmOperand::SymStatic { .. }
685            | InlineAsmOperand::Label { .. } => (None, None),
686        };
687
688        crate::mir::InlineAsmOperand { in_value, out_place, raw_rpr: format!("{self:?}") }
689    }
690}
691
692impl<'tcx> Stable<'tcx> for mir::Terminator<'tcx> {
693    type T = crate::mir::Terminator;
694    fn stable<'cx>(
695        &self,
696        tables: &mut Tables<'cx, BridgeTys>,
697        cx: &CompilerCtxt<'cx, BridgeTys>,
698    ) -> Self::T {
699        use crate::mir::Terminator;
700        Terminator {
701            kind: self.kind.stable(tables, cx),
702            span: self.source_info.span.stable(tables, cx),
703        }
704    }
705}
706
707impl<'tcx> Stable<'tcx> for mir::TerminatorKind<'tcx> {
708    type T = crate::mir::TerminatorKind;
709    fn stable<'cx>(
710        &self,
711        tables: &mut Tables<'cx, BridgeTys>,
712        cx: &CompilerCtxt<'cx, BridgeTys>,
713    ) -> Self::T {
714        use crate::mir::TerminatorKind;
715        match self {
716            mir::TerminatorKind::Goto { target } => {
717                TerminatorKind::Goto { target: target.as_usize() }
718            }
719            mir::TerminatorKind::SwitchInt { discr, targets } => TerminatorKind::SwitchInt {
720                discr: discr.stable(tables, cx),
721                targets: {
722                    let branches = targets.iter().map(|(val, target)| (val, target.as_usize()));
723                    crate::mir::SwitchTargets::new(
724                        branches.collect(),
725                        targets.otherwise().as_usize(),
726                    )
727                },
728            },
729            mir::TerminatorKind::UnwindResume => TerminatorKind::Resume,
730            mir::TerminatorKind::UnwindTerminate(_) => TerminatorKind::Abort,
731            mir::TerminatorKind::Return => TerminatorKind::Return,
732            mir::TerminatorKind::Unreachable => TerminatorKind::Unreachable,
733            mir::TerminatorKind::Drop {
734                place,
735                target,
736                unwind,
737                replace: _,
738                drop: _,
739                async_fut: _,
740            } => TerminatorKind::Drop {
741                place: place.stable(tables, cx),
742                target: target.as_usize(),
743                unwind: unwind.stable(tables, cx),
744            },
745            mir::TerminatorKind::Call {
746                func,
747                args,
748                destination,
749                target,
750                unwind,
751                call_source: _,
752                fn_span: _,
753            } => TerminatorKind::Call {
754                func: func.stable(tables, cx),
755                args: args.iter().map(|arg| arg.node.stable(tables, cx)).collect(),
756                destination: destination.stable(tables, cx),
757                target: target.map(|t| t.as_usize()),
758                unwind: unwind.stable(tables, cx),
759            },
760            mir::TerminatorKind::TailCall { func: _, args: _, fn_span: _ } => todo!(),
761            mir::TerminatorKind::Assert { cond, expected, msg, target, unwind } => {
762                TerminatorKind::Assert {
763                    cond: cond.stable(tables, cx),
764                    expected: *expected,
765                    msg: msg.stable(tables, cx),
766                    target: target.as_usize(),
767                    unwind: unwind.stable(tables, cx),
768                }
769            }
770            mir::TerminatorKind::InlineAsm {
771                asm_macro: _,
772                template,
773                operands,
774                options,
775                line_spans,
776                targets,
777                unwind,
778            } => TerminatorKind::InlineAsm {
779                template: format!("{template:?}"),
780                operands: operands.iter().map(|operand| operand.stable(tables, cx)).collect(),
781                options: format!("{options:?}"),
782                line_spans: format!("{line_spans:?}"),
783                // FIXME: Figure out how to do labels in SMIR
784                destination: targets.first().map(|d| d.as_usize()),
785                unwind: unwind.stable(tables, cx),
786            },
787            mir::TerminatorKind::Yield { .. }
788            | mir::TerminatorKind::CoroutineDrop
789            | mir::TerminatorKind::FalseEdge { .. }
790            | mir::TerminatorKind::FalseUnwind { .. } => unreachable!(),
791        }
792    }
793}
794
795impl<'tcx> Stable<'tcx> for mir::interpret::ConstAllocation<'tcx> {
796    type T = Allocation;
797
798    fn stable<'cx>(
799        &self,
800        tables: &mut Tables<'cx, BridgeTys>,
801        cx: &CompilerCtxt<'cx, BridgeTys>,
802    ) -> Self::T {
803        self.inner().stable(tables, cx)
804    }
805}
806
807impl<'tcx> Stable<'tcx> for mir::interpret::Allocation {
808    type T = crate::ty::Allocation;
809
810    fn stable<'cx>(
811        &self,
812        tables: &mut Tables<'cx, BridgeTys>,
813        cx: &CompilerCtxt<'cx, BridgeTys>,
814    ) -> Self::T {
815        use rustc_public_bridge::context::AllocRangeHelpers;
816        alloc::allocation_filter(
817            self,
818            cx.alloc_range(rustc_abi::Size::ZERO, self.size()),
819            tables,
820            cx,
821        )
822    }
823}
824
825impl<'tcx> Stable<'tcx> for mir::interpret::AllocId {
826    type T = crate::mir::alloc::AllocId;
827    fn stable<'cx>(
828        &self,
829        tables: &mut Tables<'cx, BridgeTys>,
830        _: &CompilerCtxt<'cx, BridgeTys>,
831    ) -> Self::T {
832        tables.create_alloc_id(*self)
833    }
834}
835
836impl<'tcx> Stable<'tcx> for mir::interpret::GlobalAlloc<'tcx> {
837    type T = GlobalAlloc;
838
839    fn stable<'cx>(
840        &self,
841        tables: &mut Tables<'cx, BridgeTys>,
842        cx: &CompilerCtxt<'cx, BridgeTys>,
843    ) -> Self::T {
844        match self {
845            mir::interpret::GlobalAlloc::Function { instance, .. } => {
846                GlobalAlloc::Function(instance.stable(tables, cx))
847            }
848            mir::interpret::GlobalAlloc::VTable(ty, dyn_ty) => {
849                // FIXME: Should we record the whole vtable?
850                GlobalAlloc::VTable(ty.stable(tables, cx), dyn_ty.principal().stable(tables, cx))
851            }
852            mir::interpret::GlobalAlloc::Static(def) => {
853                GlobalAlloc::Static(tables.static_def(*def))
854            }
855            mir::interpret::GlobalAlloc::Memory(alloc) => {
856                GlobalAlloc::Memory(alloc.stable(tables, cx))
857            }
858            mir::interpret::GlobalAlloc::TypeId { ty } => {
859                GlobalAlloc::TypeId { ty: ty.stable(tables, cx) }
860            }
861        }
862    }
863}
864
865impl<'tcx> Stable<'tcx> for rustc_middle::mir::Const<'tcx> {
866    type T = crate::ty::MirConst;
867
868    fn stable<'cx>(
869        &self,
870        tables: &mut Tables<'cx, BridgeTys>,
871        cx: &CompilerCtxt<'cx, BridgeTys>,
872    ) -> Self::T {
873        let id = tables.intern_mir_const(cx.lift(*self).unwrap());
874        match *self {
875            mir::Const::Ty(ty, c) => MirConst::new(
876                crate::ty::ConstantKind::Ty(c.stable(tables, cx)),
877                ty.stable(tables, cx),
878                id,
879            ),
880            mir::Const::Unevaluated(unev_const, ty) => {
881                let kind = crate::ty::ConstantKind::Unevaluated(crate::ty::UnevaluatedConst {
882                    def: tables.const_def(unev_const.def),
883                    args: unev_const.args.stable(tables, cx),
884                    promoted: unev_const.promoted.map(|u| u.as_u32()),
885                });
886                let ty = ty.stable(tables, cx);
887                MirConst::new(kind, ty, id)
888            }
889            mir::Const::Val(mir::ConstValue::ZeroSized, ty) => {
890                let ty = ty.stable(tables, cx);
891                MirConst::new(ConstantKind::ZeroSized, ty, id)
892            }
893            mir::Const::Val(val, ty) => {
894                let ty = cx.lift(ty).unwrap();
895                let val = cx.lift(val).unwrap();
896                let kind = ConstantKind::Allocated(alloc::new_allocation(ty, val, tables, cx));
897                let ty = ty.stable(tables, cx);
898                MirConst::new(kind, ty, id)
899            }
900        }
901    }
902}
903
904impl<'tcx> Stable<'tcx> for mir::interpret::ErrorHandled {
905    type T = Error;
906
907    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
908        bridge::Error::new(format!("{self:?}"))
909    }
910}
911
912impl<'tcx> Stable<'tcx> for MonoItem<'tcx> {
913    type T = crate::mir::mono::MonoItem;
914
915    fn stable<'cx>(
916        &self,
917        tables: &mut Tables<'cx, BridgeTys>,
918        cx: &CompilerCtxt<'cx, BridgeTys>,
919    ) -> Self::T {
920        use crate::mir::mono::MonoItem as StableMonoItem;
921        match self {
922            MonoItem::Fn(instance) => StableMonoItem::Fn(instance.stable(tables, cx)),
923            MonoItem::Static(def_id) => StableMonoItem::Static(tables.static_def(*def_id)),
924            MonoItem::GlobalAsm(item_id) => StableMonoItem::GlobalAsm(opaque(item_id)),
925        }
926    }
927}