Skip to main content

rustc_mir_build/builder/expr/
as_rvalue.rs

1//! See docs in `build/expr/mod.rs`.
2
3use rustc_abi::FieldIdx;
4use rustc_hir::lang_items::LangItem;
5use rustc_index::{Idx, IndexVec};
6use rustc_middle::bug;
7use rustc_middle::middle::region::{self, TempLifetime};
8use rustc_middle::mir::interpret::Scalar;
9use rustc_middle::mir::*;
10use rustc_middle::thir::*;
11use rustc_middle::ty::adjustment::PointerCoercion;
12use rustc_middle::ty::cast::{CastTy, mir_cast_kind};
13use rustc_middle::ty::util::IntTypeExt;
14use rustc_middle::ty::{self, Ty, UpvarArgs};
15use rustc_span::source_map::Spanned;
16use rustc_span::{DUMMY_SP, Span};
17use tracing::debug;
18
19use crate::builder::expr::as_place::PlaceBase;
20use crate::builder::expr::category::{Category, RvalueFunc};
21use crate::builder::scope::LintLevel;
22use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
23
24impl<'a, 'tcx> Builder<'a, 'tcx> {
25    /// Returns an rvalue suitable for use until the end of the current
26    /// scope expression.
27    ///
28    /// The operand returned from this function will *not be valid* after
29    /// an ExprKind::Scope is passed, so please do *not* return it from
30    /// functions to avoid bad miscompiles.
31    pub(crate) fn as_local_rvalue(
32        &mut self,
33        block: BasicBlock,
34        expr_id: ExprId,
35    ) -> BlockAnd<Rvalue<'tcx>> {
36        let local_scope = self.local_scope();
37        self.as_rvalue(
38            block,
39            TempLifetime { temp_lifetime: Some(local_scope), backwards_incompatible: None },
40            expr_id,
41        )
42    }
43
44    /// Compile `expr`, yielding an rvalue.
45    pub(crate) fn as_rvalue(
46        &mut self,
47        mut block: BasicBlock,
48        scope: TempLifetime,
49        expr_id: ExprId,
50    ) -> BlockAnd<Rvalue<'tcx>> {
51        let this = self; // See "LET_THIS_SELF".
52        let expr = &this.thir[expr_id];
53        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs:53",
                        "rustc_mir_build::builder::expr::as_rvalue",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(53u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_rvalue"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expr_as_rvalue(block={0:?}, scope={1:?}, expr={2:?})",
                                                    block, scope, expr) as &dyn Value))])
            });
    } else { ; }
};debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
54
55        let expr_span = expr.span;
56        let source_info = this.source_info(expr_span);
57
58        match expr.kind {
59            ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
60            ExprKind::Scope { region_scope, hir_id, value } => {
61                let region_scope = (region_scope, source_info);
62                this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| {
63                    this.as_rvalue(block, scope, value)
64                })
65            }
66            ExprKind::Repeat { value, count } => {
67                if Some(0) == count.try_to_target_usize(this.tcx) {
68                    this.build_zero_repeat(block, value, scope, source_info)
69                } else {
70                    let value_operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, value, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
71                        block = this.as_operand(
72                            block,
73                            scope,
74                            value,
75                            LocalInfo::Boring,
76                            NeedsTemporary::No
77                        )
78                    );
79                    block.and(Rvalue::Repeat(value_operand, count))
80                }
81            }
82            ExprKind::Binary { op, lhs, rhs } => {
83                let lhs = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, lhs, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
84                    block = this.as_operand(
85                        block,
86                        scope,
87                        lhs,
88                        LocalInfo::Boring,
89                        NeedsTemporary::Maybe
90                    )
91                );
92                let rhs = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, rhs, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
93                    block =
94                        this.as_operand(block, scope, rhs, LocalInfo::Boring, NeedsTemporary::No)
95                );
96                this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
97            }
98            ExprKind::Unary { op, arg } => {
99                let arg = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, arg, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
100                    block =
101                        this.as_operand(block, scope, arg, LocalInfo::Boring, NeedsTemporary::No)
102                );
103                // Check for -MIN on signed integers
104                if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
105                    let bool_ty = this.tcx.types.bool;
106
107                    let minval = this.minval_literal(expr_span, expr.ty);
108                    let is_min = this.temp(bool_ty, expr_span);
109
110                    this.cfg.push_assign(
111                        block,
112                        source_info,
113                        is_min,
114                        Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
115                    );
116
117                    block = this.assert(
118                        block,
119                        Operand::Move(is_min),
120                        false,
121                        AssertKind::OverflowNeg(arg.to_copy()),
122                        expr_span,
123                    );
124                }
125                block.and(Rvalue::UnaryOp(op, arg))
126            }
127            ExprKind::Box { value } => {
128                let value_ty = this.thir[value].ty;
129                let tcx = this.tcx;
130                let source_info = this.source_info(expr_span);
131
132                let size = tcx.require_lang_item(LangItem::SizeOf, expr_span);
133                let size = Operand::unevaluated_constant(tcx, size, &[value_ty.into()], expr_span);
134
135                let align = tcx.require_lang_item(LangItem::AlignOf, expr_span);
136                let align =
137                    Operand::unevaluated_constant(tcx, align, &[value_ty.into()], expr_span);
138
139                // malloc some memory of suitable size and align:
140                let exchange_malloc = Operand::function_handle(
141                    tcx,
142                    tcx.require_lang_item(LangItem::ExchangeMalloc, expr_span),
143                    [],
144                    expr_span,
145                );
146                let storage = this.temp(Ty::new_mut_ptr(tcx, tcx.types.u8), expr_span);
147                let success = this.cfg.start_new_block();
148                this.cfg.terminate(
149                    block,
150                    source_info,
151                    TerminatorKind::Call {
152                        func: exchange_malloc,
153                        args: [
154                            Spanned { node: size, span: DUMMY_SP },
155                            Spanned { node: align, span: DUMMY_SP },
156                        ]
157                        .into(),
158                        destination: storage,
159                        target: Some(success),
160                        unwind: UnwindAction::Continue,
161                        call_source: CallSource::Misc,
162                        fn_span: expr_span,
163                    },
164                );
165                this.diverge_from(block);
166                block = success;
167
168                let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span));
169                this.cfg
170                    .push(block, Statement::new(source_info, StatementKind::StorageLive(result)));
171                if let Some(scope) = scope.temp_lifetime {
172                    // schedule a shallow free of that memory, lest we unwind:
173                    this.schedule_drop_storage_and_value(expr_span, scope, result);
174                }
175
176                // Transmute `*mut u8` to the box (thus far, uninitialized):
177                let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value_ty);
178                this.cfg.push_assign(block, source_info, Place::from(result), box_);
179
180                // initialize the box contents:
181                block = this
182                    .expr_into_dest(this.tcx.mk_place_deref(Place::from(result)), block, value)
183                    .into_block();
184                block.and(Rvalue::Use(Operand::Move(Place::from(result))))
185            }
186            ExprKind::Cast { source } => {
187                let source_expr = &this.thir[source];
188
189                // Casting an enum to an integer is equivalent to computing the discriminant and casting the
190                // discriminant. Previously every backend had to repeat the logic for this operation. Now we
191                // create all the steps directly in MIR with operations all backends need to support anyway.
192                let (source, ty) = if let ty::Adt(adt_def, ..) = source_expr.ty.kind()
193                    && adt_def.is_enum()
194                {
195                    let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
196                    let temp = {
    let BlockAnd(b, v) = this.as_temp(block, scope, source, Mutability::Not);
    block = b;
    v
}unpack!(block = this.as_temp(block, scope, source, Mutability::Not));
197                    let discr = this.temp(discr_ty, source_expr.span);
198                    this.cfg.push_assign(
199                        block,
200                        source_info,
201                        discr,
202                        Rvalue::Discriminant(temp.into()),
203                    );
204                    (Operand::Move(discr), discr_ty)
205                } else {
206                    let ty = source_expr.ty;
207                    let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
208                        block = this.as_operand(
209                            block,
210                            scope,
211                            source,
212                            LocalInfo::Boring,
213                            NeedsTemporary::No
214                        )
215                    );
216                    (source, ty)
217                };
218                let from_ty = CastTy::from_ty(ty);
219                let cast_ty = CastTy::from_ty(expr.ty);
220                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs:220",
                        "rustc_mir_build::builder::expr::as_rvalue",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(220u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_rvalue"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ExprKind::Cast from_ty={1:?}, cast_ty={0:?}/{2:?}",
                                                    expr.ty, from_ty, cast_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("ExprKind::Cast from_ty={from_ty:?}, cast_ty={:?}/{cast_ty:?}", expr.ty);
221                let cast_kind = mir_cast_kind(ty, expr.ty);
222                block.and(Rvalue::Cast(cast_kind, source, expr.ty))
223            }
224            ExprKind::PointerCoercion { cast, source, is_from_as_cast } => {
225                let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
226                    block = this.as_operand(
227                        block,
228                        scope,
229                        source,
230                        LocalInfo::Boring,
231                        NeedsTemporary::No
232                    )
233                );
234                let origin =
235                    if is_from_as_cast { CoercionSource::AsCast } else { CoercionSource::Implicit };
236                block.and(Rvalue::Cast(CastKind::PointerCoercion(cast, origin), source, expr.ty))
237            }
238            ExprKind::Array { ref fields } => {
239                // (*) We would (maybe) be closer to codegen if we
240                // handled this and other aggregate cases via
241                // `into()`, not `as_rvalue` -- in that case, instead
242                // of generating
243                //
244                //     let tmp1 = ...1;
245                //     let tmp2 = ...2;
246                //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
247                //
248                // we could just generate
249                //
250                //     dest.f = ...1;
251                //     dest.g = ...2;
252                //
253                // The problem is that then we would need to:
254                //
255                // (a) have a more complex mechanism for handling
256                //     partial cleanup;
257                // (b) distinguish the case where the type `Foo` has a
258                //     destructor, in which case creating an instance
259                //     as a whole "arms" the destructor, and you can't
260                //     write individual fields; and,
261                // (c) handle the case where the type Foo has no
262                //     fields. We don't want `let x: ();` to compile
263                //     to the same MIR as `let x = ();`.
264
265                // first process the set of fields
266                let el_ty = expr.ty.sequence_element_type(this.tcx);
267                let fields: IndexVec<FieldIdx, _> = fields
268                    .into_iter()
269                    .copied()
270                    .map(|f| {
271                        {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, f, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
272                            block = this.as_operand(
273                                block,
274                                scope,
275                                f,
276                                LocalInfo::Boring,
277                                NeedsTemporary::Maybe
278                            )
279                        )
280                    })
281                    .collect();
282
283                block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
284            }
285            ExprKind::Tuple { ref fields } => {
286                // see (*) above
287                // first process the set of fields
288                let fields: IndexVec<FieldIdx, _> = fields
289                    .into_iter()
290                    .copied()
291                    .map(|f| {
292                        {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, f, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
293                            block = this.as_operand(
294                                block,
295                                scope,
296                                f,
297                                LocalInfo::Boring,
298                                NeedsTemporary::Maybe
299                            )
300                        )
301                    })
302                    .collect();
303
304                block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
305            }
306            ExprKind::Closure(box ClosureExpr {
307                closure_id,
308                args,
309                ref upvars,
310                ref fake_reads,
311                movability: _,
312            }) => {
313                // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
314                // and push the fake reads.
315                // This must come before creating the operands. This is required in case
316                // there is a fake read and a borrow of the same path, since otherwise the
317                // fake read might interfere with the borrow. Consider an example like this
318                // one:
319                // ```
320                // let mut x = 0;
321                // let c = || {
322                //     &mut x; // mutable borrow of `x`
323                //     match x { _ => () } // fake read of `x`
324                // };
325                // ```
326                //
327                for (thir_place, cause, hir_id) in fake_reads.into_iter() {
328                    let place_builder = {
    let BlockAnd(b, v) = this.as_place_builder(block, *thir_place);
    block = b;
    v
}unpack!(block = this.as_place_builder(block, *thir_place));
329
330                    if let Some(mir_place) = place_builder.try_to_place(this) {
331                        this.cfg.push_fake_read(
332                            block,
333                            this.source_info(this.tcx.hir_span(*hir_id)),
334                            *cause,
335                            mir_place,
336                        );
337                    }
338                }
339
340                // see (*) above
341                let operands: IndexVec<FieldIdx, _> = upvars
342                    .into_iter()
343                    .copied()
344                    .map(|upvar| {
345                        let upvar_expr = &this.thir[upvar];
346                        match Category::of(&upvar_expr.kind) {
347                            // Use as_place to avoid creating a temporary when
348                            // moving a variable into a closure, so that
349                            // borrowck knows which variables to mark as being
350                            // used as mut. This is OK here because the upvar
351                            // expressions have no side effects and act on
352                            // disjoint places.
353                            // This occurs when capturing by copy/move, while
354                            // by reference captures use as_operand
355                            Some(Category::Place) => {
356                                let place = { let BlockAnd(b, v) = this.as_place(block, upvar); block = b; v }unpack!(block = this.as_place(block, upvar));
357                                this.consume_by_copy_or_move(place)
358                            }
359                            _ => {
360                                // Turn mutable borrow captures into unique
361                                // borrow captures when capturing an immutable
362                                // variable. This is sound because the mutation
363                                // that caused the capture will cause an error.
364                                match upvar_expr.kind {
365                                    ExprKind::Borrow {
366                                        borrow_kind:
367                                            BorrowKind::Mut { kind: MutBorrowKind::Default },
368                                        arg,
369                                    } => {
    let BlockAnd(b, v) =
        this.limit_capture_mutability(upvar_expr.span, upvar_expr.ty,
            scope.temp_lifetime, block, arg);
    block = b;
    v
}unpack!(
370                                        block = this.limit_capture_mutability(
371                                            upvar_expr.span,
372                                            upvar_expr.ty,
373                                            scope.temp_lifetime,
374                                            block,
375                                            arg,
376                                        )
377                                    ),
378                                    _ => {
379                                        {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, upvar, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
380                                            block = this.as_operand(
381                                                block,
382                                                scope,
383                                                upvar,
384                                                LocalInfo::Boring,
385                                                NeedsTemporary::Maybe
386                                            )
387                                        )
388                                    }
389                                }
390                            }
391                        }
392                    })
393                    .collect();
394
395                let result = match args {
396                    UpvarArgs::Coroutine(args) => {
397                        Box::new(AggregateKind::Coroutine(closure_id.to_def_id(), args))
398                    }
399                    UpvarArgs::Closure(args) => {
400                        Box::new(AggregateKind::Closure(closure_id.to_def_id(), args))
401                    }
402                    UpvarArgs::CoroutineClosure(args) => {
403                        Box::new(AggregateKind::CoroutineClosure(closure_id.to_def_id(), args))
404                    }
405                };
406                block.and(Rvalue::Aggregate(result, operands))
407            }
408            ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
409                block = this.stmt_expr(block, expr_id, None).into_block();
410                block.and(Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
411                    span: expr_span,
412                    user_ty: None,
413                    const_: Const::zero_sized(this.tcx.types.unit),
414                }))))
415            }
416
417            ExprKind::Literal { .. }
418            | ExprKind::NamedConst { .. }
419            | ExprKind::NonHirLiteral { .. }
420            | ExprKind::ZstLiteral { .. }
421            | ExprKind::ConstParam { .. }
422            | ExprKind::ConstBlock { .. }
423            | ExprKind::StaticRef { .. } => {
424                let constant = this.as_constant(expr);
425                block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
426            }
427
428            ExprKind::WrapUnsafeBinder { source } => {
429                let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
430                    block = this.as_operand(
431                        block,
432                        scope,
433                        source,
434                        LocalInfo::Boring,
435                        NeedsTemporary::Maybe
436                    )
437                );
438                block.and(Rvalue::WrapUnsafeBinder(source, expr.ty))
439            }
440
441            ExprKind::Yield { .. }
442            | ExprKind::Block { .. }
443            | ExprKind::Match { .. }
444            | ExprKind::If { .. }
445            | ExprKind::NeverToAny { .. }
446            | ExprKind::Use { .. }
447            | ExprKind::Borrow { .. }
448            | ExprKind::RawBorrow { .. }
449            | ExprKind::Adt { .. }
450            | ExprKind::Loop { .. }
451            | ExprKind::LoopMatch { .. }
452            | ExprKind::LogicalOp { .. }
453            | ExprKind::Call { .. }
454            | ExprKind::Field { .. }
455            | ExprKind::Let { .. }
456            | ExprKind::Deref { .. }
457            | ExprKind::Index { .. }
458            | ExprKind::VarRef { .. }
459            | ExprKind::UpvarRef { .. }
460            | ExprKind::Break { .. }
461            | ExprKind::Continue { .. }
462            | ExprKind::ConstContinue { .. }
463            | ExprKind::Return { .. }
464            | ExprKind::Become { .. }
465            | ExprKind::InlineAsm { .. }
466            | ExprKind::PlaceTypeAscription { .. }
467            | ExprKind::ValueTypeAscription { .. }
468            | ExprKind::PlaceUnwrapUnsafeBinder { .. }
469            | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
470                // these do not have corresponding `Rvalue` variants,
471                // so make an operand and then return that
472                if true {
    if !!#[allow(non_exhaustive_omitted_patterns)] match Category::of(&expr.kind)
                    {
                    Some(Category::Rvalue(RvalueFunc::AsRvalue) |
                        Category::Constant) => true,
                    _ => false,
                } {
        ::core::panicking::panic("assertion failed: !matches!(Category::of(&expr.kind),\n        Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant))")
    };
};debug_assert!(!matches!(
473                    Category::of(&expr.kind),
474                    Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
475                ));
476                let operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, expr_id, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
477                    block = this.as_operand(
478                        block,
479                        scope,
480                        expr_id,
481                        LocalInfo::Boring,
482                        NeedsTemporary::No,
483                    )
484                );
485                block.and(Rvalue::Use(operand))
486            }
487
488            ExprKind::ByUse { expr, span: _ } => {
489                let operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, expr, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
490                    block =
491                        this.as_operand(block, scope, expr, LocalInfo::Boring, NeedsTemporary::No)
492                );
493                block.and(Rvalue::Use(operand))
494            }
495        }
496    }
497
498    pub(crate) fn build_binary_op(
499        &mut self,
500        mut block: BasicBlock,
501        op: BinOp,
502        span: Span,
503        ty: Ty<'tcx>,
504        lhs: Operand<'tcx>,
505        rhs: Operand<'tcx>,
506    ) -> BlockAnd<Rvalue<'tcx>> {
507        let source_info = self.source_info(span);
508        let bool_ty = self.tcx.types.bool;
509        let rvalue = match op {
510            BinOp::Add | BinOp::Sub | BinOp::Mul if self.check_overflow && ty.is_integral() => {
511                let result_tup = Ty::new_tup(self.tcx, &[ty, bool_ty]);
512                let result_value = self.temp(result_tup, span);
513
514                let op_with_overflow = op.wrapping_to_overflowing().unwrap();
515
516                self.cfg.push_assign(
517                    block,
518                    source_info,
519                    result_value,
520                    Rvalue::BinaryOp(op_with_overflow, Box::new((lhs.to_copy(), rhs.to_copy()))),
521                );
522                let val_fld = FieldIdx::ZERO;
523                let of_fld = FieldIdx::new(1);
524
525                let tcx = self.tcx;
526                let val = tcx.mk_place_field(result_value, val_fld, ty);
527                let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
528
529                let err = AssertKind::Overflow(op, lhs, rhs);
530                block = self.assert(block, Operand::Move(of), false, err, span);
531
532                Rvalue::Use(Operand::Move(val))
533            }
534            BinOp::Shl | BinOp::Shr if self.check_overflow && ty.is_integral() => {
535                // For an unsigned RHS, the shift is in-range for `rhs < bits`.
536                // For a signed RHS, `IntToInt` cast to the equivalent unsigned
537                // type and do that same comparison.
538                // A negative value will be *at least* 128 after the cast (that's i8::MIN),
539                // and 128 is an overflowing shift amount for all our currently existing types,
540                // so this cast can never make us miss an overflow.
541                let (lhs_size, _) = ty.int_size_and_signed(self.tcx);
542                if !(lhs_size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: lhs_size.bits() <= 128")
};assert!(lhs_size.bits() <= 128);
543                let rhs_ty = rhs.ty(&self.local_decls, self.tcx);
544                let (rhs_size, _) = rhs_ty.int_size_and_signed(self.tcx);
545
546                let (unsigned_rhs, unsigned_ty) = match rhs_ty.kind() {
547                    ty::Uint(_) => (rhs.to_copy(), rhs_ty),
548                    ty::Int(int_width) => {
549                        let uint_ty = Ty::new_uint(self.tcx, int_width.to_unsigned());
550                        let rhs_temp = self.temp(uint_ty, span);
551                        self.cfg.push_assign(
552                            block,
553                            source_info,
554                            rhs_temp,
555                            Rvalue::Cast(CastKind::IntToInt, rhs.to_copy(), uint_ty),
556                        );
557                        (Operand::Move(rhs_temp), uint_ty)
558                    }
559                    _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("only integers are shiftable")));
}unreachable!("only integers are shiftable"),
560                };
561
562                // This can't overflow because the largest shiftable types are 128-bit,
563                // which fits in `u8`, the smallest possible `unsigned_ty`.
564                let lhs_bits = Operand::const_from_scalar(
565                    self.tcx,
566                    unsigned_ty,
567                    Scalar::from_uint(lhs_size.bits(), rhs_size),
568                    span,
569                );
570
571                let inbounds = self.temp(bool_ty, span);
572                self.cfg.push_assign(
573                    block,
574                    source_info,
575                    inbounds,
576                    Rvalue::BinaryOp(BinOp::Lt, Box::new((unsigned_rhs, lhs_bits))),
577                );
578
579                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
580                block = self.assert(block, Operand::Move(inbounds), true, overflow_err, span);
581                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
582            }
583            BinOp::Div | BinOp::Rem if ty.is_integral() => {
584                // Checking division and remainder is more complex, since we 1. always check
585                // and 2. there are two possible failure cases, divide-by-zero and overflow.
586
587                let zero_err = if op == BinOp::Div {
588                    AssertKind::DivisionByZero(lhs.to_copy())
589                } else {
590                    AssertKind::RemainderByZero(lhs.to_copy())
591                };
592                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
593
594                // Check for / 0
595                let is_zero = self.temp(bool_ty, span);
596                let zero = self.zero_literal(span, ty);
597                self.cfg.push_assign(
598                    block,
599                    source_info,
600                    is_zero,
601                    Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
602                );
603
604                block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
605
606                // We only need to check for the overflow in one case:
607                // MIN / -1, and only for signed values.
608                if ty.is_signed() {
609                    let neg_1 = self.neg_1_literal(span, ty);
610                    let min = self.minval_literal(span, ty);
611
612                    let is_neg_1 = self.temp(bool_ty, span);
613                    let is_min = self.temp(bool_ty, span);
614                    let of = self.temp(bool_ty, span);
615
616                    // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
617
618                    self.cfg.push_assign(
619                        block,
620                        source_info,
621                        is_neg_1,
622                        Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
623                    );
624                    self.cfg.push_assign(
625                        block,
626                        source_info,
627                        is_min,
628                        Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
629                    );
630
631                    let is_neg_1 = Operand::Move(is_neg_1);
632                    let is_min = Operand::Move(is_min);
633                    self.cfg.push_assign(
634                        block,
635                        source_info,
636                        of,
637                        Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
638                    );
639
640                    block = self.assert(block, Operand::Move(of), false, overflow_err, span);
641                }
642
643                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
644            }
645            _ => Rvalue::BinaryOp(op, Box::new((lhs, rhs))),
646        };
647        block.and(rvalue)
648    }
649
650    /// Recursively inspect a THIR expression and probe through unsizing
651    /// operations that can be const-folded today.
652    fn check_constness(&self, mut kind: &'a ExprKind<'tcx>) -> bool {
653        loop {
654            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs:654",
                        "rustc_mir_build::builder::expr::as_rvalue",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(654u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_rvalue"),
                        ::tracing_core::field::FieldSet::new(&["message", "kind"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_constness")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&kind) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?kind, "check_constness");
655            match kind {
656                &ExprKind::ValueTypeAscription { source: eid, user_ty: _, user_ty_span: _ }
657                | &ExprKind::Use { source: eid }
658                | &ExprKind::PointerCoercion {
659                    cast: PointerCoercion::Unsize,
660                    source: eid,
661                    is_from_as_cast: _,
662                }
663                | &ExprKind::Scope { region_scope: _, hir_id: _, value: eid } => {
664                    kind = &self.thir[eid].kind
665                }
666                _ => return #[allow(non_exhaustive_omitted_patterns)] match Category::of(&kind) {
    Some(Category::Constant) => true,
    _ => false,
}matches!(Category::of(&kind), Some(Category::Constant)),
667            }
668        }
669    }
670
671    fn build_zero_repeat(
672        &mut self,
673        mut block: BasicBlock,
674        value: ExprId,
675        scope: TempLifetime,
676        outer_source_info: SourceInfo,
677    ) -> BlockAnd<Rvalue<'tcx>> {
678        let this = self; // See "LET_THIS_SELF".
679        let value_expr = &this.thir[value];
680        let elem_ty = value_expr.ty;
681        if this.check_constness(&value_expr.kind) {
682            // Repeating a const does nothing
683        } else {
684            // For a non-const, we may need to generate an appropriate `Drop`
685            let value_operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, value, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
686                block = this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
687            );
688            if let Operand::Move(to_drop) = value_operand {
689                let success = this.cfg.start_new_block();
690                this.cfg.terminate(
691                    block,
692                    outer_source_info,
693                    TerminatorKind::Drop {
694                        place: to_drop,
695                        target: success,
696                        unwind: UnwindAction::Continue,
697                        replace: false,
698                        drop: None,
699                        async_fut: None,
700                    },
701                );
702                this.diverge_from(block);
703                block = success;
704            }
705            this.record_operands_moved(&[Spanned { node: value_operand, span: DUMMY_SP }]);
706        }
707        block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new()))
708    }
709
710    fn limit_capture_mutability(
711        &mut self,
712        upvar_span: Span,
713        upvar_ty: Ty<'tcx>,
714        temp_lifetime: Option<region::Scope>,
715        mut block: BasicBlock,
716        arg: ExprId,
717    ) -> BlockAnd<Operand<'tcx>> {
718        let this = self; // See "LET_THIS_SELF".
719
720        let source_info = this.source_info(upvar_span);
721        let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
722
723        this.cfg.push(block, Statement::new(source_info, StatementKind::StorageLive(temp)));
724
725        let arg_place_builder = { let BlockAnd(b, v) = this.as_place_builder(block, arg); block = b; v }unpack!(block = this.as_place_builder(block, arg));
726
727        let mutability = match arg_place_builder.base() {
728            // We are capturing a path that starts off a local variable in the parent.
729            // The mutability of the current capture is same as the mutability
730            // of the local declaration in the parent.
731            PlaceBase::Local(local) => this.local_decls[local].mutability,
732            // Parent is a closure and we are capturing a path that is captured
733            // by the parent itself. The mutability of the current capture
734            // is same as that of the capture in the parent closure.
735            PlaceBase::Upvar { .. } => {
736                let enclosing_upvars_resolved = arg_place_builder.to_place(this);
737
738                match enclosing_upvars_resolved.as_ref() {
739                    PlaceRef {
740                        local,
741                        projection: &[ProjectionElem::Field(upvar_index, _), ..],
742                    }
743                    | PlaceRef {
744                        local,
745                        projection:
746                            &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
747                    } => {
748                        // Not in a closure
749                        if true {
    if !(local == ty::CAPTURE_STRUCT_LOCAL) {
        {
            ::core::panicking::panic_fmt(format_args!("Expected local to be Local(1), found {0:?}",
                    local));
        }
    };
};debug_assert!(
750                            local == ty::CAPTURE_STRUCT_LOCAL,
751                            "Expected local to be Local(1), found {local:?}"
752                        );
753                        // Not in a closure
754                        if true {
    if !(this.upvars.len() > upvar_index.index()) {
        {
            ::core::panicking::panic_fmt(format_args!("Unexpected capture place, upvars={0:#?}, upvar_index={1:?}",
                    this.upvars, upvar_index));
        }
    };
};debug_assert!(
755                            this.upvars.len() > upvar_index.index(),
756                            "Unexpected capture place, upvars={:#?}, upvar_index={:?}",
757                            this.upvars,
758                            upvar_index
759                        );
760                        this.upvars[upvar_index.index()].mutability
761                    }
762                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected capture place"))bug!("Unexpected capture place"),
763                }
764            }
765        };
766
767        let borrow_kind = match mutability {
768            Mutability::Not => BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
769            Mutability::Mut => BorrowKind::Mut { kind: MutBorrowKind::Default },
770        };
771
772        let arg_place = arg_place_builder.to_place(this);
773
774        this.cfg.push_assign(
775            block,
776            source_info,
777            Place::from(temp),
778            Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
779        );
780
781        // This can be `None` if the expression's temporary scope was extended so that it can be
782        // borrowed by a `const` or `static`. In that case, it's never dropped.
783        if let Some(temp_lifetime) = temp_lifetime {
784            this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
785        }
786
787        block.and(Operand::Move(Place::from(temp)))
788    }
789
790    // Helper to get a `-1` value of the appropriate type
791    fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
792        let typing_env = ty::TypingEnv::fully_monomorphized();
793        let size = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size;
794        let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), typing_env, ty);
795
796        self.literal_operand(span, literal)
797    }
798
799    // Helper to get the minimum value of the appropriate type
800    fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
801        if !ty.is_signed() {
    ::core::panicking::panic("assertion failed: ty.is_signed()")
};assert!(ty.is_signed());
802        let typing_env = ty::TypingEnv::fully_monomorphized();
803        let bits = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size.bits();
804        let n = 1 << (bits - 1);
805        let literal = Const::from_bits(self.tcx, n, typing_env, ty);
806
807        self.literal_operand(span, literal)
808    }
809}