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