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