1 //! See docs in `build/expr/mod.rs`.
3 use rustc_index::vec::Idx;
4 use rustc_middle::ty::util::IntTypeExt;
6 use crate::build::expr::as_place::PlaceBase;
7 use crate::build::expr::category::{Category, RvalueFunc};
8 use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
9 use rustc_hir::lang_items::LangItem;
10 use rustc_middle::middle::region;
11 use rustc_middle::mir::AssertKind;
12 use rustc_middle::mir::Place;
13 use rustc_middle::mir::*;
14 use rustc_middle::thir::*;
15 use rustc_middle::ty::cast::CastTy;
16 use rustc_middle::ty::{self, Ty, UpvarSubsts};
19 impl<'a, 'tcx> Builder<'a, 'tcx> {
20 /// Returns an rvalue suitable for use until the end of the current
23 /// The operand returned from this function will *not be valid* after
24 /// an ExprKind::Scope is passed, so please do *not* return it from
25 /// functions to avoid bad miscompiles.
26 pub(crate) fn as_local_rvalue(
30 ) -> BlockAnd<Rvalue<'tcx>> {
31 let local_scope = self.local_scope();
32 self.as_rvalue(block, Some(local_scope), expr)
35 /// Compile `expr`, yielding an rvalue.
36 pub(crate) fn as_rvalue(
38 mut block: BasicBlock,
39 scope: Option<region::Scope>,
41 ) -> BlockAnd<Rvalue<'tcx>> {
42 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
45 let expr_span = expr.span;
46 let source_info = this.source_info(expr_span);
49 ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
50 ExprKind::Scope { region_scope, lint_level, value } => {
51 let region_scope = (region_scope, source_info);
52 this.in_scope(region_scope, lint_level, |this| {
53 this.as_rvalue(block, scope, &this.thir[value])
56 ExprKind::Repeat { value, count } => {
57 if Some(0) == count.try_eval_usize(this.tcx, this.param_env) {
58 this.build_zero_repeat(block, value, scope, source_info)
60 let value_operand = unpack!(
61 block = this.as_operand(
69 block.and(Rvalue::Repeat(value_operand, count))
72 ExprKind::Binary { op, lhs, rhs } => {
75 this.as_operand(block, scope, &this.thir[lhs], None, NeedsTemporary::Maybe)
79 this.as_operand(block, scope, &this.thir[rhs], None, NeedsTemporary::No)
81 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
83 ExprKind::Unary { op, arg } => {
86 this.as_operand(block, scope, &this.thir[arg], None, NeedsTemporary::No)
88 // Check for -MIN on signed integers
89 if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
90 let bool_ty = this.tcx.types.bool;
92 let minval = this.minval_literal(expr_span, expr.ty);
93 let is_min = this.temp(bool_ty, expr_span);
99 Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
104 Operand::Move(is_min),
106 AssertKind::OverflowNeg(arg.to_copy()),
110 block.and(Rvalue::UnaryOp(op, arg))
112 ExprKind::Box { value } => {
113 let value = &this.thir[value];
116 // `exchange_malloc` is unsafe but box is safe, so need a new scope.
117 let synth_scope = this.new_source_scope(
119 LintLevel::Inherited,
120 Some(Safety::BuiltinUnsafe),
122 let synth_info = SourceInfo { span: expr_span, scope: synth_scope };
124 let size = this.temp(tcx.types.usize, expr_span);
125 this.cfg.push_assign(
129 Rvalue::NullaryOp(NullOp::SizeOf, value.ty),
132 let align = this.temp(tcx.types.usize, expr_span);
133 this.cfg.push_assign(
137 Rvalue::NullaryOp(NullOp::AlignOf, value.ty),
140 // malloc some memory of suitable size and align:
141 let exchange_malloc = Operand::function_handle(
143 tcx.require_lang_item(LangItem::ExchangeMalloc, Some(expr_span)),
147 let storage = this.temp(tcx.mk_mut_ptr(tcx.types.u8), expr_span);
148 let success = this.cfg.start_new_block();
152 TerminatorKind::Call {
153 func: exchange_malloc,
154 args: vec![Operand::Move(size), Operand::Move(align)],
155 destination: storage,
156 target: Some(success),
158 from_hir_call: false,
162 this.diverge_from(block);
165 // The `Box<T>` temporary created here is not a part of the HIR,
166 // and therefore is not considered during generator auto-trait
167 // determination. See the comment about `box` at `yield_in_scope`.
168 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
171 Statement { source_info, kind: StatementKind::StorageLive(result) },
173 if let Some(scope) = scope {
174 // schedule a shallow free of that memory, lest we unwind:
175 this.schedule_drop_storage_and_value(expr_span, scope, result);
178 // Transmute `*mut u8` to the box (thus far, uninitialized):
179 let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value.ty);
180 this.cfg.push_assign(block, source_info, Place::from(result), box_);
182 // initialize the box contents:
184 block = this.expr_into_dest(
185 this.tcx.mk_place_deref(Place::from(result)),
190 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
192 ExprKind::Cast { source } => {
193 let source = &this.thir[source];
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.ty.kind() && adt_def.is_enum() {
199 let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
200 let place = unpack!(block = this.as_place(block, source));
201 let discr = this.temp(discr_ty, source.span);
202 this.cfg.push_assign(
206 Rvalue::Discriminant(place),
209 (Operand::Move(discr), discr_ty)
212 let source = unpack!(
213 block = this.as_operand(block, scope, source, None, NeedsTemporary::No)
217 let from_ty = CastTy::from_ty(ty);
218 let cast_ty = CastTy::from_ty(expr.ty);
219 let cast_kind = match (from_ty, cast_ty) {
220 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
221 CastKind::PointerExposeAddress
223 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => {
224 CastKind::PointerFromExposedAddress
226 (_, _) => CastKind::Misc,
228 block.and(Rvalue::Cast(cast_kind, source, expr.ty))
230 ExprKind::Pointer { cast, source } => {
231 let source = unpack!(
233 this.as_operand(block, scope, &this.thir[source], None, NeedsTemporary::No)
235 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
237 ExprKind::Array { ref fields } => {
238 // (*) We would (maybe) be closer to codegen if we
239 // handled this and other aggregate cases via
240 // `into()`, not `as_rvalue` -- in that case, instead
245 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
247 // we could just generate
252 // The problem is that then we would need to:
254 // (a) have a more complex mechanism for handling
256 // (b) distinguish the case where the type `Foo` has a
257 // destructor, in which case creating an instance
258 // as a whole "arms" the destructor, and you can't
259 // write individual fields; and,
260 // (c) handle the case where the type Foo has no
261 // fields. We don't want `let x: ();` to compile
262 // to the same MIR as `let x = ();`.
264 // first process the set of fields
265 let el_ty = expr.ty.sequence_element_type(this.tcx);
266 let fields: Vec<_> = fields
271 block = this.as_operand(
276 NeedsTemporary::Maybe
282 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
284 ExprKind::Tuple { ref fields } => {
286 // first process the set of fields
287 let fields: Vec<_> = fields
292 block = this.as_operand(
297 NeedsTemporary::Maybe
303 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
305 ExprKind::Closure { closure_id, substs, ref upvars, movability, ref fake_reads } => {
306 // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
307 // and push the fake reads.
308 // This must come before creating the operands. This is required in case
309 // there is a fake read and a borrow of the same path, since otherwise the
310 // fake read might interfere with the borrow. Consider an example like this
315 // &mut x; // mutable borrow of `x`
316 // match x { _ => () } // fake read of `x`
320 for (thir_place, cause, hir_id) in fake_reads.into_iter() {
322 unpack!(block = this.as_place_builder(block, &this.thir[*thir_place]));
324 if let Ok(place_builder_resolved) = place_builder.try_upvars_resolved(this) {
325 let mir_place = place_builder_resolved.into_place(this);
326 this.cfg.push_fake_read(
328 this.source_info(this.tcx.hir().span(*hir_id)),
336 let operands: Vec<_> = upvars
340 let upvar = &this.thir[upvar];
341 match Category::of(&upvar.kind) {
342 // Use as_place to avoid creating a temporary when
343 // moving a variable into a closure, so that
344 // borrowck knows which variables to mark as being
345 // used as mut. This is OK here because the upvar
346 // expressions have no side effects and act on
348 // This occurs when capturing by copy/move, while
349 // by reference captures use as_operand
350 Some(Category::Place) => {
351 let place = unpack!(block = this.as_place(block, upvar));
352 this.consume_by_copy_or_move(place)
355 // Turn mutable borrow captures into unique
356 // borrow captures when capturing an immutable
357 // variable. This is sound because the mutation
358 // that caused the capture will cause an error.
362 BorrowKind::Mut { allow_two_phase_borrow: false },
365 block = this.limit_capture_mutability(
375 block = this.as_operand(
380 NeedsTemporary::Maybe
390 let result = match substs {
391 UpvarSubsts::Generator(substs) => {
392 // We implicitly set the discriminant to 0. See
393 // librustc_mir/transform/deaggregator.rs for details.
394 let movability = movability.unwrap();
395 Box::new(AggregateKind::Generator(closure_id, substs, movability))
397 UpvarSubsts::Closure(substs) => {
398 Box::new(AggregateKind::Closure(closure_id, substs))
401 block.and(Rvalue::Aggregate(result, operands))
403 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
404 block = unpack!(this.stmt_expr(block, expr, None));
405 block.and(Rvalue::Use(Operand::Constant(Box::new(Constant {
408 literal: ConstantKind::zero_sized(this.tcx.types.unit),
412 ExprKind::Literal { .. }
413 | ExprKind::NamedConst { .. }
414 | ExprKind::NonHirLiteral { .. }
415 | ExprKind::ZstLiteral { .. }
416 | ExprKind::ConstParam { .. }
417 | ExprKind::ConstBlock { .. }
418 | ExprKind::StaticRef { .. } => {
419 let constant = this.as_constant(expr);
420 block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
423 ExprKind::Yield { .. }
424 | ExprKind::Block { .. }
425 | ExprKind::Match { .. }
426 | ExprKind::If { .. }
427 | ExprKind::NeverToAny { .. }
428 | ExprKind::Use { .. }
429 | ExprKind::Borrow { .. }
430 | ExprKind::AddressOf { .. }
431 | ExprKind::Adt { .. }
432 | ExprKind::Loop { .. }
433 | ExprKind::LogicalOp { .. }
434 | ExprKind::Call { .. }
435 | ExprKind::Field { .. }
436 | ExprKind::Let { .. }
437 | ExprKind::Deref { .. }
438 | ExprKind::Index { .. }
439 | ExprKind::VarRef { .. }
440 | ExprKind::UpvarRef { .. }
441 | ExprKind::Break { .. }
442 | ExprKind::Continue { .. }
443 | ExprKind::Return { .. }
444 | ExprKind::InlineAsm { .. }
445 | ExprKind::PlaceTypeAscription { .. }
446 | ExprKind::ValueTypeAscription { .. } => {
447 // these do not have corresponding `Rvalue` variants,
448 // so make an operand and then return that
449 debug_assert!(!matches!(
450 Category::of(&expr.kind),
451 Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
454 unpack!(block = this.as_operand(block, scope, expr, None, NeedsTemporary::No));
455 block.and(Rvalue::Use(operand))
460 pub(crate) fn build_binary_op(
462 mut block: BasicBlock,
468 ) -> BlockAnd<Rvalue<'tcx>> {
469 let source_info = self.source_info(span);
470 let bool_ty = self.tcx.types.bool;
471 if self.check_overflow && op.is_checkable() && ty.is_integral() {
472 let result_tup = self.tcx.intern_tup(&[ty, bool_ty]);
473 let result_value = self.temp(result_tup, span);
475 self.cfg.push_assign(
479 Rvalue::CheckedBinaryOp(op, Box::new((lhs.to_copy(), rhs.to_copy()))),
481 let val_fld = Field::new(0);
482 let of_fld = Field::new(1);
485 let val = tcx.mk_place_field(result_value, val_fld, ty);
486 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
488 let err = AssertKind::Overflow(op, lhs, rhs);
490 block = self.assert(block, Operand::Move(of), false, err, span);
492 block.and(Rvalue::Use(Operand::Move(val)))
494 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
495 // Checking division and remainder is more complex, since we 1. always check
496 // and 2. there are two possible failure cases, divide-by-zero and overflow.
498 let zero_err = if op == BinOp::Div {
499 AssertKind::DivisionByZero(lhs.to_copy())
501 AssertKind::RemainderByZero(lhs.to_copy())
503 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
506 let is_zero = self.temp(bool_ty, span);
507 let zero = self.zero_literal(span, ty);
508 self.cfg.push_assign(
512 Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
515 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
517 // We only need to check for the overflow in one case:
518 // MIN / -1, and only for signed values.
520 let neg_1 = self.neg_1_literal(span, ty);
521 let min = self.minval_literal(span, ty);
523 let is_neg_1 = self.temp(bool_ty, span);
524 let is_min = self.temp(bool_ty, span);
525 let of = self.temp(bool_ty, span);
527 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
529 self.cfg.push_assign(
533 Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
535 self.cfg.push_assign(
539 Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
542 let is_neg_1 = Operand::Move(is_neg_1);
543 let is_min = Operand::Move(is_min);
544 self.cfg.push_assign(
548 Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
551 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
555 block.and(Rvalue::BinaryOp(op, Box::new((lhs, rhs))))
559 fn build_zero_repeat(
561 mut block: BasicBlock,
563 scope: Option<region::Scope>,
564 outer_source_info: SourceInfo,
565 ) -> BlockAnd<Rvalue<'tcx>> {
567 let value = &this.thir[value];
568 let elem_ty = value.ty;
569 if let Some(Category::Constant) = Category::of(&value.kind) {
570 // Repeating a const does nothing
572 // For a non-const, we may need to generate an appropriate `Drop`
574 unpack!(block = this.as_operand(block, scope, value, None, NeedsTemporary::No));
575 if let Operand::Move(to_drop) = value_operand {
576 let success = this.cfg.start_new_block();
580 TerminatorKind::Drop { place: to_drop, target: success, unwind: None },
582 this.diverge_from(block);
585 this.record_operands_moved(&[value_operand]);
587 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), Vec::new()))
590 fn limit_capture_mutability(
594 temp_lifetime: Option<region::Scope>,
595 mut block: BasicBlock,
597 ) -> BlockAnd<Operand<'tcx>> {
600 let source_info = this.source_info(upvar_span);
601 let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
603 this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
605 let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
607 let mutability = match arg_place_builder.base() {
608 // We are capturing a path that starts off a local variable in the parent.
609 // The mutability of the current capture is same as the mutability
610 // of the local declaration in the parent.
611 PlaceBase::Local(local) => this.local_decls[local].mutability,
612 // Parent is a closure and we are capturing a path that is captured
613 // by the parent itself. The mutability of the current capture
614 // is same as that of the capture in the parent closure.
615 PlaceBase::Upvar { .. } => {
616 let enclosing_upvars_resolved = arg_place_builder.clone().into_place(this);
618 match enclosing_upvars_resolved.as_ref() {
621 projection: &[ProjectionElem::Field(upvar_index, _), ..],
626 &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
630 local == ty::CAPTURE_STRUCT_LOCAL,
631 "Expected local to be Local(1), found {:?}",
636 this.upvar_mutbls.len() > upvar_index.index(),
637 "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
641 this.upvar_mutbls[upvar_index.index()]
643 _ => bug!("Unexpected capture place"),
648 let borrow_kind = match mutability {
649 Mutability::Not => BorrowKind::Unique,
650 Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
653 let arg_place = arg_place_builder.into_place(this);
655 this.cfg.push_assign(
659 Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
662 // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
663 // this can be `None`.
664 if let Some(temp_lifetime) = temp_lifetime {
665 this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
668 block.and(Operand::Move(Place::from(temp)))
671 // Helper to get a `-1` value of the appropriate type
672 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
673 let param_ty = ty::ParamEnv::empty().and(ty);
674 let size = self.tcx.layout_of(param_ty).unwrap().size;
675 let literal = ConstantKind::from_bits(self.tcx, size.unsigned_int_max(), param_ty);
677 self.literal_operand(span, literal)
680 // Helper to get the minimum value of the appropriate type
681 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
682 assert!(ty.is_signed());
683 let param_ty = ty::ParamEnv::empty().and(ty);
684 let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
685 let n = 1 << (bits - 1);
686 let literal = ConstantKind::from_bits(self.tcx, n, param_ty);
688 self.literal_operand(span, literal)