Skip to main content

charon_driver/translate/
translate_bodies.rs

1//! Translate functions from the rust compiler MIR to our internal representation.
2//! Our internal representation is very close to MIR, but is more convenient for
3//! us to handle, and easier to maintain - rustc's representation can evolve
4//! independently.
5
6use itertools::Itertools;
7use rustc_attr_ir::LangItem;
8use std::borrow::Cow;
9use std::collections::VecDeque;
10use std::mem;
11use std::ops::Deref;
12use std::ops::DerefMut;
13use std::panic;
14use std::rc::Rc;
15
16use crate::frontend as front;
17use rustc_middle::mir;
18use rustc_middle::ty;
19use rustc_span::{Symbol, kw, sym};
20
21use super::translate_ctx::*;
22use super::user_type_annotations::UserTypeAnnotations;
23use charon_lib::formatter::{FmtCtx, IntoFormatter, compute_local_names};
24use charon_lib::name_matcher::NamePattern;
25use charon_lib::options::TranslateOptions;
26use charon_lib::pretty::FmtWithCtx;
27use charon_lib::transform::ctx::BodyTransformCtx;
28use charon_lib::ullbc_ast::*;
29
30/// A translation context for function bodies.
31pub(crate) struct BodyTransCtx<'tcx, 'tctx, 'ictx> {
32    /// The translation context for the item.
33    pub i_ctx: &'ictx mut ItemTransCtx<'tcx, 'tctx>,
34    /// List of body locals.
35    pub local_decls: &'ictx rustc_index::IndexVec<mir::Local, mir::LocalDecl<'tcx>>,
36    /// Types supplied explicitly by the user.
37    pub user_type_annotations: UserTypeAnnotations,
38
39    /// What kind of drops we get in this body.
40    pub drop_kind: DropKind,
41    /// The (regular) variables in the current function body.
42    pub locals: Locals,
43    /// The map from rust variable indices to translated variables indices.
44    pub locals_map: rustc_index::IndexVec<mir::Local, LocalId>,
45    /// The translated blocks.
46    pub blocks: IndexMap<BlockId, BlockData>,
47    /// The map from rust blocks to translated blocks.
48    /// Note that when translating terminators like DropAndReplace, we might have
49    /// to introduce new blocks which don't appear in the original MIR.
50    pub blocks_map: rustc_index::IndexVec<mir::BasicBlock, Option<BlockId>>,
51    /// We register the blocks to translate in a stack, so as to avoid
52    /// writing the translation functions as recursive functions. We do
53    /// so because we had stack overflows in the past.
54    pub blocks_stack: VecDeque<mir::BasicBlock>,
55}
56
57impl<'tcx, 'tctx, 'ictx> BodyTransCtx<'tcx, 'tctx, 'ictx> {
58    pub(crate) fn new(
59        i_ctx: &'ictx mut ItemTransCtx<'tcx, 'tctx>,
60        body: &'ictx Rc<mir::Body<'tcx>>,
61        drop_kind: DropKind,
62    ) -> Result<Self, Error> {
63        i_ctx.lifetime_freshener = (!i_ctx.options.erase_body_lifetimes).then(IndexMap::new);
64        let user_type_annotations = UserTypeAnnotations::new(i_ctx, body)?;
65
66        // Translate the local variables.
67        let mut locals = Locals {
68            arg_count: body.arg_count,
69            ..Default::default()
70        };
71        let mut locals_map = rustc_index::IndexVec::with_capacity(body.local_decls.len());
72        let mut names = front::local_names(body);
73        // Translate the parameters
74        for (index, var) in body.local_decls.iter_enumerated() {
75            let name = names[index].take();
76
77            // Translate the type
78            let span = i_ctx.translate_span(&var.source_info.span);
79            let (ty, borrowck_constraints) = user_type_annotations.translate_local_ty(
80                i_ctx,
81                span,
82                locals.locals.next_idx(),
83                var,
84            )?;
85
86            // Add the variable to the environment
87            let local_id = locals.locals.push_with(|index| Local {
88                index,
89                name,
90                span,
91                ty,
92                mutable: var.mutability.is_mut(),
93                borrowck_constraints,
94                drop_flag_for: None,
95            });
96            locals_map.push(local_id);
97        }
98
99        Ok(BodyTransCtx {
100            i_ctx,
101            local_decls: &body.local_decls,
102            user_type_annotations,
103            drop_kind,
104            locals,
105            locals_map,
106            blocks: Default::default(),
107            blocks_map: rustc_index::IndexVec::from_elem_n(None, body.basic_blocks.len()),
108            blocks_stack: Default::default(),
109        })
110    }
111}
112
113impl<'tcx, 'tctx, 'ictx> Deref for BodyTransCtx<'tcx, 'tctx, 'ictx> {
114    type Target = ItemTransCtx<'tcx, 'tctx>;
115    fn deref(&self) -> &Self::Target {
116        self.i_ctx
117    }
118}
119impl<'tcx, 'tctx, 'ictx> DerefMut for BodyTransCtx<'tcx, 'tctx, 'ictx> {
120    fn deref_mut(&mut self) -> &mut Self::Target {
121        self.i_ctx
122    }
123}
124
125/// A translation context for function blocks.
126pub(crate) struct BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
127    /// The translation context for the item.
128    pub b_ctx: &'bctx mut BodyTransCtx<'tcx, 'tctx, 'ictx>,
129    /// Block onto which we're adding statements.
130    pub current_block: BlockId,
131    /// The kind of the current block.
132    pub kind: UnwindKind,
133    /// Span of the statement or terminator currently being translated.
134    pub span: Span,
135    /// List of currently translated statements
136    pub statements: Vec<Statement>,
137}
138
139impl<'tcx, 'tctx, 'ictx, 'bctx> BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
140    pub(crate) fn new(
141        b_ctx: &'bctx mut BodyTransCtx<'tcx, 'tctx, 'ictx>,
142        current_block: BlockId,
143        kind: UnwindKind,
144    ) -> Self {
145        BlockTransCtx {
146            b_ctx,
147            current_block,
148            kind,
149            span: Span::dummy(),
150            statements: Vec::new(),
151        }
152    }
153
154    fn finish_current_block(self, terminator: Terminator) {
155        let block = BlockData {
156            statements: self.statements,
157            terminator,
158            kind: self.kind,
159        };
160        self.b_ctx.blocks.set_slot(self.current_block, block);
161    }
162
163    /// Used for non-diverging intrinsics.
164    fn push_nounwind_call(&mut self, span: Span, dest: Place, call: Call) {
165        let target = self.blocks.reserve_slot();
166        let unwind_kind = self.kind.further_unwind_kind();
167        let on_unwind = self
168            .blocks
169            .push(Terminator::new(span, TerminatorKind::UndefinedBehavior).into_block(unwind_kind));
170        let block = BlockData {
171            statements: mem::take(&mut self.statements),
172            terminator: Terminator::new(
173                span,
174                TerminatorKind::Call {
175                    call,
176                    dest,
177                    target,
178                    on_unwind,
179                },
180            ),
181            kind: self.kind,
182        };
183        let current_block = mem::replace(&mut self.current_block, target);
184        self.blocks.set_slot(current_block, block);
185    }
186}
187
188impl<'tcx, 'tctx, 'ictx, 'bctx> Deref for BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
189    type Target = BodyTransCtx<'tcx, 'tctx, 'ictx>;
190    fn deref(&self) -> &Self::Target {
191        self.b_ctx
192    }
193}
194impl<'tcx, 'tctx, 'ictx, 'bctx> DerefMut for BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
195    fn deref_mut(&mut self) -> &mut Self::Target {
196        self.b_ctx
197    }
198}
199
200impl<'tcx> TranslateCtx<'tcx> {
201    pub fn translate_variant_id(&self, id: front::VariantIdx) -> VariantId {
202        VariantId::new(id.as_usize())
203    }
204
205    pub fn translate_field_id(&self, id: front::FieldIdx) -> FieldId {
206        FieldId::new(id.index())
207    }
208
209    pub fn translate_metadata_path(&self, path: &[front::FieldIdx]) -> MetadataPath {
210        path.iter().map(|id| self.translate_field_id(*id)).collect()
211    }
212
213    fn translate_borrow_kind(
214        &self,
215        span: Span,
216        borrow_kind: mir::BorrowKind,
217    ) -> Result<BorrowKind, Error> {
218        Ok(match borrow_kind {
219            mir::BorrowKind::Shared => BorrowKind::Shared,
220            mir::BorrowKind::Mut { kind } => match kind {
221                mir::MutBorrowKind::Default => BorrowKind::Mut,
222                mir::MutBorrowKind::TwoPhaseBorrow => BorrowKind::TwoPhaseMut,
223                mir::MutBorrowKind::ClosureCapture => BorrowKind::UniqueImmutable,
224            },
225            mir::BorrowKind::Fake(mir::FakeBorrowKind::Shallow) => BorrowKind::Shallow,
226            // This one is used only in deref patterns.
227            mir::BorrowKind::Fake(mir::FakeBorrowKind::Deep) => {
228                raise_error!(self, span, "deref patterns are not supported")
229            }
230        })
231    }
232}
233
234impl<'tcx> ItemTransCtx<'tcx, '_> {
235    /// Translate the names of the arguments of this function, if they are available.
236    pub fn translate_argument_names(
237        &mut self,
238        def: &front::FullDef<'tcx>,
239        n_args: usize,
240    ) -> Vec<Option<String>> {
241        let Some(def_id) = def.def_id().as_real_def_id() else {
242            return vec![None; n_args];
243        };
244        (self.tcx.fn_arg_idents(def_id).iter())
245            .map(|ident| Some(ident.filter(|i| i.name != kw::Underscore)?.to_string()))
246            .collect()
247    }
248
249    /// Translate the MIR body of this definition if it has one. Catches any error and returns
250    /// `Body::Error` instead
251    pub fn translate_def_body(&mut self, span: Span, def: &front::FullDef<'tcx>) -> Body {
252        match self.translate_def_body_inner(span, def) {
253            Ok(body) => body,
254            Err(e) => Body::Error(e),
255        }
256    }
257
258    fn translate_def_body_inner(
259        &mut self,
260        span: Span,
261        def: &front::FullDef<'tcx>,
262    ) -> Result<Body, Error> {
263        // Retrieve the body
264        if let Some(body) = self.get_mir(&def.this().derived_base(self.frontend_state()), span)? {
265            Ok(self.translate_body(span, body, &def.source_text(self.tcx)))
266        } else if let Some(value) =
267            def.evaluate(self.frontend_state_with_id(), front::ReadMode::Structured)
268        {
269            // For globals without MIR, generate a body by evaluating the global. This is how we
270            // get the value of statics (which have no cross-crate MIR at all) and of "trivial"
271            // consts (whose value rustc stores directly instead of encoding MIR for it).
272            let c = self.translate_constant_expr(span, &value)?;
273            let mut bb = BodyBuilder::new(span, 0);
274            let ret = bb.new_var(None, c.ty().clone());
275            bb.push_statement(StatementKind::Assign(
276                ret,
277                Rvalue::Use(Operand::Const(c), WithRetag::No),
278            ));
279            Ok(Body::Unstructured(bb.build()))
280        } else {
281            Ok(Body::Missing)
282        }
283    }
284
285    /// Translate a function body. Catches errors and returns `Body::Error` instead.
286    /// That's the entrypoint of this module.
287    pub fn translate_body(
288        &mut self,
289        span: Span,
290        body: mir::Body<'tcx>,
291        source_text: &Option<String>,
292    ) -> Body {
293        let _guard = charon_lib::timing::scope("translate-body");
294        let drop_kind = match body.phase {
295            mir::MirPhase::Built | mir::MirPhase::Analysis(..) => DropKind::Conditional,
296            mir::MirPhase::Runtime(..) => DropKind::Precise,
297        };
298        let mut ctx = panic::AssertUnwindSafe(&mut *self);
299        let body = panic::AssertUnwindSafe(body);
300        // Stopgap measure because there are still many panics in charon and the frontend.
301        let res = panic::catch_unwind(move || {
302            let body = Rc::new({ body }.0);
303            let ctx = BodyTransCtx::new(*ctx, &body, drop_kind)?;
304            ctx.translate_body(&body, source_text)
305        });
306        match res {
307            Ok(Ok(body)) => body,
308            // Translation error
309            Ok(Err(e)) => Body::Error(e),
310            // Panic
311            Err(_) => {
312                let e = register_error!(self, span, "Thread panicked when extracting body.");
313                Body::Error(e)
314            }
315        }
316    }
317
318    pub(crate) fn translate_unsizing_metadata(
319        &mut self,
320        span: Span,
321        meta: &front::UnsizingMetadata<'tcx>,
322    ) -> Result<UnsizingMetadata, Error> {
323        Ok(match meta {
324            front::UnsizingMetadata::Length(len) => {
325                let len = self.translate_constant_expr(span, len)?;
326                UnsizingMetadata::Length(len)
327            }
328            front::UnsizingMetadata::DirectVTable(trait_proof) => {
329                let tref = self.translate_trait_proof(span, trait_proof)?;
330                let vtable = self.translate_vtable_instance_const(span, trait_proof)?;
331                UnsizingMetadata::VTable(Box::new(tref), vtable)
332            }
333            front::UnsizingMetadata::NestedVTable(dyn_trait_proof) => {
334                // This binds a fake `T: SrcTrait` variable.
335                let binder =
336                    self.translate_dyn_binder(span, dyn_trait_proof, |ctx, _, trait_proof| {
337                        ctx.translate_trait_proof(span, trait_proof)
338                    })?;
339
340                // Compute the supertrait path from the source tref to the target
341                // tref.
342                let target_proof = binder.skip_binder.clone().erase();
343                let mut target_tref = &target_proof;
344                let mut clause_path: Vec<(TraitDeclId, TraitClauseId)> = vec![];
345                while let TraitRefKind::ParentClause(tref, id, _) = &target_tref.kind {
346                    clause_path.push((tref.trait_id(), *id));
347                    target_tref = tref;
348                }
349
350                let mut field_path = thin_vec::ThinVec::new();
351                for &(trait_id, clause_id) in &clause_path {
352                    if let Ok(ItemRef::TraitDecl(tdecl)) = self.get_or_translate(trait_id.into())
353                        && let vtable_decl_id = tdecl.vtable.as_ref().unwrap().id
354                        && let Ok(ItemRef::Type(vtable_decl)) =
355                            self.get_or_translate(vtable_decl_id.into())
356                    {
357                        let TypeSource::VTable { supertrait_map, .. } = &vtable_decl.src else {
358                            unreachable!()
359                        };
360                        field_path.push(supertrait_map[clause_id].unwrap());
361                    } else {
362                        break;
363                    }
364                }
365
366                assert_eq!(field_path.len(), clause_path.len());
367                UnsizingMetadata::VTableUpcast(field_path)
368            }
369            front::UnsizingMetadata::UnsizeClause(trait_proof) => UnsizingMetadata::UnsizeClause(
370                self.translate_trait_proof(span, trait_proof)?.erase(),
371            ),
372            front::UnsizingMetadata::CoerceUnsizedClause(trait_proof) => {
373                UnsizingMetadata::CoerceUnsizedClause(
374                    self.translate_trait_proof(span, trait_proof)?.erase(),
375                )
376            }
377        })
378    }
379
380    /// Generate a fake function body for ADT constructors.
381    pub(crate) fn build_ctor_body(
382        &mut self,
383        span: Span,
384        def: &front::FullDef<'tcx>,
385    ) -> Result<Body, Error> {
386        let ctor = def.kind().as_ctor().unwrap();
387        let tref = self.translate_type_decl_ref(
388            span,
389            &def.this()
390                .with_def_id(self.frontend_state(), ctor.adt_def_id()),
391        )?;
392        let output_ty = self.translate_ty(span, ctor.output_ty())?;
393
394        let mut builder = BodyBuilder::new(span, ctor.fields().len());
395        let return_place = builder.new_var(None, output_ty);
396        let args: Vec<_> = ctor
397            .fields()
398            .iter()
399            .map(|field| -> Result<Operand, Error> {
400                let ty = self.translate_ty(span, &field.ty)?;
401                let place = builder.new_var(None, ty);
402                Ok(Operand::Move(place))
403            })
404            .try_collect()?;
405        let variant = match ctor.ctor_of() {
406            front::CtorOf::Struct => None,
407            front::CtorOf::Variant => Some(self.translate_variant_id(ctor.variant_id())),
408        };
409        builder.push_statement(StatementKind::Assign(
410            return_place,
411            Rvalue::Aggregate(AggregateKind::Adt(tref, variant, None), args),
412        ));
413        Ok(Body::Unstructured(builder.build()))
414    }
415
416    /// FIXME(#865): Generate a function body for the `box_assume_init_into_vec_unsafe` function,
417    /// because the MIR we get for it is too optimized to be usable.
418    pub(crate) fn build_box_assume_init_into_vec_unsafe(
419        &mut self,
420        span: Span,
421        def: &front::FullDef<'tcx>,
422    ) -> Result<Body, Error> {
423        // pub fn box_assume_init_into_vec_unsafe<T, const N: usize>(
424        //     b: Box<MaybeUninit<[T; N]>>,
425        // ) -> Vec<T> {
426        //     let x: Box<[T; N]> = unsafe { Box::assume_init(b) };
427        //     let y = x as Box<[T]>;
428        //     core::slice::into_vec(y)
429        // }
430        let tcx = self.tcx;
431        let f = def.kind().as_fn().unwrap();
432        let frontend_sig = f.sig().frontend_skip_binder_ref();
433        let sig = self.translate_fun_sig(span, frontend_sig)?;
434
435        // Get the `[T; N]` and `A` parameters.
436        let (array_rust_ty, alloc_rust_ty) = {
437            let input_box_rust_args = {
438                let front::TyKind::Adt(input_box) = frontend_sig.inputs[0].kind() else {
439                    raise_error!(
440                        self,
441                        span,
442                        "expected a boxed input in the frontend signature"
443                    );
444                };
445                input_box.item.rustc_args(self.frontend_state_with_id())
446            };
447            let maybe_uninit_array_rust_ty = input_box_rust_args[0].as_type().unwrap();
448            let alloc_rust_ty = input_box_rust_args[1].as_type().unwrap();
449            let ty::Adt(_, maybe_uninit_rust_args) = maybe_uninit_array_rust_ty.kind() else {
450                raise_error!(
451                    self,
452                    span,
453                    "expected `MaybeUninit<[T; N]>` in the frontend signature"
454                );
455            };
456            let Some(array_rust_ty) = maybe_uninit_rust_args[0].as_type() else {
457                raise_error!(
458                    self,
459                    span,
460                    "expected the first `MaybeUninit` parameter to be a type"
461                );
462            };
463            (array_rust_ty, alloc_rust_ty)
464        };
465        // `T`
466        let elem_rust_ty = array_rust_ty.builtin_index().unwrap();
467        // `[T]`
468        let slice_rust_ty = ty::Ty::new_slice(tcx, elem_rust_ty);
469        // `Box<[T; N]>`
470        let box_array_rust_ty = ty::Ty::new_box(tcx, array_rust_ty);
471        let box_array_ty = self.translate_rustc_ty(span, &box_array_rust_ty)?;
472        // `Box<[T]>`
473        let box_slice_rust_ty = ty::Ty::new_box(tcx, slice_rust_ty);
474        let box_slice_ty = self.translate_rustc_ty(span, &box_slice_rust_ty)?;
475
476        if !self.monomorphize() {
477            // Make `Box::new` and `Box::write` available to a later construction pass.
478            let path = NamePattern::parse(names::BOX_NEW).unwrap();
479            let box_new_def_id = self.resolve_single_path(span, &path)?;
480            let box_new_args = tcx.mk_args(&[array_rust_ty.into()]);
481            let box_new_item = front::ItemRef::translate(
482                self.frontend_state_with_id(),
483                box_new_def_id,
484                box_new_args,
485            );
486            let _ = self.translate_fn_ptr(span, &box_new_item)?;
487
488            let path = NamePattern::parse(names::BOX_WRITE).unwrap();
489            let box_write_def_id = self.resolve_single_path(span, &path)?;
490            let box_write_args = tcx.mk_args(&[array_rust_ty.into(), alloc_rust_ty.into()]);
491            let box_write_item = front::ItemRef::translate(
492                self.frontend_state_with_id(),
493                box_write_def_id,
494                box_write_args,
495            );
496            let _ = self.translate_fn_ptr(span, &box_write_item)?;
497        }
498
499        let body = {
500            let mut builder = BodyBuilder::new(span, sig.inputs.len());
501            let return_place = builder.new_var(Some("ret".to_string()), sig.output.clone());
502            let input = builder.new_var(Some("b".to_string()), sig.inputs[0].clone());
503            let initialized_box = builder.new_var(Some("x".to_string()), box_array_ty.clone());
504            let box_slice = builder.new_var(Some("y".to_string()), box_slice_ty.clone());
505
506            let call = {
507                let assume_init_fn = {
508                    let path = NamePattern::parse("alloc::boxed::Box::assume_init").unwrap();
509                    let assume_init_def_id = self
510                        .resolve_path(span, &path, true)?
511                        .into_iter()
512                        // There's `assume_init` on `Box<MU<T>>` and `Box<[MU<T>]>`, we want the former.
513                        .filter(|&def_id| {
514                            let sig = self.tcx.fn_sig(def_id);
515                            !sig.skip_binder().inputs().skip_binder()[0]
516                                .expect_boxed_ty()
517                                .is_slice()
518                        })
519                        .exactly_one()
520                        .unwrap();
521                    let assume_init_args =
522                        tcx.mk_args(&[array_rust_ty.into(), alloc_rust_ty.into()]);
523                    let assume_init_item = front::ItemRef::translate(
524                        self.frontend_state_with_id(),
525                        assume_init_def_id,
526                        assume_init_args,
527                    );
528                    self.translate_fn_ptr(span, &assume_init_item)?
529                };
530                Call {
531                    func: FnOperand::Regular(assume_init_fn),
532                    args: vec![Operand::Move(input)],
533                    safety: CallSafety::Inherit,
534                }
535            };
536            builder.call(initialized_box.clone(), call);
537
538            builder.push_statement({
539                let (path, meta) = front::compute_unsizing_metadata(
540                    &self.frontend_state,
541                    box_array_rust_ty,
542                    box_slice_rust_ty,
543                );
544                let meta = self.translate_unsizing_metadata(span, &meta)?;
545                let path = self.translate_metadata_path(&path);
546                StatementKind::Assign(
547                    box_slice.clone(),
548                    Rvalue::UnaryOp(
549                        UnOp::Cast(CastKind::Unsize(box_slice_ty, meta, path)),
550                        Operand::Move(initialized_box),
551                    ),
552                )
553            });
554
555            let call = {
556                let into_vec_fn = {
557                    let path = NamePattern::parse("slice::into_vec").unwrap();
558                    let into_vec_def_id = self.resolve_single_path(span, &path)?;
559                    let into_vec_args = tcx.mk_args(&[elem_rust_ty.into(), alloc_rust_ty.into()]);
560                    let into_vec_item = front::ItemRef::translate(
561                        self.frontend_state_with_id(),
562                        into_vec_def_id,
563                        into_vec_args,
564                    );
565                    self.translate_fn_ptr(span, &into_vec_item)?
566                };
567                Call {
568                    func: FnOperand::Regular(into_vec_fn),
569                    args: vec![Operand::Move(box_slice)],
570                    safety: CallSafety::Inherit,
571                }
572            };
573            builder.call(return_place, call);
574            builder.build()
575        };
576
577        Ok(Body::Unstructured(body))
578    }
579
580    /// Generate a function body for `core::intrinsics::type_id`.
581    pub(crate) fn build_type_id_body(
582        &mut self,
583        span: Span,
584        signature: &FunSig,
585    ) -> Result<Body, Error> {
586        let generics = self.outermost_generics().identity_args();
587        let type_id_ty = generics.types[0].clone();
588
589        let mut builder = BodyBuilder::new(span, signature.inputs.len());
590        let return_place = builder.new_var(Some("ret".to_string()), signature.output.clone());
591        let type_id = ConstantExpr::new(
592            ConstantExprKind::TypeId(type_id_ty),
593            signature.output.clone(),
594        );
595        builder.push_statement(StatementKind::Assign(
596            return_place,
597            Rvalue::Use(Operand::Const(type_id), WithRetag::No),
598        ));
599        Ok(Body::Unstructured(builder.build()))
600    }
601
602    /// Generate a function body for `core::ptr::drop_glue`.
603    pub(crate) fn build_drop_glue_body(
604        &mut self,
605        span: Span,
606        def: &front::FullDef<'tcx>,
607        signature: &FunSig,
608    ) -> Result<Body, Error> {
609        assert!(def.kind().is_fn());
610        let def_id = def.def_id().as_real_def_id().unwrap();
611        let rustc_args = def.this().rustc_args(self.frontend_state_with_id());
612        let rustc_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, rustc_args);
613        // `skip_binder` is ok because we have that lifetime in scope.
614        let input_ty = rustc_sig.skip_binder().inputs()[0];
615        let pointee_ty = input_ty
616            .builtin_deref(true)
617            .expect("`drop_glue` argument is not a pointer");
618        let fn_ptr = self.translate_drop_glue_method_call(span, pointee_ty)?;
619
620        let mut builder = BodyBuilder::new(span, signature.inputs.len());
621        let return_place = builder.new_var(Some("ret".to_string()), signature.output.clone());
622        builder.push_statement(StatementKind::Assign(return_place, Rvalue::unit_value()));
623        let input = builder.new_var(None, signature.inputs[0].clone());
624        builder.insert_drop(input.deref(), fn_ptr);
625        Ok(Body::Unstructured(builder.build()))
626    }
627}
628
629impl<'tcx> BodyTransCtx<'tcx, '_, '_> {
630    pub(crate) fn translate_local(&self, local: &mir::Local) -> Option<LocalId> {
631        self.locals_map.get(*local).copied()
632    }
633
634    /// Translate a basic block id and register it, if it hasn't been done.
635    fn translate_basic_block_id(&mut self, block_id: mir::BasicBlock) -> BlockId {
636        match self.blocks_map[block_id] {
637            Some(id) => id,
638            // Generate a fresh id - this also registers the block
639            None => {
640                // Push to the stack of blocks awaiting translation
641                self.blocks_stack.push_back(block_id);
642                let id = self.blocks.reserve_slot();
643                // Insert in the map
644                self.blocks_map[block_id] = Some(id);
645                id
646            }
647        }
648    }
649
650    fn translate_basic_block(
651        &mut self,
652        block_id: BlockId,
653        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
654        block: &mir::BasicBlockData<'tcx>,
655    ) -> Result<(), Error> {
656        // Translate the statements
657        let kind = if block.is_cleanup {
658            UnwindKind::Cleanup
659        } else {
660            UnwindKind::Regular
661        };
662        let mut block_ctx = BlockTransCtx::new(self, block_id, kind);
663        for statement in &block.statements {
664            trace!("statement: {:?}", statement);
665            block_ctx.translate_statement(source_scopes, statement)?;
666        }
667
668        // Translate the terminator
669        let terminator = block.terminator.as_ref().unwrap();
670        block_ctx.translate_terminator(source_scopes, terminator)?;
671
672        Ok(())
673    }
674
675    /// Gather all the lines that start with `//` inside the given span.
676    fn translate_body_comments(
677        &mut self,
678        source_text: &Option<String>,
679        charon_span: Span,
680    ) -> Vec<(u32, Vec<String>)> {
681        if let Some(body_text) = source_text {
682            let mut comments = body_text
683                .lines()
684                // Iter through the lines of this body in reverse order.
685                .rev()
686                .enumerate()
687                // Compute the absolute line number
688                .filter_map(|(i, line)| {
689                    Some(((charon_span.data().end.line).checked_sub(i as u32)?, line))
690                })
691                // Extract the comment if this line starts with `//`
692                .map(|(line_nbr, line)| (line_nbr, line.trim_start().strip_prefix("//")))
693                .peekable()
694                .batching(|iter| {
695                    // Get the next line. This is not a comment: it's either the last line of the
696                    // body or a line that wasn't consumed by `peeking_take_while`.
697                    let (line_nbr, _first) = iter.next()?;
698                    // Collect all the comments before this line.
699                    let mut comments = iter
700                        // `peeking_take_while` ensures we don't consume a line that returns
701                        // `false`. It will be consumed by the next round of `batching`.
702                        .peeking_take_while(|(_, opt_comment)| opt_comment.is_some())
703                        .map(|(_, opt_comment)| opt_comment.unwrap())
704                        .map(|s| s.strip_prefix(" ").unwrap_or(s))
705                        .map(str::to_owned)
706                        .collect_vec();
707                    comments.reverse();
708                    Some((line_nbr, comments))
709                })
710                .filter(|(_, comments)| !comments.is_empty())
711                .collect_vec();
712            comments.reverse();
713            comments
714        } else {
715            Vec::new()
716        }
717    }
718
719    fn translate_body(
720        mut self,
721        mir_body: &mir::Body<'tcx>,
722        source_text: &Option<String>,
723    ) -> Result<Body, Error> {
724        // Compute the span information
725        let span = self.translate_span(&mir_body.span);
726
727        // Translate the expression body
728        trace!("Translating the expression body");
729
730        // Register the start block
731        let id = self.translate_basic_block_id(rustc_index::Idx::new(mir::START_BLOCK.as_usize()));
732        assert!(id == START_BLOCK_ID);
733
734        // For as long as there are blocks in the stack, translate them
735        while let Some(mir_block_id) = self.blocks_stack.pop_front() {
736            let mir_block = mir_body.basic_blocks.get(mir_block_id).unwrap();
737            let block_id = self.translate_basic_block_id(mir_block_id);
738            self.translate_basic_block(block_id, &mir_body.source_scopes, mir_block)?;
739        }
740
741        // Record the outlives that need to hold throughout the body.
742        let outlives = self.user_type_annotations.outlives.drain(..).map(|pred| {
743            let kind = StatementKind::Borrowck(BorrowckStatement::SetOutlives(pred));
744            Statement::new(span, kind)
745        });
746        self.blocks[START_BLOCK_ID]
747            .statements
748            .splice(0..0, outlives);
749
750        // Create the body
751        let comments = self.translate_body_comments(source_text, span);
752        Ok(Body::Unstructured(ExprBody {
753            span,
754            locals: self.locals,
755            bound_body_regions: self
756                .i_ctx
757                .lifetime_freshener
758                .take()
759                .map_or(0, |v| v.slot_count()),
760            body: self.blocks.make_contiguous(),
761            comments,
762        }))
763    }
764}
765
766impl BodyTransformCtx for BlockTransCtx<'_, '_, '_, '_> {
767    fn get_crate(&self) -> &TranslatedCrate {
768        &self.translated
769    }
770
771    fn get_options(&self) -> &TranslateOptions {
772        &self.options
773    }
774
775    fn get_params(&self) -> &GenericParams {
776        self.outermost_generics()
777    }
778
779    fn get_locals_mut(&mut self) -> &mut Locals {
780        &mut self.locals
781    }
782
783    fn insert_storage_live_stmt(&mut self, local: LocalId) {
784        self.statements
785            .push(Statement::new(self.span, StatementKind::StorageLive(local)));
786    }
787
788    fn insert_storage_dead_stmt(&mut self, local: LocalId) {
789        self.statements
790            .push(Statement::new(self.span, StatementKind::StorageDead(local)));
791    }
792
793    fn insert_assn_stmt(&mut self, place: Place, rvalue: Rvalue) {
794        self.statements.push(Statement::new(
795            self.span,
796            StatementKind::Assign(place, rvalue),
797        ));
798    }
799}
800
801impl<'tcx> BlockTransCtx<'tcx, '_, '_, '_> {
802    fn missing_ptr_metadata() -> Operand {
803        Operand::Const(ConstantExpr::new(
804            ConstantExprKind::Opaque("Missing metadata".to_string()),
805            Ty::mk_unit(),
806        ))
807    }
808
809    fn translate_thread_local_ref(
810        &mut self,
811        span: Span,
812        def_id: rustc_hir::def_id::DefId,
813    ) -> Result<Rvalue, Error> {
814        let args = ty::GenericArgs::empty();
815        let item = front::translate_item_ref(&self.frontend_state, def_id, args);
816        let global_ref = self.translate_global_decl_ref(span, &item)?;
817
818        let ptr_ty = self.tcx.thread_local_ptr_ty(def_id);
819        let ty = ptr_ty.builtin_deref(true).unwrap();
820        let ty = self.translate_rustc_ty(span, &ty)?;
821        let place = Place::new_global(global_ref, ty);
822        match ptr_ty.kind() {
823            ty::TyKind::Ref(_, _, mutability) => {
824                let kind = if mutability.is_mut() {
825                    BorrowKind::Mut
826                } else {
827                    BorrowKind::Shared
828                };
829                Ok(Rvalue::Ref {
830                    place,
831                    kind,
832                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
833                    ptr_metadata: Self::missing_ptr_metadata(),
834                })
835            }
836            ty::TyKind::RawPtr(_, mutability) => {
837                let kind = if mutability.is_mut() {
838                    RefKind::Mut
839                } else {
840                    RefKind::Shared
841                };
842                Ok(Rvalue::RawPtr {
843                    place,
844                    kind,
845                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
846                    ptr_metadata: Self::missing_ptr_metadata(),
847                })
848            }
849            _ => raise_error!(
850                self,
851                span,
852                "unexpected type for thread-local reference: {ptr_ty:?}"
853            ),
854        }
855    }
856
857    fn translate_binaryop_kind(&mut self, _span: Span, binop: mir::BinOp) -> Result<BinOp, Error> {
858        Ok(match binop {
859            mir::BinOp::BitXor => BinOp::BitXor,
860            mir::BinOp::BitAnd => BinOp::BitAnd,
861            mir::BinOp::BitOr => BinOp::BitOr,
862            mir::BinOp::Eq => BinOp::Eq,
863            mir::BinOp::Lt => BinOp::Lt,
864            mir::BinOp::Le => BinOp::Le,
865            mir::BinOp::Ne => BinOp::Ne,
866            mir::BinOp::Ge => BinOp::Ge,
867            mir::BinOp::Gt => BinOp::Gt,
868            mir::BinOp::Add => BinOp::Add(OverflowMode::Wrap),
869            mir::BinOp::AddUnchecked => BinOp::Add(OverflowMode::UB),
870            mir::BinOp::Sub => BinOp::Sub(OverflowMode::Wrap),
871            mir::BinOp::SubUnchecked => BinOp::Sub(OverflowMode::UB),
872            mir::BinOp::Mul => BinOp::Mul(OverflowMode::Wrap),
873            mir::BinOp::MulUnchecked => BinOp::Mul(OverflowMode::UB),
874            mir::BinOp::Div => BinOp::Div(OverflowMode::UB),
875            mir::BinOp::Rem => BinOp::Rem(OverflowMode::UB),
876            mir::BinOp::AddWithOverflow
877            | mir::BinOp::SubWithOverflow
878            | mir::BinOp::MulWithOverflow => unreachable!("handled in `translate_statement`"),
879            mir::BinOp::Shl => BinOp::Shl(OverflowMode::Wrap),
880            mir::BinOp::ShlUnchecked => BinOp::Shl(OverflowMode::UB),
881            mir::BinOp::Shr => BinOp::Shr(OverflowMode::Wrap),
882            mir::BinOp::ShrUnchecked => BinOp::Shr(OverflowMode::UB),
883            mir::BinOp::Cmp => BinOp::Cmp,
884            mir::BinOp::Offset => unreachable!("handled in `translate_mir_rvalue`"),
885        })
886    }
887
888    fn translate_place(
889        &mut self,
890        span: Span,
891        mir_place: &mir::Place<'tcx>,
892    ) -> Result<Place, Error> {
893        use crate::frontend::{BaseState, SInto};
894        use rustc_middle::ty;
895
896        let tcx = self.frontend_state.base().tcx;
897        let local_decls = self.local_decls;
898        let mut place_ty: mir::PlaceTy = mir::Place::from(mir_place.local).ty(local_decls, tcx);
899        let var_id = self.translate_local(&mir_place.local).unwrap();
900        let mut place = self.locals.place_for_var(var_id);
901        for elem in mir_place.projection.as_slice() {
902            use mir::ProjectionElem::*;
903            if let TyKind::Error(msg) = place.ty().kind() {
904                return Err(Error {
905                    span,
906                    msg: msg.clone(),
907                });
908            }
909            let projected_place_ty = place_ty.projection_ty(tcx, *elem);
910            let next_place_ty = projected_place_ty.ty.sinto(&self.frontend_state);
911            let next_place_ty = self.translate_ty(span, &next_place_ty)?;
912            let proj_elem = match elem {
913                Deref => ProjectionElem::Deref,
914                PhantomDeref => {
915                    raise_error!(self, span, "unsupported phantom dereference in MIR place");
916                }
917                Field(index, _) => {
918                    let TyKind::Adt(tref) = place.ty().kind() else {
919                        raise_error!(
920                            self,
921                            span,
922                            "found unexpected type in field projection: {}",
923                            next_place_ty.with_ctx(&self.into_fmt())
924                        )
925                    };
926                    let field_id = self.translate_field_id(*index);
927                    match place_ty.ty.kind() {
928                        ty::Adt(adt_def, _) => {
929                            let variant = place_ty.variant_index;
930                            let variant_id = variant.map(|id| self.translate_variant_id(id));
931                            let generics = &tref.generics;
932                            match tref.as_builtin() {
933                                None => {
934                                    assert!(
935                                        ((adt_def.is_struct() || adt_def.is_union())
936                                            && variant.is_none())
937                                            || (adt_def.is_enum() && variant.is_some())
938                                    );
939                                    ProjectionElem::Field(variant_id, field_id)
940                                }
941                                Some(BuiltinAdt::Tuple) => {
942                                    assert!(generics.regions.is_empty());
943                                    assert!(variant.is_none());
944                                    assert!(generics.const_generics.is_empty());
945                                    ProjectionElem::Field(None, field_id)
946                                }
947                                Some(BuiltinAdt::Box)
948                                    if self.t_ctx.options.treat_box_as_builtin =>
949                                {
950                                    // Some sanity checks
951                                    assert!(generics.regions.is_empty());
952                                    assert!(
953                                        self.t_ctx.options.monomorphize_with_frontend
954                                            || generics.types.len() == 2
955                                    );
956                                    assert!(generics.const_generics.is_empty());
957                                    if field_id == FieldId::ZERO {
958                                        // We pretend the pointee field is a deref.
959                                        ProjectionElem::Deref
960                                    } else {
961                                        raise_error!(
962                                            self,
963                                            span,
964                                            "trying to access the allocator field from Box, \
965                                            but it is being treated as a builtin (without allocator)"
966                                        )
967                                    }
968                                }
969                                Some(BuiltinAdt::Box) => ProjectionElem::Field(None, field_id),
970                                Some(_) => {
971                                    raise_error!(self, span, "Unexpected field projection")
972                                }
973                            }
974                        }
975                        ty::Tuple(_types) => ProjectionElem::Field(None, field_id),
976                        // We get there when we access one of the fields of the state captured by a
977                        // closure.
978                        ty::Closure(..) => ProjectionElem::Field(None, field_id),
979                        _ => panic!(),
980                    }
981                }
982                Index(local) => {
983                    let offset =
984                        self.translate_operand(span, &mir::Operand::Copy((*local).into()))?;
985                    ProjectionElem::Index {
986                        offset: Box::new(offset),
987                        from_end: false,
988                    }
989                }
990                &ConstantIndex {
991                    offset, from_end, ..
992                } => {
993                    let offset =
994                        Operand::Const(IntegerValue::mk_usize(offset as u128).to_constant());
995                    ProjectionElem::Index {
996                        offset: Box::new(offset),
997                        from_end,
998                    }
999                }
1000                &Subslice { from, to, from_end } => {
1001                    let from = Operand::Const(IntegerValue::mk_usize(from as u128).to_constant());
1002                    let to = Operand::Const(IntegerValue::mk_usize(to as u128).to_constant());
1003                    ProjectionElem::Subslice {
1004                        from: Box::new(from),
1005                        to: Box::new(to),
1006                        from_end,
1007                    }
1008                }
1009                OpaqueCast(..) => {
1010                    raise_error!(self, span, "Unexpected ProjectionElem::OpaqueCast");
1011                }
1012                Downcast { .. } => {
1013                    // We keep the same `Place`, the variant is tracked in the `PlaceTy` and we can
1014                    // access it next loop iteration.
1015                    place_ty = projected_place_ty;
1016                    continue;
1017                }
1018                UnwrapUnsafeBinder { .. } => {
1019                    raise_error!(self, span, "unsupported feature: unsafe binders");
1020                }
1021            };
1022            place = place.project(proj_elem, next_place_ty);
1023            place_ty = projected_place_ty;
1024        }
1025        Ok(place)
1026    }
1027
1028    /// Translate an operand
1029    fn translate_operand(
1030        &mut self,
1031        span: Span,
1032        operand: &mir::Operand<'tcx>,
1033    ) -> Result<Operand, Error> {
1034        Ok(match operand {
1035            mir::Operand::Copy(place) => {
1036                let ty = place.ty(self.local_decls, self.tcx).ty;
1037                let p = self.translate_place(span, place)?;
1038                if let Some(proof) = front::solve_copy(&self.frontend_state, ty) {
1039                    let proof = self.translate_trait_proof(span, &proof)?.no_bound_vars();
1040                    Operand::Copy(p, proof)
1041                } else {
1042                    // Runtime MIR replaces `CopyForDeref` with `Copy`, so we may end up here for
1043                    // non-`Copy` types such as mutable references.
1044                    Operand::Read(p)
1045                }
1046            }
1047            mir::Operand::Move(place) => {
1048                let p = self.translate_place(span, place)?;
1049                Operand::Move(p)
1050            }
1051            mir::Operand::Constant(const_op) => {
1052                let annotated_ty = if let Some(base) = const_op.user_ty {
1053                    self.user_type_annotations.translate_annotation(base)
1054                } else {
1055                    None
1056                };
1057                let const_op = self.catch_sinto(span, &const_op)?;
1058                let operand = match &const_op.kind {
1059                    front::ConstOperandKind::Value(constant) => {
1060                        let constant = self.translate_constant_expr(span, constant)?;
1061                        Operand::Const(constant)
1062                    }
1063                    front::ConstOperandKind::Promoted(item) => {
1064                        // A promoted constant that could not be evaluated.
1065                        let global_ref = self.translate_global_decl_ref(span, item)?;
1066                        let constant = ConstantExpr::new(
1067                            ConstantExprKind::Global(global_ref),
1068                            self.translate_ty(span, &const_op.ty)?,
1069                        );
1070                        Operand::Const(constant)
1071                    }
1072                };
1073                if let Some(annotated_ty) = annotated_ty
1074                    && annotated_ty != *operand.ty()
1075                {
1076                    if let TyKind::FnDef(fn_ptr) = annotated_ty.kind() {
1077                        // The function type is a singleton hence determines the value uniquely.
1078                        // Prefer using the annotated type to preserve explicit turbofishing
1079                        // choices.
1080                        let fn_ptr = self.erase_region_binder(fn_ptr.clone());
1081                        Operand::Const(ConstantExpr::new(
1082                            ConstantExprKind::FnDef(fn_ptr),
1083                            annotated_ty,
1084                        ))
1085                    } else {
1086                        // For other constants, add the type annotation as a separate constraint.
1087                        let place = self.fresh_var(None, operand.ty().clone());
1088                        self.insert_assn_stmt(place.clone(), Rvalue::Use(operand, WithRetag::No));
1089                        self.statements.push(Statement::new(
1090                            span,
1091                            StatementKind::Borrowck(BorrowckStatement::SetType(
1092                                PlaceTypeConstraint {
1093                                    place: place.clone(),
1094                                    ty: annotated_ty,
1095                                    variance: Variance::Invariant,
1096                                },
1097                            )),
1098                        ));
1099                        Operand::Move(place)
1100                    }
1101                } else {
1102                    operand
1103                }
1104            }
1105            mir::Operand::RuntimeChecks(check) => {
1106                let op = match check {
1107                    mir::RuntimeChecks::UbChecks => NullOp::UbChecks,
1108                    mir::RuntimeChecks::OverflowChecks => NullOp::OverflowChecks,
1109                    mir::RuntimeChecks::ContractChecks => NullOp::ContractChecks,
1110                };
1111                let local = self.fresh_var(None, Ty::mk_bool());
1112                self.insert_assn_stmt(local.clone(), Rvalue::NullaryOp(op));
1113                Operand::Move(local)
1114            }
1115        })
1116    }
1117
1118    /// Translate an rvalue
1119    fn translate_mir_rvalue(
1120        &mut self,
1121        span: Span,
1122        rvalue: &mir::Rvalue<'tcx>,
1123        tgt_ty: &Ty,
1124    ) -> Result<Rvalue, Error> {
1125        match rvalue {
1126            mir::Rvalue::Use(operand, retag) => {
1127                let retag = match retag {
1128                    mir::WithRetag::Yes => WithRetag::Yes,
1129                    mir::WithRetag::No => WithRetag::No,
1130                };
1131                Ok(Rvalue::Use(self.translate_operand(span, operand)?, retag))
1132            }
1133            mir::Rvalue::CopyForDeref(place) => {
1134                // A read of a pointer, used only for derefing it. The pointer need not be `Copy`.
1135                let place = self.translate_place(span, place)?;
1136                Ok(Rvalue::Use(Operand::Read(place), WithRetag::No))
1137            }
1138            mir::Rvalue::Repeat(operand, _) => {
1139                let copy_proof = {
1140                    let rust_ty = operand.ty(self.local_decls, self.tcx);
1141                    front::solve_copy(&self.frontend_state, rust_ty)
1142                };
1143                let operand = self.translate_operand(span, operand)?;
1144                let TyKind::Array(elem_ty, len, ty_is_sized) = tgt_ty.kind() else {
1145                    raise_error!(self, span, "array repeat has non-array type")
1146                };
1147                if let Some(copy_proof) = copy_proof {
1148                    let elem_is_copy = self
1149                        .translate_trait_proof(span, &copy_proof)?
1150                        .no_bound_vars();
1151                    Ok(Rvalue::Repeat {
1152                        operand,
1153                        count: len.clone(),
1154                        elem_is_copy,
1155                        elem_is_sized: ty_is_sized.clone(),
1156                    })
1157                } else if let Operand::Const(value) = operand {
1158                    let value = ConstantExpr::new(
1159                        ConstantExprKind::Repeat {
1160                            value,
1161                            count: len.clone(),
1162                            value_is_sized: ty_is_sized.clone(),
1163                        },
1164                        tgt_ty.clone(),
1165                    );
1166                    Ok(Rvalue::Use(Operand::Const(value), WithRetag::Yes))
1167                } else if len.as_usize_literal() == Some(1) {
1168                    // A single element can be moved into the array without being `Copy`.
1169                    Ok(Rvalue::Aggregate(
1170                        AggregateKind::Array(elem_ty.clone(), len.clone(), ty_is_sized.clone()),
1171                        vec![operand],
1172                    ))
1173                } else {
1174                    raise_error!(
1175                        self,
1176                        span,
1177                        "Rvalue::Repeat found with an operand that is neither constant nor `Copy`"
1178                    )
1179                }
1180            }
1181            mir::Rvalue::Ref(_region, borrow_kind, place) => {
1182                let place = self.translate_place(span, place)?;
1183                let borrow_kind = self.translate_borrow_kind(span, *borrow_kind)?;
1184                Ok(Rvalue::Ref {
1185                    place,
1186                    kind: borrow_kind,
1187                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
1188                    ptr_metadata: Self::missing_ptr_metadata(),
1189                })
1190            }
1191            mir::Rvalue::RawPtr(mtbl, place) => {
1192                let mtbl = match mtbl {
1193                    mir::RawPtrKind::Mut => RefKind::Mut,
1194                    mir::RawPtrKind::Const => RefKind::Shared,
1195                    mir::RawPtrKind::FakeForPtrMetadata => RefKind::Shared,
1196                };
1197                let place = self.translate_place(span, place)?;
1198                Ok(Rvalue::RawPtr {
1199                    place,
1200                    kind: mtbl,
1201                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
1202                    ptr_metadata: Self::missing_ptr_metadata(),
1203                })
1204            }
1205            mir::Rvalue::Cast(cast_kind, mir_operand, rust_tgt_ty) => {
1206                let op_ty = mir_operand.ty(self.local_decls, self.tcx);
1207                let tgt_ty = self.translate_rustc_ty(span, rust_tgt_ty)?;
1208
1209                // Translate the operand
1210                let mut operand = self.translate_operand(span, mir_operand)?;
1211
1212                let mut cast_kind = match cast_kind {
1213                    mir::CastKind::IntToInt
1214                    | mir::CastKind::IntToFloat
1215                    | mir::CastKind::FloatToInt
1216                    | mir::CastKind::FloatToFloat => {
1217                        let tgt_ty = *tgt_ty.kind().as_scalar().unwrap();
1218                        CastKind::Scalar(tgt_ty)
1219                    }
1220                    mir::CastKind::PtrToPtr
1221                    | mir::CastKind::PointerCoercion(
1222                        ty::adjustment::PointerCoercion::MutToConstPointer,
1223                        ..,
1224                    )
1225                    | mir::CastKind::PointerCoercion(
1226                        ty::adjustment::PointerCoercion::ArrayToPointer,
1227                        ..,
1228                    )
1229                    | mir::CastKind::FnPtrToPtr => CastKind::RawPtr(tgt_ty.clone()),
1230
1231                    mir::CastKind::PointerExposeProvenance => {
1232                        let tgt_ty = *tgt_ty.kind().as_scalar().unwrap().as_integer().unwrap();
1233                        CastKind::PtrExposeProvenance(tgt_ty)
1234                    }
1235                    mir::CastKind::PointerWithExposedProvenance => {
1236                        CastKind::PtrWithExposedProvenance(tgt_ty.clone())
1237                    }
1238                    mir::CastKind::PointerCoercion(
1239                        ty::adjustment::PointerCoercion::ClosureFnPointer(_),
1240                        ..,
1241                    ) => {
1242                        let frontend_op_ty: front::Ty = self.catch_sinto(span, &op_ty)?;
1243                        // We model casts of closures to function pointers by generating a new
1244                        // function item without the closure's state, that calls the actual closure.
1245                        let front::TyKind::Closure(closure) = frontend_op_ty.kind() else {
1246                            unreachable!("Non-closure type in PointerCoercion::ClosureFnPointer");
1247                        };
1248                        let fn_ref: RegionBinder<FunDeclRef> =
1249                            self.translate_stateless_closure_as_fn_ref(span, closure)?;
1250                        let fn_ptr_bound: RegionBinder<FnPtr> = fn_ref.map(FunDeclRef::into);
1251                        let fn_ptr: FnPtr = self.erase_region_binder(fn_ptr_bound.clone());
1252                        let src_ty = TyKind::FnDef(fn_ptr_bound).into_ty();
1253                        operand = Operand::Const(ConstantExpr::new(
1254                            ConstantExprKind::FnDef(fn_ptr),
1255                            src_ty.clone(),
1256                        ));
1257                        CastKind::FnDefToFnPtr
1258                    }
1259                    mir::CastKind::PointerCoercion(
1260                        ty::adjustment::PointerCoercion::ReifyFnPointer(_),
1261                        ..,
1262                    ) => CastKind::FnDefToFnPtr,
1263                    mir::CastKind::PointerCoercion(
1264                        ty::adjustment::PointerCoercion::UnsafeFnPointer,
1265                        ..,
1266                    ) => CastKind::FnPtrToUnsafe,
1267                    mir::CastKind::Transmute => CastKind::Transmute(tgt_ty.clone()),
1268                    mir::CastKind::BoxDerefTransmute => CastKind::BoxDerefTransmute(tgt_ty.clone()),
1269                    mir::CastKind::Subtype => CastKind::Subtype(tgt_ty.clone()),
1270                    mir::CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, ..) => {
1271                        let (path, meta) = front::compute_unsizing_metadata(
1272                            &self.frontend_state,
1273                            op_ty,
1274                            *rust_tgt_ty,
1275                        );
1276                        let meta = self.translate_unsizing_metadata(span, &meta)?;
1277                        CastKind::Unsize(tgt_ty.clone(), meta, self.translate_metadata_path(&path))
1278                    }
1279                };
1280
1281                // We're more precise than rustc: we separate "cast to fn ptr" and "safety cast",
1282                // so we reconstruct the distinction here.
1283                if let CastKind::FnDefToFnPtr = cast_kind {
1284                    let rustc_sig = match op_ty.kind() {
1285                        ty::TyKind::FnDef(..) => op_ty.fn_sig(self.tcx),
1286                        ty::TyKind::Closure(_, args) => {
1287                            front::closure_sig(self.tcx, args.as_closure())
1288                        }
1289                        _ => unreachable!("Expected a function definition or closure"),
1290                    };
1291                    let rustc_fn_ptr = ty::Ty::new_fn_ptr(self.tcx, rustc_sig);
1292                    let intermediate_ty = self.translate_rustc_ty(span, &rustc_fn_ptr)?;
1293                    let (TyKind::FnPtr(interm), TyKind::FnPtr(target)) =
1294                        (intermediate_ty.kind(), tgt_ty.kind())
1295                    else {
1296                        raise_error!(self, span, "Expected function pointers in fn pointer cast")
1297                    };
1298                    if interm.skip_binder.is_unsafe != target.skip_binder.is_unsafe {
1299                        let local = self.rval_to_place(
1300                            Rvalue::UnaryOp(UnOp::Cast(CastKind::FnDefToFnPtr), operand),
1301                            intermediate_ty.clone(),
1302                        );
1303                        operand = Operand::Move(local);
1304                        cast_kind = CastKind::FnPtrToUnsafe;
1305                    }
1306                }
1307
1308                Ok(Rvalue::UnaryOp(UnOp::Cast(cast_kind), operand))
1309            }
1310            // `ptr.offset(n)` becomes `&raw (*ptr).offset(n)`.
1311            mir::Rvalue::BinaryOp(mir::BinOp::Offset, (ptr, n)) => {
1312                let TyKind::RawPtr(pointee, kind) = tgt_ty.kind() else {
1313                    raise_error!(self, span, "`Offset` on a non-raw-pointer type")
1314                };
1315                let rust_pointee = ptr
1316                    .ty(self.local_decls, self.tcx)
1317                    .builtin_deref(true)
1318                    .unwrap();
1319                let pointee_is_sized = self.translate_sized_proof(span, rust_pointee)?;
1320                let ptr = match self.translate_operand(span, ptr)? {
1321                    Operand::Copy(p, _) | Operand::Read(p) | Operand::Move(p) => p,
1322                    op @ Operand::Const(_) => {
1323                        let ty = op.ty().clone();
1324                        self.rval_to_place(Rvalue::Use(op, WithRetag::No), ty)
1325                    }
1326                };
1327                let n = self.translate_operand(span, n)?;
1328                // MIR's `Offset` is UB if it goes out of bounds.
1329                let offset = self.offset_projection(
1330                    n,
1331                    Some(pointee),
1332                    true,
1333                    pointee.clone(),
1334                    pointee_is_sized,
1335                );
1336                let place = ptr.deref().project(offset, pointee.clone());
1337                Ok(Rvalue::RawPtr {
1338                    place,
1339                    kind: *kind,
1340                    ptr_metadata: Operand::mk_const_unit(),
1341                })
1342            }
1343            mir::Rvalue::BinaryOp(binop, (left, right)) => Ok(Rvalue::BinaryOp(
1344                self.translate_binaryop_kind(span, *binop)?,
1345                self.translate_operand(span, left)?,
1346                self.translate_operand(span, right)?,
1347            )),
1348            mir::Rvalue::UnaryOp(unop, operand) => {
1349                let operand_ty = operand.ty(self.local_decls, self.tcx);
1350                let operand = self.translate_operand(span, operand)?;
1351                let unop = match unop {
1352                    mir::UnOp::Not => UnOp::Not,
1353                    mir::UnOp::Neg => UnOp::Neg(OverflowMode::Wrap),
1354                    mir::UnOp::PtrMetadata => match operand {
1355                        Operand::Copy(p, _) | Operand::Read(p) | Operand::Move(p) => {
1356                            let metadata_ty = unop.ty(self.tcx, operand_ty);
1357                            let proof = front::solve_copy(&self.frontend_state, metadata_ty)
1358                                .expect("pointer metadata is always Copy");
1359                            let proof = self.translate_trait_proof(span, &proof)?.no_bound_vars();
1360                            return Ok(Rvalue::Use(
1361                                Operand::Copy(
1362                                    p.project(ProjectionElem::PtrMetadata, tgt_ty.clone()),
1363                                    proof,
1364                                ),
1365                                WithRetag::No,
1366                            ));
1367                        }
1368                        Operand::Const(_) => {
1369                            panic!("unexpected metadata operand")
1370                        }
1371                    },
1372                };
1373                Ok(Rvalue::UnaryOp(unop, operand))
1374            }
1375            mir::Rvalue::Discriminant(place) => {
1376                let place = self.translate_place(span, place)?;
1377                Ok(Rvalue::Discriminant(place))
1378            }
1379            mir::Rvalue::Aggregate(aggregate_kind, operands) => {
1380                // It seems this instruction is not present in certain passes:
1381                // for example, it seems it is not used in optimized MIR, where
1382                // ADT initialization is split into several instructions, for
1383                // instance:
1384                // ```
1385                // p = Pair { x:xv, y:yv };
1386                // ```
1387                // Might become:
1388                // ```
1389                // p.x = x;
1390                // p.y = yv;
1391                // ```
1392
1393                // First translate the operands
1394                let operands_t: Vec<Operand> = operands
1395                    .iter()
1396                    .map(|op| self.translate_operand(span, op))
1397                    .try_collect()?;
1398                match aggregate_kind {
1399                    mir::AggregateKind::Array(ty) => {
1400                        let t_ty = self.translate_rustc_ty(span, ty)?;
1401                        let len = ConstantExpr::mk_usize(operands_t.len() as u128);
1402                        let TyKind::Array(_, _, ty_is_sized) = tgt_ty.kind() else {
1403                            raise_error!(self, span, "array aggregate has non-array type")
1404                        };
1405                        if operands_t.len() >= 2 && operands_t.iter().all(Operand::is_const) {
1406                            let fields =
1407                                operands_t.iter().map(|operand| operand.as_const().unwrap());
1408                            if let Ok(field) = fields.dedup().exactly_one()
1409                                && let Some(copy_proof) =
1410                                    front::solve_copy(&self.frontend_state, *ty)
1411                            {
1412                                let ty_is_copy = self
1413                                    .translate_trait_proof(span, &copy_proof)?
1414                                    .no_bound_vars();
1415                                return Ok(Rvalue::Repeat {
1416                                    operand: Operand::Const(field.clone()),
1417                                    count: len,
1418                                    elem_is_sized: ty_is_sized.clone(),
1419                                    elem_is_copy: ty_is_copy,
1420                                });
1421                            }
1422                        }
1423                        Ok(Rvalue::Aggregate(
1424                            AggregateKind::Array(t_ty, len, ty_is_sized.clone()),
1425                            operands_t,
1426                        ))
1427                    }
1428                    mir::AggregateKind::Tuple => {
1429                        let tys = operands.iter().map(|op| op.ty(self.local_decls, self.tcx));
1430                        let ty = ty::Ty::new_tup_from_iter(self.tcx, tys);
1431                        let ty = self.translate_rustc_ty(span, &ty)?;
1432                        let tref = ty.as_adt().unwrap().clone();
1433                        Ok(Rvalue::Aggregate(
1434                            AggregateKind::Adt(tref, None, None),
1435                            operands_t,
1436                        ))
1437                    }
1438                    mir::AggregateKind::Adt(
1439                        def_id,
1440                        variant_idx,
1441                        generics,
1442                        user_ty,
1443                        field_index,
1444                    ) => {
1445                        use ty::AdtKind;
1446                        trace!("{:?}", rvalue);
1447
1448                        let adt_kind = self.tcx.adt_def(*def_id).adt_kind();
1449                        let tref = if let Some(user_ty) = *user_ty
1450                            && let Some(ty) =
1451                                self.user_type_annotations.translate_annotation(user_ty)
1452                        {
1453                            // Use the type annotation if there is one.
1454                            let TyKind::Adt(tref) = ty.kind() else {
1455                                raise_error!(self, span, "aggregate annotation has non-ADT type");
1456                            };
1457                            tref.clone()
1458                        } else {
1459                            let item =
1460                                front::translate_item_ref(&self.frontend_state, *def_id, *generics);
1461                            self.translate_type_decl_ref(span, &item)?
1462                        };
1463                        let variant_id = match adt_kind {
1464                            AdtKind::Struct | AdtKind::Union => None,
1465                            AdtKind::Enum => Some(self.translate_variant_id(*variant_idx)),
1466                        };
1467                        let field_id = match adt_kind {
1468                            AdtKind::Struct | AdtKind::Enum => None,
1469                            AdtKind::Union => Some(self.translate_field_id(field_index.unwrap())),
1470                        };
1471
1472                        let akind = AggregateKind::Adt(tref, variant_id, field_id);
1473                        Ok(Rvalue::Aggregate(akind, operands_t))
1474                    }
1475                    mir::AggregateKind::Closure(def_id, generics) => {
1476                        let item =
1477                            front::translate_item_ref(&self.frontend_state, *def_id, *generics);
1478                        let tref = self.translate_closure_type_ref(span, &item)?;
1479                        let akind = AggregateKind::Adt(tref, None, None);
1480                        Ok(Rvalue::Aggregate(akind, operands_t))
1481                    }
1482                    mir::AggregateKind::RawPtr(ty, mutability) => {
1483                        let t_ty = self.translate_rustc_ty(span, ty)?;
1484                        let mutability = if mutability.is_mut() {
1485                            RefKind::Mut
1486                        } else {
1487                            RefKind::Shared
1488                        };
1489
1490                        let akind = AggregateKind::RawPtr(t_ty, mutability);
1491
1492                        Ok(Rvalue::Aggregate(akind, operands_t))
1493                    }
1494                    mir::AggregateKind::Coroutine(..)
1495                    | mir::AggregateKind::CoroutineClosure(..) => {
1496                        raise_error!(self, span, "Coroutines are not supported");
1497                    }
1498                }
1499            }
1500            mir::Rvalue::ThreadLocalRef(def_id) => self.translate_thread_local_ref(span, *def_id),
1501            mir::Rvalue::WrapUnsafeBinder { .. } => {
1502                raise_error!(
1503                    self,
1504                    span,
1505                    "charon does not support unsafe lifetime binders"
1506                );
1507            }
1508            mir::Rvalue::Reborrow(..) => {
1509                raise_error!(
1510                    self,
1511                    span,
1512                    "charon does not support reborrow rvalues (for Reborrow traits)"
1513                );
1514            }
1515        }
1516    }
1517
1518    /// Translate a statement.
1519    fn translate_statement(
1520        &mut self,
1521        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
1522        statement: &mir::Statement<'tcx>,
1523    ) -> Result<(), Error> {
1524        trace!("About to translate statement (MIR) {:?}", statement);
1525        let span = self.translate_span_from_source_info(source_scopes, &statement.source_info);
1526
1527        self.span = span;
1528        let kind: Option<StatementKind> = match &statement.kind {
1529            mir::StatementKind::Assign((
1530                place,
1531                mir::Rvalue::BinaryOp(
1532                    binop @ (mir::BinOp::AddWithOverflow
1533                    | mir::BinOp::SubWithOverflow
1534                    | mir::BinOp::MulWithOverflow),
1535                    (left, right),
1536                ),
1537            )) => {
1538                // Translate these binops to intrinsic calls to make binops easier to typecheck:
1539                // their return type is a tuple, which we monomorphize hence it's hard to compute
1540                // ourselves.
1541                let name = match binop {
1542                    mir::BinOp::AddWithOverflow => sym::add_with_overflow,
1543                    mir::BinOp::SubWithOverflow => sym::sub_with_overflow,
1544                    mir::BinOp::MulWithOverflow => sym::mul_with_overflow,
1545                    _ => unreachable!(),
1546                };
1547                let ty = left.ty(self.local_decls, self.tcx);
1548                let generic_args = self.tcx.mk_args(&[ty.into()]);
1549                let dest = self.translate_place(span, place)?;
1550                let left = self.translate_operand(span, left)?;
1551                let right = self.translate_operand(span, right)?;
1552                self.translate_intrinsic_call(span, dest, name, generic_args, vec![left, right])?;
1553                None
1554            }
1555            mir::StatementKind::Assign((place, rvalue)) => {
1556                let t_place = self.translate_place(span, place)?;
1557                let t_rvalue = self.translate_mir_rvalue(span, rvalue, t_place.ty())?;
1558                Some(StatementKind::Assign(t_place, t_rvalue))
1559            }
1560            mir::StatementKind::SetDiscriminant {
1561                place,
1562                variant_index,
1563            } => {
1564                let t_place = self.translate_place(span, place)?;
1565                let variant_id = self.translate_variant_id(*variant_index);
1566                Some(StatementKind::SetDiscriminant(t_place, variant_id))
1567            }
1568            mir::StatementKind::StorageLive(local) => {
1569                let var_id = self.translate_local(local).unwrap();
1570                Some(StatementKind::StorageLive(var_id))
1571            }
1572            mir::StatementKind::StorageDead(local) => {
1573                let var_id = self.translate_local(local).unwrap();
1574                Some(StatementKind::StorageDead(var_id))
1575            }
1576            mir::StatementKind::Intrinsic(mir::NonDivergingIntrinsic::Assume(op)) => {
1577                let op = self.translate_operand(span, op)?;
1578                let dest = self.locals.new_var(None, Ty::mk_unit());
1579                self.translate_intrinsic_call(
1580                    span,
1581                    dest,
1582                    sym::assume,
1583                    ty::GenericArgs::empty(),
1584                    vec![op],
1585                )?;
1586                None
1587            }
1588            mir::StatementKind::Intrinsic(mir::NonDivergingIntrinsic::CopyNonOverlapping(
1589                mir::CopyNonOverlapping { src, dst, count },
1590            )) => {
1591                let pointee_ty = src
1592                    .ty(self.local_decls, self.tcx)
1593                    .builtin_deref(true)
1594                    .unwrap();
1595                let generic_args = self.tcx.mk_args(&[pointee_ty.into()]);
1596                let src = self.translate_operand(span, src)?;
1597                let dst = self.translate_operand(span, dst)?;
1598                let count = self.translate_operand(span, count)?;
1599                let dest = self.locals.new_var(None, Ty::mk_unit());
1600                self.translate_intrinsic_call(
1601                    span,
1602                    dest,
1603                    sym::copy_nonoverlapping,
1604                    generic_args,
1605                    vec![src, dst, count],
1606                )?;
1607                None
1608            }
1609            mir::StatementKind::PlaceMention(place) => {
1610                let place = self.translate_place(span, place)?;
1611                // We only translate this for places with projections, as
1612                // no UB can arise from simply mentioning a local variable.
1613                if place.is_local() {
1614                    None
1615                } else {
1616                    Some(StatementKind::PlaceMention(place))
1617                }
1618            }
1619            mir::StatementKind::FakeRead((_, place)) => {
1620                let place = self.translate_place(span, place)?;
1621                Some(StatementKind::Borrowck(BorrowckStatement::FakeRead(place)))
1622            }
1623            mir::StatementKind::AscribeUserType((place, user_ty), variance) => {
1624                let variance = match variance {
1625                    ty::Variance::Covariant => Variance::Covariant,
1626                    ty::Variance::Invariant => Variance::Invariant,
1627                    ty::Variance::Contravariant => Variance::Contravariant,
1628                    // Does nothing so we discard it.
1629                    ty::Variance::Bivariant => return Ok(()),
1630                };
1631                let place = self.translate_place(span, place)?;
1632                let ty = self
1633                    .user_type_annotations
1634                    .translate_projected_annotation(user_ty);
1635                // This is a statement for practical impl reasons, but semantically this constrains
1636                // the local throughout the body.
1637                let local_id = place.local_id().expect("MIR ascription without a local");
1638                self.locals[local_id]
1639                    .borrowck_constraints
1640                    .push(PlaceTypeConstraint {
1641                        place,
1642                        ty,
1643                        variance,
1644                    });
1645                None
1646            }
1647            // Used for coverage instrumentation.
1648            mir::StatementKind::Coverage(_) => None,
1649            // Used in the interpreter to check that const code doesn't run for too long or even
1650            // indefinitely.
1651            mir::StatementKind::ConstEvalCounter => None,
1652            // Semantically equivalent to `Nop`, used only for rustc lints.
1653            mir::StatementKind::BackwardIncompatibleDropHint { .. } => None,
1654            mir::StatementKind::Nop => None,
1655        };
1656
1657        let Some(kind) = kind else {
1658            return Ok(());
1659        };
1660        self.statements.push(Statement::new(span, kind));
1661        Ok(())
1662    }
1663
1664    /// Translate a call to a non-diverging intrinsic.
1665    fn translate_intrinsic_call(
1666        &mut self,
1667        span: Span,
1668        dest: Place,
1669        name: Symbol,
1670        generic_args: ty::GenericArgs<'tcx>,
1671        args: Vec<Operand>,
1672    ) -> Result<(), Error> {
1673        // Sadly rustc doesn't expose a Symbol -> DefId map for intrinsics.
1674        let def_id = match self.t_ctx.intrinsic_def_ids.get(&name) {
1675            Some(&def_id) => def_id,
1676            None => {
1677                let path = NamePattern::parse(&format!("core::intrinsics::{name}")).unwrap();
1678                let def_id = self.resolve_single_path(span, &path)?;
1679                self.t_ctx.intrinsic_def_ids.insert(name, def_id);
1680                def_id
1681            }
1682        };
1683        assert!(self.tcx.is_rustc_intrinsic(def_id, name));
1684        let item = front::ItemRef::translate(self.frontend_state_with_id(), def_id, generic_args);
1685        let func = FnOperand::Regular(self.translate_fn_ptr(span, &item)?);
1686        self.push_nounwind_call(
1687            span,
1688            dest,
1689            Call {
1690                func,
1691                args,
1692                safety: CallSafety::Inherit,
1693            },
1694        );
1695        Ok(())
1696    }
1697
1698    /// Translate a terminator
1699    fn translate_terminator(
1700        mut self,
1701        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
1702        terminator: &mir::Terminator<'tcx>,
1703    ) -> Result<(), Error> {
1704        trace!("About to translate terminator (MIR) {:?}", terminator);
1705        let span = self.translate_span_from_source_info(source_scopes, &terminator.source_info);
1706
1707        // Translate the terminator
1708        self.span = span;
1709        use mir::TerminatorKind;
1710        let kind: ullbc_ast::TerminatorKind = match &terminator.kind {
1711            TerminatorKind::Goto {
1712                target,
1713                loop_hint_attrs: _,
1714            } => {
1715                let target = self.translate_basic_block_id(*target);
1716                ullbc_ast::TerminatorKind::Goto { target }
1717            }
1718            TerminatorKind::SwitchInt { discr, targets, .. } => {
1719                let discr = self.translate_operand(span, discr)?;
1720                let (data, branches) = self.translate_switch_targets(span, discr, targets)?;
1721                ullbc_ast::TerminatorKind::Switch { data, branches }
1722            }
1723            TerminatorKind::UnwindResume => ullbc_ast::TerminatorKind::UnwindResume,
1724            TerminatorKind::UnwindTerminate(reason) => {
1725                self.translate_unwind_terminate(span, *reason)?
1726            }
1727            TerminatorKind::Return => ullbc_ast::TerminatorKind::Return,
1728            // A MIR `Unreachable` terminator indicates undefined behavior of the rust abstract
1729            // machine.
1730            TerminatorKind::Unreachable => ullbc_ast::TerminatorKind::UndefinedBehavior,
1731            TerminatorKind::Drop {
1732                place,
1733                target,
1734                unwind,
1735                ..
1736            } => self.translate_drop(span, place, target, unwind)?,
1737            TerminatorKind::Call {
1738                func,
1739                args,
1740                destination,
1741                target,
1742                unwind,
1743                ..
1744            } => self.translate_function_call(span, func, args, destination, target, unwind)?,
1745            TerminatorKind::Assert {
1746                cond,
1747                expected,
1748                msg,
1749                target,
1750                unwind,
1751            } => {
1752                let on_unwind = self.translate_unwind_action(span, unwind)?;
1753                let kind = self.translate_assert_kind(span, msg)?;
1754                let (lang_item, args) = match &kind {
1755                    BuiltinAssertKind::BoundsCheck { len, index } => {
1756                        (LangItem::PanicBoundsCheck, vec![index.clone(), len.clone()])
1757                    }
1758                    BuiltinAssertKind::MisalignedPointerDereference { required, found } => (
1759                        LangItem::PanicMisalignedPointerDereference,
1760                        vec![required.clone(), found.clone()],
1761                    ),
1762                    BuiltinAssertKind::InvalidEnumConstruction(source) => {
1763                        (msg.panic_function(), vec![source.clone()])
1764                    }
1765                    _ => (msg.panic_function(), vec![]),
1766                };
1767                let def_id = self
1768                    .tcx
1769                    .require_lang_item(lang_item, terminator.source_info.span);
1770                let item = front::translate_item_ref(
1771                    &self.frontend_state,
1772                    def_id,
1773                    ty::GenericArgs::empty(),
1774                );
1775                let func = self.translate_fn_ptr(span, &item)?;
1776                let assert = Assert {
1777                    cond: self.translate_operand(span, cond)?,
1778                    expected: *expected,
1779                    check_kind: Some(kind),
1780                    call: Box::new(Call {
1781                        func: FnOperand::Regular(func),
1782                        args,
1783                        safety: CallSafety::Inherit,
1784                    }),
1785                };
1786                let target = self.translate_basic_block_id(*target);
1787                ullbc_ast::TerminatorKind::Assert {
1788                    assert,
1789                    target,
1790                    on_unwind,
1791                }
1792            }
1793            TerminatorKind::FalseEdge {
1794                real_target,
1795                imaginary_target: _,
1796            } => {
1797                // False edges are used to make the borrow checker a bit conservative.
1798                // We translate them as Gotos.
1799                // Also note that they are used in some passes, and not in some others
1800                // (they are present in mir_promoted, but not mir_optimized).
1801                let target = self.translate_basic_block_id(*real_target);
1802                ullbc_ast::TerminatorKind::Goto { target }
1803            }
1804            TerminatorKind::FalseUnwind {
1805                real_target,
1806                unwind: _,
1807            } => {
1808                // We consider this to be a goto
1809                let target = self.translate_basic_block_id(*real_target);
1810                ullbc_ast::TerminatorKind::Goto { target }
1811            }
1812            TerminatorKind::InlineAsm {
1813                asm_macro,
1814                template,
1815                operands,
1816                options,
1817                targets,
1818                unwind,
1819                ..
1820            } => {
1821                use rustc_ast::ast::InlineAsmOptions as O;
1822                let kind = match asm_macro {
1823                    mir::InlineAsmMacro::Asm => AsmKind::Asm,
1824                    mir::InlineAsmMacro::NakedAsm => AsmKind::NakedAsm,
1825                };
1826                let options = AsmOptions {
1827                    pure: options.contains(O::PURE),
1828                    nomem: options.contains(O::NOMEM),
1829                    readonly: options.contains(O::READONLY),
1830                    preserves_flags: options.contains(O::PRESERVES_FLAGS),
1831                    noreturn: options.contains(O::NORETURN),
1832                    nostack: options.contains(O::NOSTACK),
1833                    att_syntax: options.contains(O::ATT_SYNTAX),
1834                    may_unwind: options.contains(O::MAY_UNWIND),
1835                };
1836                let template = template
1837                    .iter()
1838                    .map(|piece| match piece {
1839                        rustc_ast::ast::InlineAsmTemplatePiece::String(text) => {
1840                            AsmTemplatePiece::Text(text.to_string().into())
1841                        }
1842                        rustc_ast::ast::InlineAsmTemplatePiece::Placeholder {
1843                            operand_idx,
1844                            modifier,
1845                            span,
1846                        } => AsmTemplatePiece::Placeholder {
1847                            operand_id: AsmOperandId::from_usize(*operand_idx),
1848                            modifier: *modifier,
1849                            span: self.translate_span(span),
1850                        },
1851                    })
1852                    .collect();
1853                let has_fallthrough = matches!(kind, AsmKind::Asm) && !options.noreturn;
1854                let translate_reg = |reg: &rustc_target::asm::InlineAsmRegOrRegClass| match reg {
1855                    rustc_target::asm::InlineAsmRegOrRegClass::Reg(reg) => {
1856                        AsmRegister::Explicit(reg.name().to_string().into())
1857                    }
1858                    rustc_target::asm::InlineAsmRegOrRegClass::RegClass(class) => {
1859                        AsmRegister::Class(class.name().to_string().into())
1860                    }
1861                };
1862                let operands = operands
1863                    .iter()
1864                    .map(|operand| {
1865                        Ok(match operand {
1866                            mir::InlineAsmOperand::In { reg, value } => AsmOperand::In {
1867                                reg: translate_reg(reg),
1868                                value: self.translate_operand(span, value)?,
1869                            },
1870                            mir::InlineAsmOperand::Out { reg, late, place } => AsmOperand::Out {
1871                                reg: translate_reg(reg),
1872                                late: *late,
1873                                place: place
1874                                    .as_ref()
1875                                    .map(|place| self.translate_place(span, place))
1876                                    .transpose()?,
1877                            },
1878                            mir::InlineAsmOperand::InOut {
1879                                reg,
1880                                late,
1881                                in_value,
1882                                out_place,
1883                            } => AsmOperand::InOut {
1884                                reg: translate_reg(reg),
1885                                late: *late,
1886                                in_value: self.translate_operand(span, in_value)?,
1887                                out_place: out_place
1888                                    .as_ref()
1889                                    .map(|place| self.translate_place(span, place))
1890                                    .transpose()?,
1891                            },
1892                            mir::InlineAsmOperand::Const { value } => {
1893                                let Operand::Const(value) = self.translate_operand(
1894                                    span,
1895                                    &mir::Operand::Constant(value.clone()),
1896                                )?
1897                                else {
1898                                    unreachable!("inline asm const operand is not a constant")
1899                                };
1900                                AsmOperand::Const(value)
1901                            }
1902                            mir::InlineAsmOperand::SymFn { value } => {
1903                                let Operand::Const(value) = self.translate_operand(
1904                                    span,
1905                                    &mir::Operand::Constant(value.clone()),
1906                                )?
1907                                else {
1908                                    unreachable!("inline asm function symbol is not a constant")
1909                                };
1910                                let ConstantExprKind::FnDef(fn_ptr) = value.kind() else {
1911                                    unreachable!("inline asm function symbol is not a function")
1912                                };
1913                                AsmOperand::SymFn(fn_ptr.clone())
1914                            }
1915                            mir::InlineAsmOperand::SymStatic { def_id } => {
1916                                let item = front::translate_item_ref(
1917                                    &self.frontend_state,
1918                                    *def_id,
1919                                    ty::GenericArgs::empty(),
1920                                );
1921                                AsmOperand::SymStatic(self.translate_global_decl_ref(span, &item)?)
1922                            }
1923                            mir::InlineAsmOperand::Label { target_index } => AsmOperand::Label(
1924                                BranchId::from_usize(*target_index - usize::from(has_fallthrough)),
1925                            ),
1926                        })
1927                    })
1928                    .collect::<Result<IndexVec<AsmOperandId, _>, Error>>()?;
1929                let fallthrough =
1930                    has_fallthrough.then(|| self.translate_basic_block_id(targets[0]));
1931                let labels = targets
1932                    .iter()
1933                    .skip(usize::from(has_fallthrough))
1934                    .map(|target| self.translate_basic_block_id(*target))
1935                    .collect();
1936                let on_unwind = self.translate_unwind_action(span, unwind)?;
1937                let asm = Box::new(InlineAsm {
1938                    kind,
1939                    template,
1940                    operands,
1941                    options,
1942                });
1943                ullbc_ast::TerminatorKind::InlineAsm {
1944                    asm,
1945                    fallthrough,
1946                    labels,
1947                    on_unwind,
1948                }
1949            }
1950            TerminatorKind::CoroutineDrop
1951            | TerminatorKind::TailCall { .. }
1952            | TerminatorKind::Yield { .. } => {
1953                raise_error!(self, span, "Unsupported terminator: {:?}", terminator.kind);
1954            }
1955        };
1956
1957        self.finish_current_block(Terminator::new(span, kind));
1958        Ok(())
1959    }
1960
1961    /// Translate switch targets
1962    fn translate_switch_targets(
1963        &mut self,
1964        span: Span,
1965        discr: Operand,
1966        targets: &mir::SwitchTargets,
1967    ) -> Result<(SwitchData, IndexVec<BranchId, BlockId>), Error> {
1968        // Convert all the test values to the proper values.
1969        let otherwise = targets.otherwise();
1970        let switch_ty = discr.ty();
1971        let switch_scalar_ty = *switch_ty.as_scalar().unwrap();
1972        let mut branch_targets: IndexVec<BranchId, BlockId> = IndexVec::new();
1973        let mut target_to_branch: SeqHashMap<BlockId, BranchId> = SeqHashMap::default();
1974        let mut switch_branches = Vec::with_capacity(targets.iter().count());
1975
1976        // Keep the historical true-then-false traversal order for boolean switches.
1977        let bool_fallback = (switch_scalar_ty == ScalarTy::Bool).then(|| {
1978            let target = self.translate_basic_block_id(otherwise);
1979            *target_to_branch
1980                .entry(target)
1981                .or_insert_with(|| branch_targets.push(target))
1982        });
1983
1984        for (bits, target) in targets.iter() {
1985            let Some(kind) = ConstantExprKind::from_bits(&switch_scalar_ty, bits) else {
1986                raise_error!(self, span, "Can't match on type {switch_scalar_ty}")
1987            };
1988            let target = self.translate_basic_block_id(target);
1989            let branch_id = *target_to_branch
1990                .entry(target)
1991                .or_insert_with(|| branch_targets.push(target));
1992            let value = ConstantExpr::new(kind, switch_ty.clone());
1993            switch_branches.push((value, branch_id));
1994        }
1995
1996        let fallback = bool_fallback.unwrap_or_else(|| {
1997            let target = self.translate_basic_block_id(otherwise);
1998            *target_to_branch
1999                .entry(target)
2000                .or_insert_with(|| branch_targets.push(target))
2001        });
2002        let data = SwitchData {
2003            scrutinee: SwitchScrutinee::Value(discr),
2004            branches: switch_branches,
2005            fallback: Some(fallback),
2006        };
2007        Ok((data, branch_targets))
2008    }
2009
2010    /// Translate a function call statement.
2011    /// Note that `body` is the body of the function being translated, not of the
2012    /// function referenced in the function call: we need it in order to translate
2013    /// the blocks we go to after the function call returns.
2014    #[allow(clippy::too_many_arguments)]
2015    fn translate_function_call(
2016        &mut self,
2017        span: Span,
2018        func: &mir::Operand<'tcx>,
2019        args: &[front::Spanned<mir::Operand<'tcx>>],
2020        destination: &mir::Place<'tcx>,
2021        target: &Option<mir::BasicBlock>,
2022        unwind: &mir::UnwindAction,
2023    ) -> Result<TerminatorKind, Error> {
2024        let tcx = self.tcx;
2025        let op_ty = func.ty(self.local_decls, tcx);
2026        // There are two cases, depending on whether this is a "regular"
2027        // call to a top-level function identified by its id, or if we
2028        // are using a local function pointer (i.e., the operand is a "move").
2029        let lval = self.translate_place(span, destination)?;
2030        let on_unwind = self.translate_unwind_action(span, unwind)?;
2031        // Translate the function operand.
2032        let op = self.translate_operand(span, func)?;
2033        let fn_operand = match op.ty().kind() {
2034            // The type of the value is one of the singleton types that corresponds to each
2035            // function, so we statically know which function is getting called.
2036            TyKind::FnDef(fn_ptr) => {
2037                let fn_ptr = self.erase_region_binder(fn_ptr.clone());
2038                FnOperand::Regular(fn_ptr)
2039            }
2040            // Otherwise, we're calling a function pointer.
2041            TyKind::FnPtr(sig) => {
2042                let regions = RegionArgs::new(
2043                    sig.regions
2044                        .map_ref_indexed(|_, _| self.translate_erased_region()),
2045                );
2046                FnOperand::Dynamic(Box::new(op), regions)
2047            }
2048            _ => raise_error!(
2049                self,
2050                span,
2051                "cannot call a value of type {}",
2052                op.ty().with_ctx(&self.into_fmt())
2053            ),
2054        };
2055        let args = self.translate_arguments(span, args)?;
2056
2057        let safety = match op_ty.kind() {
2058            ty::TyKind::FnDef(def_id, generics) => 'safety_fndef: {
2059                let sig_is_unsafe = tcx.fn_sig(*def_id).skip_binder().safety().is_unsafe();
2060
2061                // Safe `#[target_feature]` functions still get an unsafe signature, but calling them is safe if
2062                // the caller enables the same (or implying) features (safety.unsafe-target-feature-call).
2063                // We also get the inverse: `#[unsafe(force_target_feature)]` functions have a safe signature, but calling
2064                // them is unsafe if the caller does not enable the feature.
2065                let attrs = tcx.codegen_fn_attrs(*def_id);
2066                let caller = self.item_src.def_id().derived_base().as_real_or_promoted();
2067                let caller_features = caller
2068                    .map(|caller| tcx.typeck_root_def_id(caller))
2069                    .filter(|caller| tcx.def_kind(*caller).has_codegen_attrs())
2070                    .map_or(&[][..], |caller| {
2071                        &tcx.codegen_fn_attrs(caller).target_features[..]
2072                    });
2073                let has_feature =
2074                    tcx.is_target_feature_call_safe(&attrs.target_features, caller_features);
2075                if sig_is_unsafe && attrs.safe_target_features && has_feature {
2076                    break 'safety_fndef CallSafety::Safe;
2077                } else if !has_feature {
2078                    break 'safety_fndef CallSafety::Unsafe;
2079                }
2080
2081                // Explicitly calling a `Drop` method is unsafe.
2082                if let Some(trait_id) = tcx.trait_of_assoc(*def_id)
2083                    && tcx.is_lang_item(trait_id, LangItem::Drop)
2084                {
2085                    break 'safety_fndef CallSafety::Unsafe;
2086                }
2087
2088                // FIXME(#856) In mono mode, trait decls have no methods, so we track the safety of the function here,
2089                // and `transform_dyn_trait_calls` moves it into the signature of the called function pointer.
2090                let mono_dyn_call = self.monomorphize()
2091                    && tcx.trait_of_assoc(*def_id).is_some()
2092                    && generics.skip_binder().type_at(0).is_trait();
2093                if mono_dyn_call {
2094                    break 'safety_fndef if sig_is_unsafe {
2095                        CallSafety::Unsafe
2096                    } else {
2097                        CallSafety::Safe
2098                    };
2099                }
2100
2101                CallSafety::Inherit
2102            }
2103            _ => CallSafety::Inherit,
2104        };
2105
2106        let call = Call {
2107            func: fn_operand,
2108            args,
2109            safety,
2110        };
2111
2112        let target = match target {
2113            Some(target) => self.translate_basic_block_id(*target),
2114            None => {
2115                let abort = Terminator::new(span, TerminatorKind::UndefinedBehavior);
2116                let kind = self.kind;
2117                self.blocks.push(abort.into_block(kind))
2118            }
2119        };
2120
2121        Ok(TerminatorKind::Call {
2122            call,
2123            dest: lval,
2124            target,
2125            on_unwind,
2126        })
2127    }
2128
2129    /// Translate a drop terminator
2130    #[allow(clippy::too_many_arguments)]
2131    fn translate_drop(
2132        &mut self,
2133        span: Span,
2134        place: &mir::Place<'tcx>,
2135        target: &mir::BasicBlock,
2136        unwind: &mir::UnwindAction,
2137    ) -> Result<TerminatorKind, Error> {
2138        let place_ty = place.ty(self.local_decls, self.tcx).ty;
2139        let fn_ptr = self.translate_drop_glue_method_call(span, place_ty)?;
2140        let place = self.translate_place(span, place)?;
2141        let target = self.translate_basic_block_id(*target);
2142        let on_unwind = self.translate_unwind_action(span, unwind)?;
2143
2144        Ok(TerminatorKind::Drop {
2145            kind: self.drop_kind,
2146            place,
2147            fn_ptr,
2148            target,
2149            on_unwind,
2150        })
2151    }
2152
2153    // construct unwind block for the terminators
2154    fn translate_unwind_action(
2155        &mut self,
2156        span: Span,
2157        unwind: &mir::UnwindAction,
2158    ) -> Result<BlockId, Error> {
2159        let unwind_kind = self.kind.further_unwind_kind();
2160        Ok(match unwind {
2161            mir::UnwindAction::Continue => {
2162                assert_eq!(unwind_kind, UnwindKind::Cleanup);
2163                let unwind_continue = Terminator::new(span, TerminatorKind::UnwindResume);
2164                self.blocks.push(unwind_continue.into_block(unwind_kind))
2165            }
2166            mir::UnwindAction::Unreachable => {
2167                let abort = Terminator::new(span, TerminatorKind::UndefinedBehavior);
2168                self.blocks.push(abort.into_block(unwind_kind))
2169            }
2170            mir::UnwindAction::Terminate(reason) => {
2171                let kind = self.translate_unwind_terminate(span, *reason)?;
2172                let abort = Terminator::new(span, kind);
2173                self.blocks.push(abort.into_block(unwind_kind))
2174            }
2175            mir::UnwindAction::Cleanup(bb) => self.translate_basic_block_id(*bb),
2176        })
2177    }
2178
2179    fn translate_assert_kind(
2180        &mut self,
2181        span: Span,
2182        kind: &mir::AssertKind<mir::Operand<'tcx>>,
2183    ) -> Result<BuiltinAssertKind, Error> {
2184        match kind {
2185            mir::AssertKind::BoundsCheck { len, index } => {
2186                let len = self.translate_operand(span, len)?;
2187                let index = self.translate_operand(span, index)?;
2188                Ok(BuiltinAssertKind::BoundsCheck { len, index })
2189            }
2190            mir::AssertKind::Overflow(binop, left, right) => {
2191                let binop = self.translate_binaryop_kind(span, *binop)?;
2192                let left = self.translate_operand(span, left)?;
2193                let right = self.translate_operand(span, right)?;
2194                Ok(BuiltinAssertKind::Overflow(binop, left, right))
2195            }
2196            mir::AssertKind::OverflowNeg(operand) => {
2197                let operand = self.translate_operand(span, operand)?;
2198                Ok(BuiltinAssertKind::OverflowNeg(operand))
2199            }
2200            mir::AssertKind::DivisionByZero(operand) => {
2201                let operand = self.translate_operand(span, operand)?;
2202                Ok(BuiltinAssertKind::DivisionByZero(operand))
2203            }
2204            mir::AssertKind::RemainderByZero(operand) => {
2205                let operand = self.translate_operand(span, operand)?;
2206                Ok(BuiltinAssertKind::RemainderByZero(operand))
2207            }
2208            mir::AssertKind::MisalignedPointerDereference { required, found } => {
2209                let required = self.translate_operand(span, required)?;
2210                let found = self.translate_operand(span, found)?;
2211                Ok(BuiltinAssertKind::MisalignedPointerDereference { required, found })
2212            }
2213            mir::AssertKind::NullPointerDereference => {
2214                Ok(BuiltinAssertKind::NullPointerDereference)
2215            }
2216            mir::AssertKind::NullReferenceConstructed => {
2217                Ok(BuiltinAssertKind::NullReferenceCreated)
2218            }
2219            mir::AssertKind::InvalidEnumConstruction(operand) => {
2220                let operand = self.translate_operand(span, operand)?;
2221                Ok(BuiltinAssertKind::InvalidEnumConstruction(operand))
2222            }
2223            mir::AssertKind::ResumedAfterDrop(..)
2224            | mir::AssertKind::ResumedAfterPanic(..)
2225            | mir::AssertKind::ResumedAfterReturn(..) => {
2226                raise_error!(self, span, "Coroutines are not supported");
2227            }
2228        }
2229    }
2230
2231    fn translate_unwind_terminate(
2232        &mut self,
2233        span: Span,
2234        reason: mir::UnwindTerminateReason,
2235    ) -> Result<TerminatorKind, Error> {
2236        let def_id = self
2237            .tcx
2238            .require_lang_item(reason.lang_item(), rustc_span::DUMMY_SP);
2239        let item =
2240            front::translate_item_ref(&self.frontend_state, def_id, ty::GenericArgs::empty());
2241        let fun_ref = self.translate_item(span, &item)?;
2242        let reason = match reason {
2243            mir::UnwindTerminateReason::Abi => UnwindTerminateReason::Abi,
2244            mir::UnwindTerminateReason::InCleanup => UnwindTerminateReason::InCleanup,
2245        };
2246        Ok(TerminatorKind::UnwindTerminate(reason, fun_ref))
2247    }
2248
2249    /// Evaluate function arguments in a context, and return the list of computed
2250    /// values.
2251    fn translate_arguments(
2252        &mut self,
2253        span: Span,
2254        args: &[front::Spanned<mir::Operand<'tcx>>],
2255    ) -> Result<Vec<Operand>, Error> {
2256        let mut t_args: Vec<Operand> = Vec::new();
2257        for arg in args.iter().map(|x| &x.node) {
2258            // Translate
2259            let op = self.translate_operand(span, arg)?;
2260            t_args.push(op);
2261        }
2262        Ok(t_args)
2263    }
2264}
2265
2266impl<'a> IntoFormatter for &'a BodyTransCtx<'_, '_, '_> {
2267    type C = FmtCtx<'a>;
2268    fn into_fmt(self) -> Self::C {
2269        FmtCtx {
2270            local_names: Some(Cow::Owned(compute_local_names(&self.locals))),
2271            ..self.i_ctx.into_fmt()
2272        }
2273    }
2274}