Skip to main content

rustc_mir_build/builder/expr/
into.rs

1//! See docs in build/expr/mod.rs
2
3use rustc_abi::FieldIdx;
4use rustc_ast::{AsmMacro, InlineAsmOptions};
5use rustc_data_structures::fx::FxHashMap;
6use rustc_hir as hir;
7use rustc_hir::attrs::lang_items::LangItem;
8use rustc_middle::mir::*;
9use rustc_middle::thir::*;
10use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty};
11use rustc_span::{DUMMY_SP, Spanned, span_bug, sym};
12use rustc_trait_selection::infer::InferCtxtExt;
13use tracing::{debug, instrument};
14
15use crate::builder::expr::category::{Category, RvalueFunc};
16use crate::builder::matches::{DeclareLetBindings, Exhaustive, HasMatchGuard, LowerIfCondArgs};
17use crate::builder::scope::LintLevel;
18use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary};
19use crate::diagnostics::{LoopMatchArmWithGuard, LoopMatchUnsupportedType};
20
21impl<'a, 'tcx> Builder<'a, 'tcx> {
22    /// Compile `expr`, storing the result into `destination`, which
23    /// is assumed to be uninitialized.
24    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("expr_into_dest",
                                    "rustc_mir_build::builder::expr::into",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/into.rs"),
                                    ::tracing_core::__macro_support::Option::Some(24u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::into"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("destination")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("destination");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("block")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("block");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&destination)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&block)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: BlockAnd<()> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let this = self;
            let expr = &this.thir[expr_id];
            let expr_span = expr.span;
            let source_info = this.source_info(expr_span);
            let expr_is_block_or_scope =
                #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
                    ExprKind::Block { .. } | ExprKind::Scope { .. } => true,
                    _ => false,
                };
            if !expr_is_block_or_scope {
                this.block_context.push(BlockFrame::SubExpr);
            }
            let block_and =
                match expr.kind {
                    ExprKind::Scope { region_scope, hir_id, value } => {
                        let region_scope = (region_scope, source_info);
                        this.in_scope(region_scope, LintLevel::Explicit(hir_id),
                            |this|
                                {
                                    this.push_coverage_point_for_expr(block, source_info,
                                        hir_id);
                                    this.expr_into_dest(destination, block, value)
                                })
                    }
                    ExprKind::Block { block: ast_block } => {
                        this.ast_block(destination, block, ast_block, source_info)
                    }
                    ExprKind::Match { scrutinee, ref arms, .. } => {
                        this.match_expr(destination, block, scrutinee, arms,
                            expr_span)
                    }
                    ExprKind::If { cond, then, else_opt, if_then_scope } => {
                        let then_span = this.thir[then].span;
                        let then_source_info = this.source_info(then_span);
                        let condition_scope = this.local_scope();
                        let true_and_false_blocks =
                            this.in_scope((if_then_scope, then_source_info),
                                LintLevel::Inherited,
                                |this|
                                    {
                                        let source_info =
                                            if this.is_let(cond) {
                                                let variable_scope =
                                                    this.new_source_scope(then_span, LintLevel::Inherited);
                                                this.source_scope = variable_scope;
                                                SourceInfo { span: then_span, scope: variable_scope }
                                            } else { this.source_info(then_span) };
                                        let (true_block, false_block) =
                                            this.in_if_then_scope(condition_scope, then_span,
                                                |this|
                                                    {
                                                        let true_block =
                                                            this.lower_if_condition(block, cond,
                                                                    LowerIfCondArgs {
                                                                        temp_scope_override: Some(condition_scope),
                                                                        variable_source_info: source_info,
                                                                        declare_let_bindings: DeclareLetBindings::Yes,
                                                                    }).into_block();
                                                        this.expr_into_dest(destination, true_block, then)
                                                    });
                                        true_block.and(false_block)
                                    });
                        let (true_block, mut false_block);
                        false_block =
                            {
                                let BlockAnd(b, v) = true_and_false_blocks;
                                true_block = b;
                                v
                            };
                        if let Some(else_expr) = else_opt {
                            false_block =
                                this.expr_into_dest(destination, false_block,
                                        else_expr).into_block();
                        } else {
                            let correct_si = this.source_info(expr_span.shrink_to_hi());
                            this.push_coverage_point_for_implicit_else(false_block,
                                correct_si, expr);
                            this.cfg.push_assign_unit(false_block, correct_si,
                                destination, this.tcx);
                        }
                        let join_block = this.cfg.start_new_block();
                        this.cfg.goto(true_block, source_info, join_block);
                        this.cfg.goto(false_block, source_info, join_block);
                        join_block.unit()
                    }
                    ExprKind::Let { .. } => {
                        bug_impl(Some(expr_span),
                            format_args!("unexpected let expression outside of if or match-guard"),
                            Location::caller());
                    }
                    ExprKind::NeverToAny { source } => {
                        let source_expr = &this.thir[source];
                        let is_call =
                            #[allow(non_exhaustive_omitted_patterns)] match source_expr.kind
                                {
                                ExprKind::Call { .. } | ExprKind::InlineAsm { .. } => true,
                                _ => false,
                            };
                        {
                            let BlockAnd(b, v) =
                                this.as_temp(block, this.local_temp_lifetime(), source,
                                    Mutability::Mut);
                            block = b;
                            v
                        };
                        if is_call {
                            block.unit()
                        } else {
                            this.cfg.terminate(block, source_info,
                                TerminatorKind::Unreachable);
                            let end_block = this.cfg.start_new_block();
                            end_block.unit()
                        }
                    }
                    ExprKind::LogicalOp { op, lhs, rhs } => {
                        let condition_scope = this.local_scope();
                        let source_info = this.source_info(expr.span);
                        let (true_block, false_block) =
                            this.in_if_then_scope(condition_scope, expr.span,
                                |this|
                                    {
                                        this.lower_if_condition(block, lhs,
                                            LowerIfCondArgs {
                                                temp_scope_override: Some(condition_scope),
                                                variable_source_info: source_info,
                                                declare_let_bindings: DeclareLetBindings::LetNotPermitted,
                                            })
                                    });
                        let (short_circuit_block, short_circuit_value,
                                continue_block) =
                            match op {
                                LogicalOp::And => (false_block, false, true_block),
                                LogicalOp::Or => (true_block, true, false_block),
                            };
                        this.cfg.push_assign_constant(short_circuit_block,
                            source_info, destination,
                            ConstOperand {
                                span: expr.span,
                                user_ty: None,
                                const_: Const::from_bool(this.tcx, short_circuit_value),
                            });
                        let mut rhs_block =
                            this.expr_into_dest(destination, continue_block,
                                    rhs).into_block();
                        this.visit_coverage_standalone_condition(rhs, destination,
                            &mut rhs_block);
                        let join_block = this.cfg.start_new_block();
                        this.cfg.goto(rhs_block, source_info, join_block);
                        this.cfg.goto(short_circuit_block, source_info, join_block);
                        join_block.unit()
                    }
                    ExprKind::Loop { body } => {
                        let loop_block = this.cfg.start_new_block();
                        this.cfg.goto(block, source_info, loop_block);
                        this.in_breakable_scope(Some(loop_block), destination,
                            expr_span,
                            move |this|
                                {
                                    let body_block = this.cfg.start_new_block();
                                    this.cfg.terminate(loop_block, source_info,
                                        TerminatorKind::FalseUnwind {
                                            real_target: body_block,
                                            unwind: UnwindAction::Continue,
                                        });
                                    this.diverge_from(loop_block);
                                    let tmp = this.get_unit_temp();
                                    let body_block_end =
                                        this.expr_into_dest(tmp, body_block, body).into_block();
                                    let goto =
                                        this.cfg.goto(body_block_end, source_info, loop_block);
                                    if let Some(attrs) = this.thir.attributes.get(&expr_id) {
                                        goto.attributes = attrs.clone();
                                    }
                                    None
                                })
                    }
                    ExprKind::LoopMatch {
                        state,
                        region_scope,
                        match_data: LoopMatchMatchData {
                            ref arms, span: match_span, scrutinee
                            } } => {
                        fn is_supported_loop_match_type(ty: Ty<'_>) -> bool {
                            match ty.kind() {
                                ty::Uint(_) | ty::Int(_) | ty::Float(_) | ty::Bool |
                                    ty::Char => true,
                                ty::Adt(adt_def, _) =>
                                    match adt_def.adt_kind() {
                                        ty::AdtKind::Struct | ty::AdtKind::Union => false,
                                        ty::AdtKind::Enum => {
                                            adt_def.variants().iter().all(|v| v.fields.is_empty())
                                        }
                                    },
                                _ => false,
                            }
                        }
                        let state_ty = this.thir.exprs[state].ty;
                        if !is_supported_loop_match_type(state_ty) {
                            let span = this.thir.exprs[state].span;
                            this.tcx.dcx().emit_fatal(LoopMatchUnsupportedType {
                                    span,
                                    ty: state_ty,
                                })
                        }
                        let loop_block = this.cfg.start_new_block();
                        this.cfg.goto(block, source_info, loop_block);
                        this.in_breakable_scope(Some(loop_block), destination,
                            expr_span,
                            |this|
                                {
                                    let mut body_block = this.cfg.start_new_block();
                                    this.cfg.terminate(loop_block, source_info,
                                        TerminatorKind::FalseUnwind {
                                            real_target: body_block,
                                            unwind: UnwindAction::Continue,
                                        });
                                    this.diverge_from(loop_block);
                                    let scrutinee_span = this.thir.exprs[scrutinee].span;
                                    let scrutinee_place_builder =
                                        {
                                            let BlockAnd(b, v) =
                                                this.lower_scrutinee(body_block, scrutinee);
                                            body_block = b;
                                            v
                                        };
                                    let match_start_span =
                                        match_span.shrink_to_lo().to(scrutinee_span);
                                    let mut patterns = Vec::with_capacity(arms.len());
                                    for &arm_id in arms.iter() {
                                        let arm = &this.thir[arm_id];
                                        if let Some(guard) = arm.guard {
                                            let span = this.thir.exprs[guard].span;
                                            this.tcx.dcx().emit_fatal(LoopMatchArmWithGuard { span })
                                        }
                                        patterns.push((&*arm.pattern, HasMatchGuard::No));
                                    }
                                    let built_tree =
                                        this.lower_match_tree(body_block, scrutinee_span,
                                            &scrutinee_place_builder, match_start_span, patterns,
                                            Exhaustive::Yes);
                                    let state_place = scrutinee_place_builder.to_place(this);
                                    let state_result = this.temp(state_ty, expr_span);
                                    let state_result_place = Place::from(state_result);
                                    {
                                        let BlockAnd(b, v) =
                                            this.in_scope((region_scope, source_info),
                                                LintLevel::Inherited,
                                                move |this|
                                                    {
                                                        this.in_const_continuable_scope(arms.clone(),
                                                            built_tree.clone(), state_place, expr_span,
                                                            |this|
                                                                {
                                                                    let block =
                                                                        this.in_breakable_scope(None, state_result_place, expr_span,
                                                                                |this|
                                                                                    {
                                                                                        Some(this.lower_match_arms(state_result_place,
                                                                                                scrutinee_place_builder, scrutinee_span, arms, built_tree,
                                                                                                this.source_info(match_span)))
                                                                                    }).into_block();
                                                                    this.cfg.push_assign(block, source_info, state_place,
                                                                        Rvalue::Use(this.consume_by_copy_or_move(state_result_place),
                                                                            WithRetag::Yes));
                                                                    block.unit()
                                                                })
                                                    });
                                        body_block = b;
                                        v
                                    };
                                    this.cfg.goto(body_block, source_info, loop_block);
                                    None
                                })
                    }
                    ExprKind::Call { ty, fun, ref args, .. } if
                        let ty::FnDef(def_id, generic_args) = *ty.kind() &&
                                let Some(intrinsic) = this.tcx.intrinsic(def_id) &&
                            #[allow(non_exhaustive_omitted_patterns)] match intrinsic.name
                                {
                                sym::write_via_move | sym::write_box_via_move => true,
                                _ => false,
                            } => {
                        let generic_args = generic_args.no_bound_vars().unwrap();
                        let _fun =
                            {
                                let BlockAnd(b, v) = this.as_local_operand(block, fun);
                                block = b;
                                v
                            };
                        match intrinsic.name {
                            sym::write_via_move => {
                                if !destination.ty(&this.local_decls, this.tcx).ty.is_unit()
                                    {
                                    ::core::panicking::panic("assertion failed: destination.ty(&this.local_decls, this.tcx).ty.is_unit()")
                                };
                                let [ptr, val] =
                                    **args else {
                                        bug_impl(Some(expr_span),
                                            format_args!("invalid write_via_move call"),
                                            Location::caller())
                                    };
                                let Some(ptr) =
                                    {
                                            let BlockAnd(b, v) = this.as_local_operand(block, ptr);
                                            block = b;
                                            v
                                        }.place() else {
                                        bug_impl(Some(expr_span),
                                            format_args!("invalid write_via_move call"),
                                            Location::caller())
                                    };
                                let ptr_deref =
                                    ptr.project_deeper(&[ProjectionElem::Deref], this.tcx);
                                this.expr_into_dest(ptr_deref, block, val)
                            }
                            sym::write_box_via_move => {
                                let [b, val] =
                                    **args else {
                                        bug_impl(Some(expr_span),
                                            format_args!("invalid init_box_via_move call"),
                                            Location::caller())
                                    };
                                let Some(b) =
                                    {
                                            let BlockAnd(b, v) = this.as_local_operand(block, b);
                                            block = b;
                                            v
                                        }.place() else {
                                        bug_impl(Some(expr_span),
                                            format_args!("invalid init_box_via_move call"),
                                            Location::caller())
                                    };
                                let tcx = this.tcx;
                                let decls = &this.local_decls;
                                let place = b.project_deeper(&[ProjectionElem::Deref], tcx);
                                let place =
                                    place.project_to_field(FieldIdx::from_u32(1), decls, tcx);
                                let place =
                                    place.project_to_field(FieldIdx::ZERO, decls, tcx);
                                {
                                    match (&place.ty(decls, tcx).ty, &generic_args.type_at(0)) {
                                        (left_val, right_val) => {
                                            if !(*left_val == *right_val) {
                                                let kind = ::core::panicking::AssertKind::Eq;
                                                ::core::panicking::assert_failed(kind, &*left_val,
                                                    &*right_val, ::core::option::Option::None);
                                            }
                                        }
                                    }
                                };
                                {
                                    let BlockAnd(b, v) = this.expr_into_dest(place, block, val);
                                    block = b;
                                    v
                                };
                                this.cfg.push_assign(block, source_info, destination,
                                    Rvalue::Use(Operand::Move(b), WithRetag::Yes));
                                block.unit()
                            }
                            _ =>
                                bug_impl(None, format_args!("impossible case reached"),
                                    Location::caller()),
                        }
                    }
                    ExprKind::Call {
                        ty: _, fun, ref args, from_hir_call, fn_span } => {
                        let fun =
                            {
                                let BlockAnd(b, v) = this.as_local_operand(block, fun);
                                block = b;
                                v
                            };
                        let args: Box<[_]> =
                            args.into_iter().copied().map(|arg|
                                        Spanned {
                                            node: {
                                                let BlockAnd(b, v) = this.as_local_call_operand(block, arg);
                                                block = b;
                                                v
                                            },
                                            span: this.thir.exprs[arg].span,
                                        }).collect();
                        let success = this.cfg.start_new_block();
                        this.record_operands_moved(&args);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/into.rs:491",
                                                "rustc_mir_build::builder::expr::into",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/into.rs"),
                                                ::tracing_core::__macro_support::Option::Some(491u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::into"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expr_into_dest: fn_span={0:?}",
                                                                            fn_span) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        this.cfg.terminate(block, source_info,
                            TerminatorKind::Call {
                                func: fun,
                                args,
                                unwind: UnwindAction::Continue,
                                destination,
                                target: Some(success),
                                call_source: if from_hir_call {
                                    CallSource::Normal
                                } else { CallSource::OverloadedOperator },
                                fn_span,
                            });
                        this.diverge_from(block);
                        success.unit()
                    }
                    ExprKind::ByUse { expr, span } => {
                        let place =
                            {
                                let BlockAnd(b, v) = this.as_place(block, expr);
                                block = b;
                                v
                            };
                        let ty = place.ty(&this.local_decls, this.tcx).ty;
                        if this.tcx.type_is_copy_modulo_regions(this.infcx.typing_env(this.param_env),
                                ty) {
                            this.cfg.push_assign(block, source_info, destination,
                                Rvalue::Use(Operand::Copy(place), WithRetag::Yes));
                            block.unit()
                        } else if this.infcx.type_is_use_cloned_modulo_regions(this.param_env,
                                ty) {
                            let success = this.cfg.start_new_block();
                            let clone_trait =
                                this.tcx.require_lang_item(LangItem::Clone, span);
                            let clone_fn =
                                this.tcx.associated_item_def_ids(clone_trait)[0];
                            let func =
                                Operand::function_handle(this.tcx, clone_fn, &[ty.into()],
                                    expr_span);
                            let ref_ty =
                                Ty::new_imm_ref(this.tcx, this.tcx.lifetimes.re_erased, ty);
                            let ref_place = this.temp(ref_ty, span);
                            this.cfg.push_assign(block, source_info, ref_place,
                                Rvalue::Ref(this.tcx.lifetimes.re_erased,
                                    BorrowKind::Shared, place));
                            this.cfg.terminate(block, source_info,
                                TerminatorKind::Call {
                                    func,
                                    args: [Spanned {
                                                    node: Operand::Move(ref_place),
                                                    span: DUMMY_SP,
                                                }].into(),
                                    destination,
                                    target: Some(success),
                                    unwind: UnwindAction::Unreachable,
                                    call_source: CallSource::Use,
                                    fn_span: expr_span,
                                });
                            success.unit()
                        } else {
                            this.cfg.push_assign(block, source_info, destination,
                                Rvalue::Use(Operand::Move(place), WithRetag::Yes));
                            block.unit()
                        }
                    }
                    ExprKind::ValueExpr { source } =>
                        this.expr_into_dest(destination, block, source),
                    ExprKind::Borrow { arg, borrow_kind } => {
                        let arg_place =
                            match borrow_kind {
                                BorrowKind::Shared => {
                                    {
                                        let BlockAnd(b, v) = this.as_read_only_place(block, arg);
                                        block = b;
                                        v
                                    }
                                }
                                _ => {
                                    let BlockAnd(b, v) = this.as_place(block, arg);
                                    block = b;
                                    v
                                }
                            };
                        let borrow =
                            Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind,
                                arg_place);
                        this.cfg.push_assign(block, source_info, destination,
                            borrow);
                        block.unit()
                    }
                    ExprKind::RawBorrow { mutability, arg } => {
                        let place =
                            match mutability {
                                hir::Mutability::Not => this.as_read_only_place(block, arg),
                                hir::Mutability::Mut => this.as_place(block, arg),
                            };
                        let address_of =
                            Rvalue::RawPtr(mutability.into(),
                                { let BlockAnd(b, v) = place; block = b; v });
                        this.cfg.push_assign(block, source_info, destination,
                            address_of);
                        block.unit()
                    }
                    ExprKind::Adt(AdtExpr {
                        adt_def,
                        variant_index,
                        args,
                        ref user_ty,
                        ref fields,
                        ref base }) => {
                        let is_union = adt_def.is_union();
                        let active_field_index = is_union.then(|| fields[0].name);
                        let scope = this.local_temp_lifetime();
                        let fields_map: FxHashMap<_, _> =
                            fields.into_iter().map(|f|
                                        {
                                            (f.name,
                                                {
                                                    let BlockAnd(b, v) =
                                                        this.as_operand(block, scope, f.expr,
                                                            LocalInfo::AggregateTemp, NeedsTemporary::Maybe);
                                                    block = b;
                                                    v
                                                })
                                        }).collect();
                        let variant = adt_def.variant(variant_index);
                        let field_names = variant.fields.indices();
                        let fields =
                            match base {
                                AdtExprBase::None => {
                                    field_names.filter_map(|n|
                                                fields_map.get(&n).cloned()).collect()
                                }
                                AdtExprBase::Base(FruInfo { base, field_types }) => {
                                    let place_builder =
                                        {
                                            let BlockAnd(b, v) = this.as_place_builder(block, *base);
                                            block = b;
                                            v
                                        };
                                    itertools::zip_eq(field_names,
                                                &**field_types).map(|(n, ty)|
                                                match fields_map.get(&n) {
                                                    Some(v) => v.clone(),
                                                    None => {
                                                        let place =
                                                            place_builder.clone_project(PlaceElem::Field(n, *ty));
                                                        this.consume_by_copy_or_move(place.to_place(this))
                                                    }
                                                }).collect()
                                }
                                AdtExprBase::DefaultFields(field_types) => {
                                    itertools::zip_eq(field_names,
                                                field_types).map(|(n, &ty)|
                                                match fields_map.get(&n) {
                                                    Some(v) => v.clone(),
                                                    None =>
                                                        match variant.fields[n].value {
                                                            Some(def) => {
                                                                let value =
                                                                    Const::Unevaluated(UnevaluatedConst::new(def, args), ty);
                                                                Operand::Constant(Box::new(ConstOperand {
                                                                            span: expr_span,
                                                                            user_ty: None,
                                                                            const_: value,
                                                                        }))
                                                            }
                                                            None => {
                                                                let name = variant.fields[n].name;
                                                                bug_impl(Some(expr_span),
                                                                    format_args!("missing mandatory field `{0}` of type `{1}`",
                                                                        name, ty), Location::caller());
                                                            }
                                                        },
                                                }).collect()
                                }
                            };
                        let inferred_ty = expr.ty;
                        let user_ty =
                            user_ty.as_ref().map(|user_ty|
                                    {
                                        this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
                                                span: source_info.span,
                                                user_ty: user_ty.clone(),
                                                inferred_ty,
                                            })
                                    });
                        let adt =
                            Box::new(AggregateKind::Adt(adt_def.did(), variant_index,
                                    args, user_ty, active_field_index));
                        this.cfg.push_assign(block, source_info, destination,
                            Rvalue::Aggregate(adt, fields));
                        block.unit()
                    }
                    ExprKind::InlineAsm(InlineAsmExpr {
                        asm_macro, template, ref operands, options, line_spans }) =>
                        {
                        use rustc_middle::{mir, thir};
                        let destination_block = this.cfg.start_new_block();
                        let mut targets =
                            if asm_macro.diverges(options) {
                                ::alloc::vec::Vec::new()
                            } else {
                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                        [destination_block]))
                            };
                        let operands =
                            operands.into_iter().map(|op|
                                        match *op {
                                            thir::InlineAsmOperand::In { reg, expr } =>
                                                mir::InlineAsmOperand::In {
                                                    reg,
                                                    value: {
                                                        let BlockAnd(b, v) = this.as_local_operand(block, expr);
                                                        block = b;
                                                        v
                                                    },
                                                },
                                            thir::InlineAsmOperand::Out { reg, late, expr } => {
                                                mir::InlineAsmOperand::Out {
                                                    reg,
                                                    late,
                                                    place: expr.map(|expr|
                                                            {
                                                                let BlockAnd(b, v) = this.as_place(block, expr);
                                                                block = b;
                                                                v
                                                            }),
                                                }
                                            }
                                            thir::InlineAsmOperand::InOut { reg, late, expr } => {
                                                let place =
                                                    {
                                                        let BlockAnd(b, v) = this.as_place(block, expr);
                                                        block = b;
                                                        v
                                                    };
                                                mir::InlineAsmOperand::InOut {
                                                    reg,
                                                    late,
                                                    in_value: Operand::Copy(place),
                                                    out_place: Some(place),
                                                }
                                            }
                                            thir::InlineAsmOperand::SplitInOut {
                                                reg, late, in_expr, out_expr } => {
                                                mir::InlineAsmOperand::InOut {
                                                    reg,
                                                    late,
                                                    in_value: {
                                                        let BlockAnd(b, v) = this.as_local_operand(block, in_expr);
                                                        block = b;
                                                        v
                                                    },
                                                    out_place: out_expr.map(|out_expr|
                                                            {
                                                                {
                                                                    let BlockAnd(b, v) = this.as_place(block, out_expr);
                                                                    block = b;
                                                                    v
                                                                }
                                                            }),
                                                }
                                            }
                                            thir::InlineAsmOperand::Const { value, span } => {
                                                mir::InlineAsmOperand::Const {
                                                    value: Box::new(ConstOperand {
                                                            span,
                                                            user_ty: None,
                                                            const_: value,
                                                        }),
                                                }
                                            }
                                            thir::InlineAsmOperand::SymFn { value } =>
                                                mir::InlineAsmOperand::SymFn {
                                                    value: Box::new(this.as_constant(&this.thir[value])),
                                                },
                                            thir::InlineAsmOperand::SymStatic { def_id } => {
                                                mir::InlineAsmOperand::SymStatic { def_id }
                                            }
                                            thir::InlineAsmOperand::Label { block } => {
                                                let target = this.cfg.start_new_block();
                                                let target_index = targets.len();
                                                targets.push(target);
                                                let tmp = this.get_unit_temp();
                                                let target =
                                                    this.ast_block(tmp, target, block,
                                                            source_info).into_block();
                                                this.cfg.terminate(target, source_info,
                                                    TerminatorKind::Goto { target: destination_block });
                                                mir::InlineAsmOperand::Label { target_index }
                                            }
                                        }).collect();
                        if !expr.ty.is_never() {
                            this.cfg.push_assign_unit(block, source_info, destination,
                                this.tcx);
                        }
                        let asm_macro =
                            match asm_macro {
                                AsmMacro::Asm | AsmMacro::GlobalAsm => InlineAsmMacro::Asm,
                                AsmMacro::NakedAsm => InlineAsmMacro::NakedAsm,
                            };
                        this.cfg.terminate(block, source_info,
                            TerminatorKind::InlineAsm {
                                asm_macro,
                                template,
                                operands,
                                options,
                                line_spans,
                                targets: targets.into_boxed_slice(),
                                unwind: if options.contains(InlineAsmOptions::MAY_UNWIND) {
                                    UnwindAction::Continue
                                } else { UnwindAction::Unreachable },
                            });
                        if options.contains(InlineAsmOptions::MAY_UNWIND) {
                            this.diverge_from(block);
                        }
                        destination_block.unit()
                    }
                    ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
                        block = this.stmt_expr(block, expr_id, None).into_block();
                        this.cfg.push_assign_unit(block, source_info, destination,
                            this.tcx);
                        block.unit()
                    }
                    ExprKind::Continue { .. } | ExprKind::ConstContinue { .. } |
                        ExprKind::Break { .. } | ExprKind::Return { .. } |
                        ExprKind::Become { .. } => {
                        block = this.stmt_expr(block, expr_id, None).into_block();
                        block.unit()
                    }
                    ExprKind::VarRef { .. } | ExprKind::UpvarRef { .. } |
                        ExprKind::PlaceTypeAscription { .. } |
                        ExprKind::ValueTypeAscription { .. } |
                        ExprKind::PlaceUnwrapUnsafeBinder { .. } |
                        ExprKind::ValueUnwrapUnsafeBinder { .. } => {
                        if true {
                            if !(Category::of(&expr.kind) == Some(Category::Place)) {
                                ::core::panicking::panic("assertion failed: Category::of(&expr.kind) == Some(Category::Place)")
                            };
                        };
                        let place =
                            {
                                let BlockAnd(b, v) = this.as_place(block, expr_id);
                                block = b;
                                v
                            };
                        let rvalue =
                            Rvalue::Use(this.consume_by_copy_or_move(place),
                                WithRetag::Yes);
                        this.cfg.push_assign(block, source_info, destination,
                            rvalue);
                        block.unit()
                    }
                    ExprKind::Index { .. } | ExprKind::Deref { .. } |
                        ExprKind::Field { .. } => {
                        if true {
                            {
                                match (&Category::of(&expr.kind), &Some(Category::Place)) {
                                    (left_val, right_val) => {
                                        if !(*left_val == *right_val) {
                                            let kind = ::core::panicking::AssertKind::Eq;
                                            ::core::panicking::assert_failed(kind, &*left_val,
                                                &*right_val, ::core::option::Option::None);
                                        }
                                    }
                                }
                            };
                        };
                        if !destination.projection.is_empty() {
                            this.local_decls.push(LocalDecl::new(expr.ty, expr.span));
                        }
                        let place =
                            {
                                let BlockAnd(b, v) = this.as_place(block, expr_id);
                                block = b;
                                v
                            };
                        let rvalue =
                            Rvalue::Use(this.consume_by_copy_or_move(place),
                                WithRetag::Yes);
                        this.cfg.push_assign(block, source_info, destination,
                            rvalue);
                        block.unit()
                    }
                    ExprKind::Yield { value } => {
                        let scope = this.local_temp_lifetime();
                        let value =
                            {
                                let BlockAnd(b, v) =
                                    this.as_operand(block, scope, value, LocalInfo::Boring,
                                        NeedsTemporary::No);
                                block = b;
                                v
                            };
                        let resume = this.cfg.start_new_block();
                        this.cfg.terminate(block, source_info,
                            TerminatorKind::Yield {
                                value,
                                resume,
                                resume_arg: destination,
                                drop: None,
                            });
                        this.coroutine_drop_cleanup(block);
                        resume.unit()
                    }
                    ExprKind::Unary { .. } | ExprKind::Binary { .. } |
                        ExprKind::Cast { .. } | ExprKind::PointerCoercion { .. } |
                        ExprKind::Repeat { .. } | ExprKind::Array { .. } |
                        ExprKind::Tuple { .. } | ExprKind::Closure { .. } |
                        ExprKind::ConstBlock { .. } | ExprKind::Literal { .. } |
                        ExprKind::NamedConst { .. } | ExprKind::NonHirLiteral { .. }
                        | ExprKind::ZstLiteral { .. } | ExprKind::ConstParam { .. }
                        | ExprKind::ThreadLocalRef(_) | ExprKind::StaticRef { .. } |
                        ExprKind::WrapUnsafeBinder { .. } => {
                        if true {
                            if !match Category::of(&expr.kind).unwrap() {
                                        Category::Rvalue(RvalueFunc::Into) => false,
                                        Category::Place => false,
                                        _ => true,
                                    } {
                                ::core::panicking::panic("assertion failed: match Category::of(&expr.kind).unwrap() {\n    Category::Rvalue(RvalueFunc::Into) => false,\n    Category::Place => false,\n    _ => true,\n}")
                            };
                        };
                        let rvalue =
                            {
                                let BlockAnd(b, v) = this.as_local_rvalue(block, expr_id);
                                block = b;
                                v
                            };
                        this.cfg.push_assign(block, source_info, destination,
                            rvalue);
                        block.unit()
                    }
                    ExprKind::Reborrow { source, mutability, target } => {
                        let place =
                            {
                                let BlockAnd(b, v) = this.as_place(block, source);
                                block = b;
                                v
                            };
                        this.cfg.push_assign(block, source_info, destination,
                            Rvalue::Reborrow(target, mutability, place));
                        block.unit()
                    }
                };
            if !expr_is_block_or_scope {
                let popped = this.block_context.pop();
                if !popped.is_some() {
                    ::core::panicking::panic("assertion failed: popped.is_some()")
                };
            }
            block_and
        }
    }
}#[instrument(level = "debug", skip(self))]
25    pub(crate) fn expr_into_dest(
26        &mut self,
27        destination: Place<'tcx>,
28        mut block: BasicBlock,
29        expr_id: ExprId,
30    ) -> BlockAnd<()> {
31        // since we frequently have to reference `self` from within a
32        // closure, where `self` would be shadowed, it's easier to
33        // just use the name `this` uniformly
34        let this = self; // See "LET_THIS_SELF".
35        let expr = &this.thir[expr_id];
36        let expr_span = expr.span;
37        let source_info = this.source_info(expr_span);
38
39        let expr_is_block_or_scope =
40            matches!(expr.kind, ExprKind::Block { .. } | ExprKind::Scope { .. });
41
42        if !expr_is_block_or_scope {
43            this.block_context.push(BlockFrame::SubExpr);
44        }
45
46        let block_and = match expr.kind {
47            ExprKind::Scope { region_scope, hir_id, value } => {
48                let region_scope = (region_scope, source_info);
49                this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| {
50                    this.push_coverage_point_for_expr(block, source_info, hir_id);
51                    this.expr_into_dest(destination, block, value)
52                })
53            }
54            ExprKind::Block { block: ast_block } => {
55                this.ast_block(destination, block, ast_block, source_info)
56            }
57            ExprKind::Match { scrutinee, ref arms, .. } => {
58                this.match_expr(destination, block, scrutinee, arms, expr_span)
59            }
60            ExprKind::If { cond, then, else_opt, if_then_scope } => {
61                let then_span = this.thir[then].span;
62                let then_source_info = this.source_info(then_span);
63                let condition_scope = this.local_scope();
64
65                let true_and_false_blocks = this.in_scope(
66                    (if_then_scope, then_source_info),
67                    LintLevel::Inherited,
68                    |this| {
69                        // FIXME: Does this need extra logic to handle let-chains?
70                        let source_info = if this.is_let(cond) {
71                            let variable_scope =
72                                this.new_source_scope(then_span, LintLevel::Inherited);
73                            this.source_scope = variable_scope;
74                            SourceInfo { span: then_span, scope: variable_scope }
75                        } else {
76                            this.source_info(then_span)
77                        };
78
79                        // Lower the condition, and have it branch into *true* and *false* blocks.
80                        let (true_block, false_block) =
81                            this.in_if_then_scope(condition_scope, then_span, |this| {
82                                let true_block = this
83                                    .lower_if_condition(
84                                        block,
85                                        cond,
86                                        LowerIfCondArgs {
87                                            temp_scope_override: Some(condition_scope),
88                                            variable_source_info: source_info,
89                                            declare_let_bindings: DeclareLetBindings::Yes,
90                                        },
91                                    )
92                                    .into_block();
93
94                                // Lower the `then` arm into its block.
95                                this.expr_into_dest(destination, true_block, then)
96                            });
97
98                        // Pack `(true_block, false_block)` into `BlockAnd<BasicBlock>`.
99                        true_block.and(false_block)
100                    },
101                );
102
103                // Unpack `BlockAnd<BasicBlock>` into `(true_block, false_block)`.
104                let (true_block, mut false_block);
105                false_block = unpack!(true_block = true_and_false_blocks);
106
107                // If there is an `else` arm, lower it into `false_block`.
108                if let Some(else_expr) = else_opt {
109                    false_block =
110                        this.expr_into_dest(destination, false_block, else_expr).into_block();
111                } else {
112                    // There is no `else` arm, so we know both arms have type `()`.
113                    // Generate the implicit `else {}` by assigning unit.
114                    let correct_si = this.source_info(expr_span.shrink_to_hi());
115                    this.push_coverage_point_for_implicit_else(false_block, correct_si, expr);
116                    this.cfg.push_assign_unit(false_block, correct_si, destination, this.tcx);
117                }
118
119                // The `then` and `else` arms have been lowered into their respective
120                // blocks, so make both of them meet up in a new block.
121                let join_block = this.cfg.start_new_block();
122                this.cfg.goto(true_block, source_info, join_block);
123                this.cfg.goto(false_block, source_info, join_block);
124                join_block.unit()
125            }
126            ExprKind::Let { .. } => {
127                // After desugaring, `let` expressions should only appear inside `if`
128                // expressions or `match` guards, possibly nested within a let-chain.
129                // In both cases they are specifically handled by the lowerings of
130                // those expressions, so this case is currently unreachable.
131                span_bug!(expr_span, "unexpected let expression outside of if or match-guard");
132            }
133            ExprKind::NeverToAny { source } => {
134                let source_expr = &this.thir[source];
135                let is_call =
136                    matches!(source_expr.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. });
137
138                // (#66975) Source could be a const of type `!`, so has to
139                // exist in the generated MIR.
140                unpack!(
141                    block =
142                        this.as_temp(block, this.local_temp_lifetime(), source, Mutability::Mut)
143                );
144
145                // This is an optimization. If the expression was a call then we already have an
146                // unreachable block. Don't bother to terminate it and create a new one.
147                if is_call {
148                    block.unit()
149                } else {
150                    this.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
151                    let end_block = this.cfg.start_new_block();
152                    end_block.unit()
153                }
154            }
155            ExprKind::LogicalOp { op, lhs, rhs } => {
156                let condition_scope = this.local_scope();
157                let source_info = this.source_info(expr.span);
158
159                // We first evaluate the left-hand side of the predicate ...
160                let (true_block, false_block) =
161                    this.in_if_then_scope(condition_scope, expr.span, |this| {
162                        this.lower_if_condition(
163                            block,
164                            lhs,
165                            LowerIfCondArgs {
166                                temp_scope_override: Some(condition_scope),
167                                variable_source_info: source_info,
168                                declare_let_bindings: DeclareLetBindings::LetNotPermitted,
169                            },
170                        )
171                    });
172
173                // At this point, the control flow splits into a short-circuiting path
174                // and a continuation path.
175                // - If the operator is `&&`, passing `lhs` leads to continuation of evaluation on `rhs`;
176                //   failing it leads to the short-circuting path which assigns `false` to the place.
177                // - If the operator is `||`, failing `lhs` leads to continuation of evaluation on `rhs`;
178                //   passing it leads to the short-circuting path which assigns `true` to the place.
179                let (short_circuit_block, short_circuit_value, continue_block) = match op {
180                    LogicalOp::And => (false_block, false, true_block),
181                    LogicalOp::Or => (true_block, true, false_block),
182                };
183                this.cfg.push_assign_constant(
184                    short_circuit_block,
185                    source_info,
186                    destination,
187                    ConstOperand {
188                        span: expr.span,
189                        user_ty: None,
190                        const_: Const::from_bool(this.tcx, short_circuit_value),
191                    },
192                );
193                let mut rhs_block =
194                    this.expr_into_dest(destination, continue_block, rhs).into_block();
195                // Instrument the lowered RHS's value for condition coverage.
196                // (Does nothing if condition coverage is not enabled.)
197                this.visit_coverage_standalone_condition(rhs, destination, &mut rhs_block);
198
199                // Reunite the continuation path and the short-circuit path.
200                let join_block = this.cfg.start_new_block();
201                this.cfg.goto(rhs_block, source_info, join_block);
202                this.cfg.goto(short_circuit_block, source_info, join_block);
203                join_block.unit()
204            }
205            ExprKind::Loop { body } => {
206                // [block]
207                //    |
208                //   [loop_block] -> [body_block] -/eval. body/-> [body_block_end]
209                //    |        ^                                         |
210                // false link  |                                         |
211                //    |        +-----------------------------------------+
212                //    +-> [diverge_cleanup]
213                // The false link is required to make sure borrowck considers unwinds through the
214                // body, even when the exact code in the body cannot unwind
215
216                let loop_block = this.cfg.start_new_block();
217
218                // Start the loop.
219                this.cfg.goto(block, source_info, loop_block);
220
221                this.in_breakable_scope(Some(loop_block), destination, expr_span, move |this| {
222                    // conduct the test, if necessary
223                    let body_block = this.cfg.start_new_block();
224                    this.cfg.terminate(
225                        loop_block,
226                        source_info,
227                        TerminatorKind::FalseUnwind {
228                            real_target: body_block,
229                            unwind: UnwindAction::Continue,
230                        },
231                    );
232                    this.diverge_from(loop_block);
233
234                    // The “return” value of the loop body must always be a unit. We therefore
235                    // introduce a unit temporary as the destination for the loop body.
236                    let tmp = this.get_unit_temp();
237                    // Execute the body, branching back to the test.
238                    let body_block_end = this.expr_into_dest(tmp, body_block, body).into_block();
239
240                    let goto = this.cfg.goto(body_block_end, source_info, loop_block);
241                    if let Some(attrs) = this.thir.attributes.get(&expr_id) {
242                        goto.attributes = attrs.clone();
243                    }
244
245                    // Loops are only exited by `break` expressions.
246                    None
247                })
248            }
249            ExprKind::LoopMatch {
250                state,
251                region_scope,
252                match_data: LoopMatchMatchData { ref arms, span: match_span, scrutinee },
253            } => {
254                // Intuitively, this is a combination of a loop containing a labeled block
255                // containing a match.
256                //
257                // The only new bit here is that the lowering of the match is wrapped in a
258                // `in_const_continuable_scope`, which makes the match arms and their target basic
259                // block available to the lowering of `#[const_continue]`.
260
261                fn is_supported_loop_match_type(ty: Ty<'_>) -> bool {
262                    match ty.kind() {
263                        ty::Uint(_) | ty::Int(_) | ty::Float(_) | ty::Bool | ty::Char => true,
264                        ty::Adt(adt_def, _) => match adt_def.adt_kind() {
265                            ty::AdtKind::Struct | ty::AdtKind::Union => false,
266                            ty::AdtKind::Enum => {
267                                adt_def.variants().iter().all(|v| v.fields.is_empty())
268                            }
269                        },
270                        _ => false,
271                    }
272                }
273
274                let state_ty = this.thir.exprs[state].ty;
275                if !is_supported_loop_match_type(state_ty) {
276                    let span = this.thir.exprs[state].span;
277                    this.tcx.dcx().emit_fatal(LoopMatchUnsupportedType { span, ty: state_ty })
278                }
279
280                let loop_block = this.cfg.start_new_block();
281
282                // Start the loop.
283                this.cfg.goto(block, source_info, loop_block);
284
285                this.in_breakable_scope(Some(loop_block), destination, expr_span, |this| {
286                    // Logic for `loop`.
287                    let mut body_block = this.cfg.start_new_block();
288                    this.cfg.terminate(
289                        loop_block,
290                        source_info,
291                        TerminatorKind::FalseUnwind {
292                            real_target: body_block,
293                            unwind: UnwindAction::Continue,
294                        },
295                    );
296                    this.diverge_from(loop_block);
297
298                    // Logic for `match`.
299                    let scrutinee_span = this.thir.exprs[scrutinee].span;
300                    let scrutinee_place_builder =
301                        unpack!(body_block = this.lower_scrutinee(body_block, scrutinee));
302
303                    let match_start_span = match_span.shrink_to_lo().to(scrutinee_span);
304
305                    let mut patterns = Vec::with_capacity(arms.len());
306                    for &arm_id in arms.iter() {
307                        let arm = &this.thir[arm_id];
308
309                        if let Some(guard) = arm.guard {
310                            let span = this.thir.exprs[guard].span;
311                            this.tcx.dcx().emit_fatal(LoopMatchArmWithGuard { span })
312                        }
313
314                        patterns.push((&*arm.pattern, HasMatchGuard::No));
315                    }
316
317                    // The `built_tree` maps match arms to their basic block (where control flow
318                    // jumps to when a value matches the arm). This structure is stored so that a
319                    // `#[const_continue]` can figure out what basic block to jump to.
320                    let built_tree = this.lower_match_tree(
321                        body_block,
322                        scrutinee_span,
323                        &scrutinee_place_builder,
324                        match_start_span,
325                        patterns,
326                        Exhaustive::Yes,
327                    );
328
329                    let state_place = scrutinee_place_builder.to_place(this);
330                    let state_result = this.temp(state_ty, expr_span);
331                    let state_result_place = Place::from(state_result);
332
333                    // This is logic for the labeled block: a block is a drop scope, hence
334                    // `in_scope`, and a labeled block can be broken out of with a `break 'label`,
335                    // hence the `in_breakable_scope`.
336                    //
337                    // The state update is still modeled like `state = 'blk: { ... }`: normal
338                    // match arm results and ordinary breaks to the block are first written to
339                    // `state_result_place`, then written back to `state_place`. This avoids
340                    // building an overlapping assignment like `state = state`.
341                    //
342                    // Then `in_const_continuable_scope` stores information for the lowering of
343                    // `#[const_continue]`, which still updates the actual `state_place` directly
344                    // so it can jump to the statically known next match branch.
345                    unpack!(
346                        body_block = this.in_scope(
347                            (region_scope, source_info),
348                            LintLevel::Inherited,
349                            move |this| {
350                                this.in_const_continuable_scope(
351                                    arms.clone(),
352                                    built_tree.clone(),
353                                    state_place,
354                                    expr_span,
355                                    |this| {
356                                        let block = this
357                                            .in_breakable_scope(
358                                                None,
359                                                state_result_place,
360                                                expr_span,
361                                                |this| {
362                                                    Some(this.lower_match_arms(
363                                                        state_result_place,
364                                                        scrutinee_place_builder,
365                                                        scrutinee_span,
366                                                        arms,
367                                                        built_tree,
368                                                        this.source_info(match_span),
369                                                    ))
370                                                },
371                                            )
372                                            .into_block();
373
374                                        this.cfg.push_assign(
375                                            block,
376                                            source_info,
377                                            state_place,
378                                            Rvalue::Use(
379                                                this.consume_by_copy_or_move(state_result_place),
380                                                WithRetag::Yes,
381                                            ),
382                                        );
383                                        block.unit()
384                                    },
385                                )
386                            }
387                        )
388                    );
389
390                    this.cfg.goto(body_block, source_info, loop_block);
391
392                    // Loops are only exited by `break` expressions.
393                    None
394                })
395            }
396            // Some intrinsics are handled here because they desperately want to avoid introducing
397            // unnecessary copies.
398            ExprKind::Call { ty, fun, ref args, .. }
399                if let ty::FnDef(def_id, generic_args) = *ty.kind()
400                    && let Some(intrinsic) = this.tcx.intrinsic(def_id)
401                    && matches!(intrinsic.name, sym::write_via_move | sym::write_box_via_move) =>
402            {
403                let generic_args = generic_args.no_bound_vars().unwrap();
404                // We still have to evaluate the callee expression as normal (but we don't care
405                // about its result).
406                let _fun = unpack!(block = this.as_local_operand(block, fun));
407
408                match intrinsic.name {
409                    sym::write_via_move => {
410                        // `write_via_move(ptr, val)` becomes `*ptr = val` but without any dropping.
411
412                        // The destination must have unit type (so we don't actually have to store anything
413                        // into it).
414                        assert!(destination.ty(&this.local_decls, this.tcx).ty.is_unit());
415
416                        // Compile this to an assignment of the argument into the destination.
417                        let [ptr, val] = **args else {
418                            span_bug!(expr_span, "invalid write_via_move call")
419                        };
420                        let Some(ptr) = unpack!(block = this.as_local_operand(block, ptr)).place()
421                        else {
422                            span_bug!(expr_span, "invalid write_via_move call")
423                        };
424                        let ptr_deref = ptr.project_deeper(&[ProjectionElem::Deref], this.tcx);
425                        this.expr_into_dest(ptr_deref, block, val)
426                    }
427                    sym::write_box_via_move => {
428                        // The signature is:
429                        // `fn write_box_via_move<T>(b: Box<MaybeUninit<T>>, val: T) -> Box<MaybeUninit<T>>`.
430                        // `write_box_via_move(b, val)` becomes
431                        // ```
432                        // (*b).value.value.value = val;
433                        // b
434                        // ```
435                        // One crucial aspect of this lowering is that the generated code must
436                        // cause the borrow checker to enforce that `val` lives sufficiently
437                        // long to be stored in `b`. The above lowering does this; anything that
438                        // involves a `*const T` or a `NonNull<T>` does not as those are covariant.
439
440                        // Extract the operands, compile `b`.
441                        let [b, val] = **args else {
442                            span_bug!(expr_span, "invalid init_box_via_move call")
443                        };
444                        let Some(b) = unpack!(block = this.as_local_operand(block, b)).place()
445                        else {
446                            span_bug!(expr_span, "invalid init_box_via_move call")
447                        };
448                        let tcx = this.tcx;
449                        let decls = &this.local_decls;
450
451                        // `b` is a `Box<MaybeUninit<T>>`.
452                        let place = b.project_deeper(&[ProjectionElem::Deref], tcx);
453                        // Current type: `MaybeUninit<T>`. Field #1 is `ManuallyDrop<T>`.
454                        let place = place.project_to_field(FieldIdx::from_u32(1), decls, tcx);
455                        // Current type: `ManuallyDrop<T>`. Field #0 is `T`.
456                        let place = place.project_to_field(FieldIdx::ZERO, decls, tcx);
457                        // Sanity check.
458                        assert_eq!(place.ty(decls, tcx).ty, generic_args.type_at(0));
459
460                        // Store `val` into place.
461                        unpack!(block = this.expr_into_dest(place, block, val));
462
463                        // Return `b`
464                        this.cfg.push_assign(
465                            block,
466                            source_info,
467                            destination,
468                            // Move from `b` so that does not get dropped any more.
469                            Rvalue::Use(Operand::Move(b), WithRetag::Yes),
470                        );
471                        block.unit()
472                    }
473                    _ => rustc_span::bug!(),
474                }
475            }
476            ExprKind::Call { ty: _, fun, ref args, from_hir_call, fn_span } => {
477                let fun = unpack!(block = this.as_local_operand(block, fun));
478                let args: Box<[_]> = args
479                    .into_iter()
480                    .copied()
481                    .map(|arg| Spanned {
482                        node: unpack!(block = this.as_local_call_operand(block, arg)),
483                        span: this.thir.exprs[arg].span,
484                    })
485                    .collect();
486
487                let success = this.cfg.start_new_block();
488
489                this.record_operands_moved(&args);
490
491                debug!("expr_into_dest: fn_span={:?}", fn_span);
492
493                this.cfg.terminate(
494                    block,
495                    source_info,
496                    TerminatorKind::Call {
497                        func: fun,
498                        args,
499                        unwind: UnwindAction::Continue,
500                        destination,
501                        target: Some(success),
502                        call_source: if from_hir_call {
503                            CallSource::Normal
504                        } else {
505                            CallSource::OverloadedOperator
506                        },
507                        fn_span,
508                    },
509                );
510                this.diverge_from(block);
511                success.unit()
512            }
513            ExprKind::ByUse { expr, span } => {
514                let place = unpack!(block = this.as_place(block, expr));
515                let ty = place.ty(&this.local_decls, this.tcx).ty;
516
517                if this.tcx.type_is_copy_modulo_regions(this.infcx.typing_env(this.param_env), ty) {
518                    this.cfg.push_assign(
519                        block,
520                        source_info,
521                        destination,
522                        Rvalue::Use(Operand::Copy(place), WithRetag::Yes),
523                    );
524                    block.unit()
525                } else if this.infcx.type_is_use_cloned_modulo_regions(this.param_env, ty) {
526                    // Convert `expr.use` to a call like `Clone::clone(&expr)`
527                    let success = this.cfg.start_new_block();
528                    let clone_trait = this.tcx.require_lang_item(LangItem::Clone, span);
529                    let clone_fn = this.tcx.associated_item_def_ids(clone_trait)[0];
530                    let func =
531                        Operand::function_handle(this.tcx, clone_fn, &[ty.into()], expr_span);
532                    let ref_ty = Ty::new_imm_ref(this.tcx, this.tcx.lifetimes.re_erased, ty);
533                    let ref_place = this.temp(ref_ty, span);
534                    this.cfg.push_assign(
535                        block,
536                        source_info,
537                        ref_place,
538                        Rvalue::Ref(this.tcx.lifetimes.re_erased, BorrowKind::Shared, place),
539                    );
540                    this.cfg.terminate(
541                        block,
542                        source_info,
543                        TerminatorKind::Call {
544                            func,
545                            args: [Spanned { node: Operand::Move(ref_place), span: DUMMY_SP }]
546                                .into(),
547                            destination,
548                            target: Some(success),
549                            unwind: UnwindAction::Unreachable,
550                            call_source: CallSource::Use,
551                            fn_span: expr_span,
552                        },
553                    );
554                    success.unit()
555                } else {
556                    this.cfg.push_assign(
557                        block,
558                        source_info,
559                        destination,
560                        Rvalue::Use(Operand::Move(place), WithRetag::Yes),
561                    );
562                    block.unit()
563                }
564            }
565            ExprKind::ValueExpr { source } => this.expr_into_dest(destination, block, source),
566            ExprKind::Borrow { arg, borrow_kind } => {
567                // We don't do this in `as_rvalue` because we use `as_place`
568                // for borrow expressions, so we cannot create an `RValue` that
569                // remains valid across user code. `as_rvalue` is usually called
570                // by this method anyway, so this shouldn't cause too many
571                // unnecessary temporaries.
572                let arg_place = match borrow_kind {
573                    BorrowKind::Shared => {
574                        unpack!(block = this.as_read_only_place(block, arg))
575                    }
576                    _ => unpack!(block = this.as_place(block, arg)),
577                };
578                let borrow = Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place);
579                this.cfg.push_assign(block, source_info, destination, borrow);
580                block.unit()
581            }
582            ExprKind::RawBorrow { mutability, arg } => {
583                let place = match mutability {
584                    hir::Mutability::Not => this.as_read_only_place(block, arg),
585                    hir::Mutability::Mut => this.as_place(block, arg),
586                };
587                let address_of = Rvalue::RawPtr(mutability.into(), unpack!(block = place));
588                this.cfg.push_assign(block, source_info, destination, address_of);
589                block.unit()
590            }
591            ExprKind::Adt(AdtExpr {
592                adt_def,
593                variant_index,
594                args,
595                ref user_ty,
596                ref fields,
597                ref base,
598            }) => {
599                // See the notes for `ExprKind::Array` in `as_rvalue` and for
600                // `ExprKind::Borrow` above.
601                let is_union = adt_def.is_union();
602                let active_field_index = is_union.then(|| fields[0].name);
603
604                let scope = this.local_temp_lifetime();
605
606                // first process the set of fields that were provided
607                // (evaluating them in order given by user)
608                let fields_map: FxHashMap<_, _> = fields
609                    .into_iter()
610                    .map(|f| {
611                        (
612                            f.name,
613                            unpack!(
614                                block = this.as_operand(
615                                    block,
616                                    scope,
617                                    f.expr,
618                                    LocalInfo::AggregateTemp,
619                                    NeedsTemporary::Maybe,
620                                )
621                            ),
622                        )
623                    })
624                    .collect();
625
626                let variant = adt_def.variant(variant_index);
627                let field_names = variant.fields.indices();
628
629                let fields = match base {
630                    AdtExprBase::None => {
631                        field_names.filter_map(|n| fields_map.get(&n).cloned()).collect()
632                    }
633                    AdtExprBase::Base(FruInfo { base, field_types }) => {
634                        let place_builder = unpack!(block = this.as_place_builder(block, *base));
635
636                        // We desugar FRU as we lower to MIR, so for each
637                        // base-supplied field, generate an operand that
638                        // reads it from the base.
639                        itertools::zip_eq(field_names, &**field_types)
640                            .map(|(n, ty)| match fields_map.get(&n) {
641                                Some(v) => v.clone(),
642                                None => {
643                                    let place =
644                                        place_builder.clone_project(PlaceElem::Field(n, *ty));
645                                    this.consume_by_copy_or_move(place.to_place(this))
646                                }
647                            })
648                            .collect()
649                    }
650                    AdtExprBase::DefaultFields(field_types) => {
651                        itertools::zip_eq(field_names, field_types)
652                            .map(|(n, &ty)| match fields_map.get(&n) {
653                                Some(v) => v.clone(),
654                                None => match variant.fields[n].value {
655                                    Some(def) => {
656                                        let value = Const::Unevaluated(
657                                            UnevaluatedConst::new(def, args),
658                                            ty,
659                                        );
660                                        Operand::Constant(Box::new(ConstOperand {
661                                            span: expr_span,
662                                            user_ty: None,
663                                            const_: value,
664                                        }))
665                                    }
666                                    None => {
667                                        let name = variant.fields[n].name;
668                                        span_bug!(
669                                            expr_span,
670                                            "missing mandatory field `{name}` of type `{ty}`",
671                                        );
672                                    }
673                                },
674                            })
675                            .collect()
676                    }
677                };
678
679                let inferred_ty = expr.ty;
680                let user_ty = user_ty.as_ref().map(|user_ty| {
681                    this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
682                        span: source_info.span,
683                        user_ty: user_ty.clone(),
684                        inferred_ty,
685                    })
686                });
687                let adt = Box::new(AggregateKind::Adt(
688                    adt_def.did(),
689                    variant_index,
690                    args,
691                    user_ty,
692                    active_field_index,
693                ));
694                this.cfg.push_assign(
695                    block,
696                    source_info,
697                    destination,
698                    Rvalue::Aggregate(adt, fields),
699                );
700                block.unit()
701            }
702            ExprKind::InlineAsm(InlineAsmExpr {
703                asm_macro,
704                template,
705                ref operands,
706                options,
707                line_spans,
708            }) => {
709                use rustc_middle::{mir, thir};
710
711                let destination_block = this.cfg.start_new_block();
712                let mut targets =
713                    if asm_macro.diverges(options) { vec![] } else { vec![destination_block] };
714
715                let operands = operands
716                    .into_iter()
717                    .map(|op| match *op {
718                        thir::InlineAsmOperand::In { reg, expr } => mir::InlineAsmOperand::In {
719                            reg,
720                            value: unpack!(block = this.as_local_operand(block, expr)),
721                        },
722                        thir::InlineAsmOperand::Out { reg, late, expr } => {
723                            mir::InlineAsmOperand::Out {
724                                reg,
725                                late,
726                                place: expr.map(|expr| unpack!(block = this.as_place(block, expr))),
727                            }
728                        }
729                        thir::InlineAsmOperand::InOut { reg, late, expr } => {
730                            let place = unpack!(block = this.as_place(block, expr));
731                            mir::InlineAsmOperand::InOut {
732                                reg,
733                                late,
734                                // This works because asm operands must be Copy
735                                in_value: Operand::Copy(place),
736                                out_place: Some(place),
737                            }
738                        }
739                        thir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
740                            mir::InlineAsmOperand::InOut {
741                                reg,
742                                late,
743                                in_value: unpack!(block = this.as_local_operand(block, in_expr)),
744                                out_place: out_expr.map(|out_expr| {
745                                    unpack!(block = this.as_place(block, out_expr))
746                                }),
747                            }
748                        }
749                        thir::InlineAsmOperand::Const { value, span } => {
750                            mir::InlineAsmOperand::Const {
751                                value: Box::new(ConstOperand {
752                                    span,
753                                    user_ty: None,
754                                    const_: value,
755                                }),
756                            }
757                        }
758                        thir::InlineAsmOperand::SymFn { value } => mir::InlineAsmOperand::SymFn {
759                            value: Box::new(this.as_constant(&this.thir[value])),
760                        },
761                        thir::InlineAsmOperand::SymStatic { def_id } => {
762                            mir::InlineAsmOperand::SymStatic { def_id }
763                        }
764                        thir::InlineAsmOperand::Label { block } => {
765                            let target = this.cfg.start_new_block();
766                            let target_index = targets.len();
767                            targets.push(target);
768
769                            let tmp = this.get_unit_temp();
770                            let target =
771                                this.ast_block(tmp, target, block, source_info).into_block();
772                            this.cfg.terminate(
773                                target,
774                                source_info,
775                                TerminatorKind::Goto { target: destination_block },
776                            );
777
778                            mir::InlineAsmOperand::Label { target_index }
779                        }
780                    })
781                    .collect();
782
783                if !expr.ty.is_never() {
784                    this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
785                }
786
787                let asm_macro = match asm_macro {
788                    AsmMacro::Asm | AsmMacro::GlobalAsm => InlineAsmMacro::Asm,
789                    AsmMacro::NakedAsm => InlineAsmMacro::NakedAsm,
790                };
791
792                this.cfg.terminate(
793                    block,
794                    source_info,
795                    TerminatorKind::InlineAsm {
796                        asm_macro,
797                        template,
798                        operands,
799                        options,
800                        line_spans,
801                        targets: targets.into_boxed_slice(),
802                        unwind: if options.contains(InlineAsmOptions::MAY_UNWIND) {
803                            UnwindAction::Continue
804                        } else {
805                            UnwindAction::Unreachable
806                        },
807                    },
808                );
809                if options.contains(InlineAsmOptions::MAY_UNWIND) {
810                    this.diverge_from(block);
811                }
812                destination_block.unit()
813            }
814
815            // These cases don't actually need a destination
816            ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
817                block = this.stmt_expr(block, expr_id, None).into_block();
818                this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
819                block.unit()
820            }
821
822            ExprKind::Continue { .. }
823            | ExprKind::ConstContinue { .. }
824            | ExprKind::Break { .. }
825            | ExprKind::Return { .. }
826            | ExprKind::Become { .. } => {
827                block = this.stmt_expr(block, expr_id, None).into_block();
828                // No assign, as these have type `!`.
829                block.unit()
830            }
831
832            // Avoid creating a temporary
833            ExprKind::VarRef { .. }
834            | ExprKind::UpvarRef { .. }
835            | ExprKind::PlaceTypeAscription { .. }
836            | ExprKind::ValueTypeAscription { .. }
837            | ExprKind::PlaceUnwrapUnsafeBinder { .. }
838            | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
839                debug_assert!(Category::of(&expr.kind) == Some(Category::Place));
840
841                let place = unpack!(block = this.as_place(block, expr_id));
842                let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place), WithRetag::Yes);
843                this.cfg.push_assign(block, source_info, destination, rvalue);
844                block.unit()
845            }
846            ExprKind::Index { .. } | ExprKind::Deref { .. } | ExprKind::Field { .. } => {
847                debug_assert_eq!(Category::of(&expr.kind), Some(Category::Place));
848
849                // Create a "fake" temporary variable so that we check that the
850                // value is Sized. Usually, this is caught in type checking, but
851                // in the case of box expr there is no such check.
852                if !destination.projection.is_empty() {
853                    this.local_decls.push(LocalDecl::new(expr.ty, expr.span));
854                }
855
856                let place = unpack!(block = this.as_place(block, expr_id));
857                let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place), WithRetag::Yes);
858                this.cfg.push_assign(block, source_info, destination, rvalue);
859                block.unit()
860            }
861
862            ExprKind::Yield { value } => {
863                let scope = this.local_temp_lifetime();
864                let value = unpack!(
865                    block =
866                        this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
867                );
868                let resume = this.cfg.start_new_block();
869                this.cfg.terminate(
870                    block,
871                    source_info,
872                    TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None },
873                );
874                this.coroutine_drop_cleanup(block);
875                resume.unit()
876            }
877
878            // these are the cases that are more naturally handled by some other mode
879            ExprKind::Unary { .. }
880            | ExprKind::Binary { .. }
881            | ExprKind::Cast { .. }
882            | ExprKind::PointerCoercion { .. }
883            | ExprKind::Repeat { .. }
884            | ExprKind::Array { .. }
885            | ExprKind::Tuple { .. }
886            | ExprKind::Closure { .. }
887            | ExprKind::ConstBlock { .. }
888            | ExprKind::Literal { .. }
889            | ExprKind::NamedConst { .. }
890            | ExprKind::NonHirLiteral { .. }
891            | ExprKind::ZstLiteral { .. }
892            | ExprKind::ConstParam { .. }
893            | ExprKind::ThreadLocalRef(_)
894            | ExprKind::StaticRef { .. }
895            | ExprKind::WrapUnsafeBinder { .. } => {
896                debug_assert!(match Category::of(&expr.kind).unwrap() {
897                    // should be handled above
898                    Category::Rvalue(RvalueFunc::Into) => false,
899
900                    // must be handled above or else we get an
901                    // infinite loop in the builder; see
902                    // e.g., `ExprKind::VarRef` above
903                    Category::Place => false,
904
905                    _ => true,
906                });
907
908                let rvalue = unpack!(block = this.as_local_rvalue(block, expr_id));
909                this.cfg.push_assign(block, source_info, destination, rvalue);
910                block.unit()
911            }
912            ExprKind::Reborrow { source, mutability, target } => {
913                let place = unpack!(block = this.as_place(block, source));
914                this.cfg.push_assign(
915                    block,
916                    source_info,
917                    destination,
918                    Rvalue::Reborrow(target, mutability, place),
919                );
920                block.unit()
921            }
922        };
923
924        if !expr_is_block_or_scope {
925            let popped = this.block_context.pop();
926            assert!(popped.is_some());
927        }
928
929        block_and
930    }
931
932    fn is_let(&self, expr: ExprId) -> bool {
933        match self.thir[expr].kind {
934            ExprKind::Let { .. } => true,
935            ExprKind::Scope { value, .. } => self.is_let(value),
936            _ => false,
937        }
938    }
939}