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