1 //! See docs in `build/expr/mod.rs`.
3 use rustc_index::vec::Idx;
5 use crate::build::expr::as_place::PlaceBase;
6 use crate::build::expr::category::{Category, RvalueFunc};
7 use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_middle::middle::region;
10 use rustc_middle::mir::AssertKind;
11 use rustc_middle::mir::Place;
12 use rustc_middle::mir::*;
13 use rustc_middle::thir::*;
14 use rustc_middle::ty::cast::CastTy;
15 use rustc_middle::ty::{self, Ty, UpvarSubsts};
18 impl<'a, 'tcx> Builder<'a, 'tcx> {
19 /// Returns an rvalue suitable for use until the end of the current
22 /// The operand returned from this function will *not be valid* after
23 /// an ExprKind::Scope is passed, so please do *not* return it from
24 /// functions to avoid bad miscompiles.
25 pub(crate) fn as_local_rvalue(
29 ) -> BlockAnd<Rvalue<'tcx>> {
30 let local_scope = self.local_scope();
31 self.as_rvalue(block, Some(local_scope), expr)
34 /// Compile `expr`, yielding an rvalue.
35 pub(crate) fn as_rvalue(
37 mut block: BasicBlock,
38 scope: Option<region::Scope>,
40 ) -> BlockAnd<Rvalue<'tcx>> {
41 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
44 let expr_span = expr.span;
45 let source_info = this.source_info(expr_span);
48 ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
49 ExprKind::Scope { region_scope, lint_level, value } => {
50 let region_scope = (region_scope, source_info);
51 this.in_scope(region_scope, lint_level, |this| {
52 this.as_rvalue(block, scope, &this.thir[value])
55 ExprKind::Repeat { value, count } => {
56 if Some(0) == count.try_eval_usize(this.tcx, this.param_env) {
57 this.build_zero_repeat(block, value, scope, source_info)
59 let value_operand = unpack!(
60 block = this.as_operand(
68 block.and(Rvalue::Repeat(value_operand, count))
71 ExprKind::Binary { op, lhs, rhs } => {
74 this.as_operand(block, scope, &this.thir[lhs], None, NeedsTemporary::Maybe)
78 this.as_operand(block, scope, &this.thir[rhs], None, NeedsTemporary::No)
80 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
82 ExprKind::Unary { op, arg } => {
85 this.as_operand(block, scope, &this.thir[arg], None, NeedsTemporary::No)
87 // Check for -MIN on signed integers
88 if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
89 let bool_ty = this.tcx.types.bool;
91 let minval = this.minval_literal(expr_span, expr.ty);
92 let is_min = this.temp(bool_ty, expr_span);
98 Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
103 Operand::Move(is_min),
105 AssertKind::OverflowNeg(arg.to_copy()),
109 block.and(Rvalue::UnaryOp(op, arg))
111 ExprKind::Box { value } => {
112 let value = &this.thir[value];
115 // `exchange_malloc` is unsafe but box is safe, so need a new scope.
116 let synth_scope = this.new_source_scope(
118 LintLevel::Inherited,
119 Some(Safety::BuiltinUnsafe),
121 let synth_info = SourceInfo { span: expr_span, scope: synth_scope };
123 let size = this.temp(tcx.types.usize, expr_span);
124 this.cfg.push_assign(
128 Rvalue::NullaryOp(NullOp::SizeOf, value.ty),
131 let align = this.temp(tcx.types.usize, expr_span);
132 this.cfg.push_assign(
136 Rvalue::NullaryOp(NullOp::AlignOf, value.ty),
139 // malloc some memory of suitable size and align:
140 let exchange_malloc = Operand::function_handle(
142 tcx.require_lang_item(LangItem::ExchangeMalloc, Some(expr_span)),
146 let storage = this.temp(tcx.mk_mut_ptr(tcx.types.u8), expr_span);
147 let success = this.cfg.start_new_block();
151 TerminatorKind::Call {
152 func: exchange_malloc,
153 args: vec![Operand::Move(size), Operand::Move(align)],
154 destination: storage,
155 target: Some(success),
157 from_hir_call: false,
161 this.diverge_from(block);
164 // The `Box<T>` temporary created here is not a part of the HIR,
165 // and therefore is not considered during generator auto-trait
166 // determination. See the comment about `box` at `yield_in_scope`.
167 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
170 Statement { source_info, kind: StatementKind::StorageLive(result) },
172 if let Some(scope) = scope {
173 // schedule a shallow free of that memory, lest we unwind:
174 this.schedule_drop_storage_and_value(expr_span, scope, result);
177 // Transmute `*mut u8` to the box (thus far, uninitialized):
178 let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value.ty);
179 this.cfg.push_assign(block, source_info, Place::from(result), box_);
181 // initialize the box contents:
183 block = this.expr_into_dest(
184 this.tcx.mk_place_deref(Place::from(result)),
189 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
191 ExprKind::Cast { source } => {
192 let source = &this.thir[source];
193 let from_ty = CastTy::from_ty(source.ty);
194 let cast_ty = CastTy::from_ty(expr.ty);
195 let cast_kind = match (from_ty, cast_ty) {
196 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
197 CastKind::PointerExposeAddress
199 (_, _) => CastKind::Misc,
201 let source = unpack!(
202 block = this.as_operand(block, scope, source, None, NeedsTemporary::No)
204 block.and(Rvalue::Cast(cast_kind, source, expr.ty))
206 ExprKind::Pointer { cast, source } => {
207 let source = unpack!(
209 this.as_operand(block, scope, &this.thir[source], None, NeedsTemporary::No)
211 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
213 ExprKind::Array { ref fields } => {
214 // (*) We would (maybe) be closer to codegen if we
215 // handled this and other aggregate cases via
216 // `into()`, not `as_rvalue` -- in that case, instead
221 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
223 // we could just generate
228 // The problem is that then we would need to:
230 // (a) have a more complex mechanism for handling
232 // (b) distinguish the case where the type `Foo` has a
233 // destructor, in which case creating an instance
234 // as a whole "arms" the destructor, and you can't
235 // write individual fields; and,
236 // (c) handle the case where the type Foo has no
237 // fields. We don't want `let x: ();` to compile
238 // to the same MIR as `let x = ();`.
240 // first process the set of fields
241 let el_ty = expr.ty.sequence_element_type(this.tcx);
242 let fields: Vec<_> = fields
247 block = this.as_operand(
252 NeedsTemporary::Maybe
258 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
260 ExprKind::Tuple { ref fields } => {
262 // first process the set of fields
263 let fields: Vec<_> = fields
268 block = this.as_operand(
273 NeedsTemporary::Maybe
279 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
281 ExprKind::Closure { closure_id, substs, ref upvars, movability, ref fake_reads } => {
282 // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
283 // and push the fake reads.
284 // This must come before creating the operands. This is required in case
285 // there is a fake read and a borrow of the same path, since otherwise the
286 // fake read might interfere with the borrow. Consider an example like this
291 // &mut x; // mutable borrow of `x`
292 // match x { _ => () } // fake read of `x`
296 for (thir_place, cause, hir_id) in fake_reads.into_iter() {
298 unpack!(block = this.as_place_builder(block, &this.thir[*thir_place]));
300 if let Ok(place_builder_resolved) =
301 place_builder.try_upvars_resolved(this.tcx, this.typeck_results)
304 place_builder_resolved.into_place(this.tcx, this.typeck_results);
305 this.cfg.push_fake_read(
307 this.source_info(this.tcx.hir().span(*hir_id)),
315 let operands: Vec<_> = upvars
319 let upvar = &this.thir[upvar];
320 match Category::of(&upvar.kind) {
321 // Use as_place to avoid creating a temporary when
322 // moving a variable into a closure, so that
323 // borrowck knows which variables to mark as being
324 // used as mut. This is OK here because the upvar
325 // expressions have no side effects and act on
327 // This occurs when capturing by copy/move, while
328 // by reference captures use as_operand
329 Some(Category::Place) => {
330 let place = unpack!(block = this.as_place(block, upvar));
331 this.consume_by_copy_or_move(place)
334 // Turn mutable borrow captures into unique
335 // borrow captures when capturing an immutable
336 // variable. This is sound because the mutation
337 // that caused the capture will cause an error.
341 BorrowKind::Mut { allow_two_phase_borrow: false },
344 block = this.limit_capture_mutability(
354 block = this.as_operand(
359 NeedsTemporary::Maybe
369 let result = match substs {
370 UpvarSubsts::Generator(substs) => {
371 // We implicitly set the discriminant to 0. See
372 // librustc_mir/transform/deaggregator.rs for details.
373 let movability = movability.unwrap();
374 Box::new(AggregateKind::Generator(closure_id, substs, movability))
376 UpvarSubsts::Closure(substs) => {
377 Box::new(AggregateKind::Closure(closure_id, substs))
380 block.and(Rvalue::Aggregate(result, operands))
382 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
383 block = unpack!(this.stmt_expr(block, expr, None));
384 block.and(Rvalue::Use(Operand::Constant(Box::new(Constant {
387 literal: ConstantKind::zero_sized(this.tcx.types.unit),
391 ExprKind::Literal { .. }
392 | ExprKind::NamedConst { .. }
393 | ExprKind::NonHirLiteral { .. }
394 | ExprKind::ConstParam { .. }
395 | ExprKind::ConstBlock { .. }
396 | ExprKind::StaticRef { .. } => {
397 let constant = this.as_constant(expr);
398 block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
401 ExprKind::Yield { .. }
402 | ExprKind::Block { .. }
403 | ExprKind::Match { .. }
404 | ExprKind::If { .. }
405 | ExprKind::NeverToAny { .. }
406 | ExprKind::Use { .. }
407 | ExprKind::Borrow { .. }
408 | ExprKind::AddressOf { .. }
409 | ExprKind::Adt { .. }
410 | ExprKind::Loop { .. }
411 | ExprKind::LogicalOp { .. }
412 | ExprKind::Call { .. }
413 | ExprKind::Field { .. }
414 | ExprKind::Let { .. }
415 | ExprKind::Deref { .. }
416 | ExprKind::Index { .. }
417 | ExprKind::VarRef { .. }
418 | ExprKind::UpvarRef { .. }
419 | ExprKind::Break { .. }
420 | ExprKind::Continue { .. }
421 | ExprKind::Return { .. }
422 | ExprKind::InlineAsm { .. }
423 | ExprKind::PlaceTypeAscription { .. }
424 | ExprKind::ValueTypeAscription { .. } => {
425 // these do not have corresponding `Rvalue` variants,
426 // so make an operand and then return that
427 debug_assert!(!matches!(
428 Category::of(&expr.kind),
429 Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
432 unpack!(block = this.as_operand(block, scope, expr, None, NeedsTemporary::No));
433 block.and(Rvalue::Use(operand))
438 pub(crate) fn build_binary_op(
440 mut block: BasicBlock,
446 ) -> BlockAnd<Rvalue<'tcx>> {
447 let source_info = self.source_info(span);
448 let bool_ty = self.tcx.types.bool;
449 if self.check_overflow && op.is_checkable() && ty.is_integral() {
450 let result_tup = self.tcx.intern_tup(&[ty, bool_ty]);
451 let result_value = self.temp(result_tup, span);
453 self.cfg.push_assign(
457 Rvalue::CheckedBinaryOp(op, Box::new((lhs.to_copy(), rhs.to_copy()))),
459 let val_fld = Field::new(0);
460 let of_fld = Field::new(1);
463 let val = tcx.mk_place_field(result_value, val_fld, ty);
464 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
466 let err = AssertKind::Overflow(op, lhs, rhs);
468 block = self.assert(block, Operand::Move(of), false, err, span);
470 block.and(Rvalue::Use(Operand::Move(val)))
472 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
473 // Checking division and remainder is more complex, since we 1. always check
474 // and 2. there are two possible failure cases, divide-by-zero and overflow.
476 let zero_err = if op == BinOp::Div {
477 AssertKind::DivisionByZero(lhs.to_copy())
479 AssertKind::RemainderByZero(lhs.to_copy())
481 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
484 let is_zero = self.temp(bool_ty, span);
485 let zero = self.zero_literal(span, ty);
486 self.cfg.push_assign(
490 Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
493 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
495 // We only need to check for the overflow in one case:
496 // MIN / -1, and only for signed values.
498 let neg_1 = self.neg_1_literal(span, ty);
499 let min = self.minval_literal(span, ty);
501 let is_neg_1 = self.temp(bool_ty, span);
502 let is_min = self.temp(bool_ty, span);
503 let of = self.temp(bool_ty, span);
505 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
507 self.cfg.push_assign(
511 Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
513 self.cfg.push_assign(
517 Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
520 let is_neg_1 = Operand::Move(is_neg_1);
521 let is_min = Operand::Move(is_min);
522 self.cfg.push_assign(
526 Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
529 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
533 block.and(Rvalue::BinaryOp(op, Box::new((lhs, rhs))))
537 fn build_zero_repeat(
539 mut block: BasicBlock,
541 scope: Option<region::Scope>,
542 outer_source_info: SourceInfo,
543 ) -> BlockAnd<Rvalue<'tcx>> {
545 let value = &this.thir[value];
546 let elem_ty = value.ty;
547 if let Some(Category::Constant) = Category::of(&value.kind) {
548 // Repeating a const does nothing
550 // For a non-const, we may need to generate an appropriate `Drop`
552 unpack!(block = this.as_operand(block, scope, value, None, NeedsTemporary::No));
553 if let Operand::Move(to_drop) = value_operand {
554 let success = this.cfg.start_new_block();
558 TerminatorKind::Drop { place: to_drop, target: success, unwind: None },
560 this.diverge_from(block);
563 this.record_operands_moved(&[value_operand]);
565 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), Vec::new()))
568 fn limit_capture_mutability(
572 temp_lifetime: Option<region::Scope>,
573 mut block: BasicBlock,
575 ) -> BlockAnd<Operand<'tcx>> {
578 let source_info = this.source_info(upvar_span);
579 let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
581 this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
583 let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
585 let mutability = match arg_place_builder.base() {
586 // We are capturing a path that starts off a local variable in the parent.
587 // The mutability of the current capture is same as the mutability
588 // of the local declaration in the parent.
589 PlaceBase::Local(local) => this.local_decls[local].mutability,
590 // Parent is a closure and we are capturing a path that is captured
591 // by the parent itself. The mutability of the current capture
592 // is same as that of the capture in the parent closure.
593 PlaceBase::Upvar { .. } => {
594 let enclosing_upvars_resolved =
595 arg_place_builder.clone().into_place(this.tcx, this.typeck_results);
597 match enclosing_upvars_resolved.as_ref() {
600 projection: &[ProjectionElem::Field(upvar_index, _), ..],
605 &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
609 local == ty::CAPTURE_STRUCT_LOCAL,
610 "Expected local to be Local(1), found {:?}",
615 this.upvar_mutbls.len() > upvar_index.index(),
616 "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
620 this.upvar_mutbls[upvar_index.index()]
622 _ => bug!("Unexpected capture place"),
627 let borrow_kind = match mutability {
628 Mutability::Not => BorrowKind::Unique,
629 Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
632 let arg_place = arg_place_builder.into_place(this.tcx, this.typeck_results);
634 this.cfg.push_assign(
638 Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
641 // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
642 // this can be `None`.
643 if let Some(temp_lifetime) = temp_lifetime {
644 this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
647 block.and(Operand::Move(Place::from(temp)))
650 // Helper to get a `-1` value of the appropriate type
651 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
652 let param_ty = ty::ParamEnv::empty().and(ty);
653 let size = self.tcx.layout_of(param_ty).unwrap().size;
654 let literal = ConstantKind::from_bits(self.tcx, size.unsigned_int_max(), param_ty);
656 self.literal_operand(span, literal)
659 // Helper to get the minimum value of the appropriate type
660 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
661 assert!(ty.is_signed());
662 let param_ty = ty::ParamEnv::empty().and(ty);
663 let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
664 let n = 1 << (bits - 1);
665 let literal = ConstantKind::from_bits(self.tcx, n, param_ty);
667 self.literal_operand(span, literal)