1 //! See docs in `build/expr/mod.rs`.
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_data_structures::indexed_vec::Idx;
6 use crate::build::expr::category::{Category, RvalueFunc};
7 use crate::build::{BlockAnd, BlockAndExtension, Builder};
9 use rustc::middle::region;
10 use rustc::mir::interpret::InterpError;
12 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty, UpvarSubsts};
15 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
16 /// See comment on `as_local_operand`
17 pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Rvalue<'tcx>>
19 M: Mirror<'tcx, Output = Expr<'tcx>>,
21 let local_scope = self.local_scope();
22 self.as_rvalue(block, local_scope, expr)
25 /// Compile `expr`, yielding an rvalue.
29 scope: Option<region::Scope>,
31 ) -> BlockAnd<Rvalue<'tcx>>
33 M: Mirror<'tcx, Output = Expr<'tcx>>,
35 let expr = self.hir.mirror(expr);
36 self.expr_as_rvalue(block, scope, expr)
41 mut block: BasicBlock,
42 scope: Option<region::Scope>,
44 ) -> BlockAnd<Rvalue<'tcx>> {
46 "expr_as_rvalue(block={:?}, scope={:?}, expr={:?})",
51 let expr_span = expr.span;
52 let source_info = this.source_info(expr_span);
60 let region_scope = (region_scope, source_info);
61 this.in_scope(region_scope, lint_level, |this| {
62 this.as_rvalue(block, scope, value)
65 ExprKind::Repeat { value, count } => {
66 let value_operand = unpack!(block = this.as_operand(block, scope, value));
67 block.and(Rvalue::Repeat(value_operand, count))
73 let arg_place = match borrow_kind {
74 BorrowKind::Shared => unpack!(block = this.as_read_only_place(block, arg)),
75 _ => unpack!(block = this.as_place(block, arg)),
77 block.and(Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place))
79 ExprKind::Binary { op, lhs, rhs } => {
80 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
81 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
82 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
84 ExprKind::Unary { op, arg } => {
85 let arg = unpack!(block = this.as_operand(block, scope, arg));
86 // Check for -MIN on signed integers
87 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
88 let bool_ty = this.hir.bool_ty();
90 let minval = this.minval_literal(expr_span, expr.ty);
91 let is_min = this.temp(bool_ty, expr_span);
97 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval),
102 Operand::Move(is_min),
104 InterpError::OverflowNeg,
108 block.and(Rvalue::UnaryOp(op, arg))
110 ExprKind::Box { value } => {
111 let value = this.hir.mirror(value);
112 // The `Box<T>` temporary created here is not a part of the HIR,
113 // and therefore is not considered during generator OIBIT
114 // determination. See the comment about `box` at `yield_in_scope`.
117 .push(LocalDecl::new_internal(expr.ty, expr_span));
122 kind: StatementKind::StorageLive(result),
125 if let Some(scope) = scope {
126 // schedule a shallow free of that memory, lest we unwind:
127 this.schedule_drop_storage_and_value(
130 &Place::Base(PlaceBase::Local(result)),
135 // malloc some memory of suitable type (thus far, uninitialized):
136 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
138 .push_assign(block, source_info, &Place::Base(PlaceBase::Local(result)), box_);
140 // initialize the box contents:
143 &Place::Base(PlaceBase::Local(result)).deref(),
147 block.and(Rvalue::Use(Operand::Move(Place::Base(PlaceBase::Local(result)))))
149 ExprKind::Cast { source } => {
150 let source = unpack!(block = this.as_operand(block, scope, source));
151 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
153 ExprKind::Pointer { cast, source } => {
154 let source = unpack!(block = this.as_operand(block, scope, source));
155 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
157 ExprKind::Array { fields } => {
158 // (*) We would (maybe) be closer to codegen if we
159 // handled this and other aggregate cases via
160 // `into()`, not `as_rvalue` -- in that case, instead
165 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
167 // we could just generate
172 // The problem is that then we would need to:
174 // (a) have a more complex mechanism for handling
176 // (b) distinguish the case where the type `Foo` has a
177 // destructor, in which case creating an instance
178 // as a whole "arms" the destructor, and you can't
179 // write individual fields; and,
180 // (c) handle the case where the type Foo has no
181 // fields. We don't want `let x: ();` to compile
182 // to the same MIR as `let x = ();`.
184 // first process the set of fields
185 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
186 let fields: Vec<_> = fields
188 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
191 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
193 ExprKind::Tuple { fields } => {
195 // first process the set of fields
196 let fields: Vec<_> = fields
198 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
201 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
210 let operands: Vec<_> = upvars
213 let upvar = this.hir.mirror(upvar);
214 match Category::of(&upvar.kind) {
215 // Use as_place to avoid creating a temporary when
216 // moving a variable into a closure, so that
217 // borrowck knows which variables to mark as being
218 // used as mut. This is OK here because the upvar
219 // expressions have no side effects and act on
221 // This occurs when capturing by copy/move, while
222 // by reference captures use as_operand
223 Some(Category::Place) => {
224 let place = unpack!(block = this.as_place(block, upvar));
225 this.consume_by_copy_or_move(place)
228 // Turn mutable borrow captures into unique
229 // borrow captures when capturing an immutable
230 // variable. This is sound because the mutation
231 // that caused the capture will cause an error.
236 allow_two_phase_borrow: false,
240 block = this.limit_capture_mutability(
241 upvar.span, upvar.ty, scope, block, arg,
244 _ => unpack!(block = this.as_operand(block, scope, upvar)),
249 let result = match substs {
250 UpvarSubsts::Generator(substs) => {
251 // We implicitly set the discriminant to 0. See
252 // librustc_mir/transform/deaggregator.rs for details.
253 let movability = movability.unwrap();
254 box AggregateKind::Generator(closure_id, substs, movability)
256 UpvarSubsts::Closure(substs) => box AggregateKind::Closure(closure_id, substs),
258 block.and(Rvalue::Aggregate(result, operands))
269 let is_union = adt_def.is_union();
270 let active_field_index = if is_union {
271 Some(fields[0].name.index())
276 // first process the set of fields that were provided
277 // (evaluating them in order given by user)
278 let fields_map: FxHashMap<_, _> = fields
283 unpack!(block = this.as_operand(block, scope, f.expr)),
287 let field_names = this.hir.all_fields(adt_def, variant_index);
289 let fields = if let Some(FruInfo { base, field_types }) = base {
290 let base = unpack!(block = this.as_place(block, base));
292 // MIR does not natively support FRU, so for each
293 // base-supplied field, generate an operand that
294 // reads it from the base.
297 .zip(field_types.into_iter())
298 .map(|(n, ty)| match fields_map.get(&n) {
299 Some(v) => v.clone(),
300 None => this.consume_by_copy_or_move(base.clone().field(n, ty)),
305 .filter_map(|n| fields_map.get(n).cloned())
309 let inferred_ty = expr.ty;
310 let user_ty = user_ty.map(|ty| {
311 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
312 span: source_info.span,
317 let adt = box AggregateKind::Adt(
324 block.and(Rvalue::Aggregate(adt, fields))
326 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
327 block = unpack!(this.stmt_expr(block, expr, None));
328 block.and(this.unit_rvalue())
330 ExprKind::Yield { value } => {
331 let value = unpack!(block = this.as_operand(block, scope, value));
332 let resume = this.cfg.start_new_block();
333 let cleanup = this.generator_drop_cleanup();
337 TerminatorKind::Yield {
343 resume.and(this.unit_rvalue())
345 ExprKind::Literal { .. }
346 | ExprKind::Block { .. }
347 | ExprKind::Match { .. }
348 | ExprKind::NeverToAny { .. }
349 | ExprKind::Use { .. }
350 | ExprKind::Loop { .. }
351 | ExprKind::LogicalOp { .. }
352 | ExprKind::Call { .. }
353 | ExprKind::Field { .. }
354 | ExprKind::Deref { .. }
355 | ExprKind::Index { .. }
356 | ExprKind::VarRef { .. }
358 | ExprKind::Break { .. }
359 | ExprKind::Continue { .. }
360 | ExprKind::Return { .. }
361 | ExprKind::InlineAsm { .. }
362 | ExprKind::StaticRef { .. }
363 | ExprKind::PlaceTypeAscription { .. }
364 | ExprKind::ValueTypeAscription { .. } => {
365 // these do not have corresponding `Rvalue` variants,
366 // so make an operand and then return that
367 debug_assert!(match Category::of(&expr.kind) {
368 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
371 let operand = unpack!(block = this.as_operand(block, scope, expr));
372 block.and(Rvalue::Use(operand))
377 pub fn build_binary_op(
379 mut block: BasicBlock,
385 ) -> BlockAnd<Rvalue<'tcx>> {
386 let source_info = self.source_info(span);
387 let bool_ty = self.hir.bool_ty();
388 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
389 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
390 let result_value = self.temp(result_tup, span);
392 self.cfg.push_assign(
396 Rvalue::CheckedBinaryOp(op, lhs, rhs),
398 let val_fld = Field::new(0);
399 let of_fld = Field::new(1);
401 let val = result_value.clone().field(val_fld, ty);
402 let of = result_value.field(of_fld, bool_ty);
404 let err = InterpError::Overflow(op);
406 block = self.assert(block, Operand::Move(of), false, err, span);
408 block.and(Rvalue::Use(Operand::Move(val)))
410 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
411 // Checking division and remainder is more complex, since we 1. always check
412 // and 2. there are two possible failure cases, divide-by-zero and overflow.
414 let (zero_err, overflow_err) = if op == BinOp::Div {
415 (InterpError::DivisionByZero, InterpError::Overflow(op))
417 (InterpError::RemainderByZero, InterpError::Overflow(op))
421 let is_zero = self.temp(bool_ty, span);
422 let zero = self.zero_literal(span, ty);
423 self.cfg.push_assign(
427 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
430 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
432 // We only need to check for the overflow in one case:
433 // MIN / -1, and only for signed values.
435 let neg_1 = self.neg_1_literal(span, ty);
436 let min = self.minval_literal(span, ty);
438 let is_neg_1 = self.temp(bool_ty, span);
439 let is_min = self.temp(bool_ty, span);
440 let of = self.temp(bool_ty, span);
442 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
444 self.cfg.push_assign(
448 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
450 self.cfg.push_assign(
454 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
457 let is_neg_1 = Operand::Move(is_neg_1);
458 let is_min = Operand::Move(is_min);
459 self.cfg.push_assign(
463 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
466 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
470 block.and(Rvalue::BinaryOp(op, lhs, rhs))
474 fn limit_capture_mutability(
478 temp_lifetime: Option<region::Scope>,
479 mut block: BasicBlock,
481 ) -> BlockAnd<Operand<'tcx>> {
484 let source_info = this.source_info(upvar_span);
487 .push(LocalDecl::new_temp(upvar_ty, upvar_span));
493 kind: StatementKind::StorageLive(temp),
497 let arg_place = unpack!(block = this.as_place(block, arg));
499 let mutability = match arg_place {
500 Place::Base(PlaceBase::Local(local)) => this.local_decls[local].mutability,
501 Place::Projection(box Projection {
502 base: Place::Base(PlaceBase::Local(local)),
503 elem: ProjectionElem::Deref,
506 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
507 this.local_decls[local].is_user_variable
513 "Unexpected capture place",
515 this.local_decls[local].mutability
517 Place::Projection(box Projection {
519 elem: ProjectionElem::Field(upvar_index, _),
521 | Place::Projection(box Projection {
523 Place::Projection(box Projection {
525 elem: ProjectionElem::Field(upvar_index, _),
527 elem: ProjectionElem::Deref,
529 // Not projected from the implicit `self` in a closure.
532 Some(local) => local == Local::new(1),
535 "Unexpected capture place"
539 this.upvar_mutbls.len() > upvar_index.index(),
540 "Unexpected capture place"
542 this.upvar_mutbls[upvar_index.index()]
544 _ => bug!("Unexpected capture place"),
547 let borrow_kind = match mutability {
548 Mutability::Not => BorrowKind::Unique,
549 Mutability::Mut => BorrowKind::Mut {
550 allow_two_phase_borrow: false,
554 this.cfg.push_assign(
557 &Place::Base(PlaceBase::Local(temp)),
558 Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
561 // In constants, temp_lifetime is None. We should not need to drop
562 // anything because no values with a destructor can be created in
563 // a constant at this time, even if the type may need dropping.
564 if let Some(temp_lifetime) = temp_lifetime {
565 this.schedule_drop_storage_and_value(
568 &Place::Base(PlaceBase::Local(temp)),
573 block.and(Operand::Move(Place::Base(PlaceBase::Local(temp))))
576 // Helper to get a `-1` value of the appropriate type
577 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
578 let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
579 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
580 let n = (!0u128) >> (128 - bits);
581 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
583 self.literal_operand(span, ty, literal)
586 // Helper to get the minimum value of the appropriate type
587 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
588 assert!(ty.is_signed());
589 let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
590 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
591 let n = 1 << (bits - 1);
592 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
594 self.literal_operand(span, ty, literal)