1 //! See docs in `build/expr/mod.rs`.
3 use rustc_index::vec::Idx;
5 use crate::build::expr::category::{Category, RvalueFunc};
6 use crate::build::{BlockAnd, BlockAndExtension, Builder};
8 use rustc::middle::region;
9 use rustc::mir::interpret::PanicInfo;
11 use rustc::ty::{self, Ty, UpvarSubsts};
14 impl<'a, 'tcx> Builder<'a, 'tcx> {
15 /// Returns an rvalue suitable for use until the end of the current
18 /// The operand returned from this function will *not be valid* after
19 /// an ExprKind::Scope is passed, so please do *not* return it from
20 /// functions to avoid bad miscompiles.
21 pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Rvalue<'tcx>>
23 M: Mirror<'tcx, Output = Expr<'tcx>>,
25 let local_scope = self.local_scope();
26 self.as_rvalue(block, local_scope, expr)
29 /// Compile `expr`, yielding an rvalue.
33 scope: Option<region::Scope>,
35 ) -> BlockAnd<Rvalue<'tcx>>
37 M: Mirror<'tcx, Output = Expr<'tcx>>,
39 let expr = self.hir.mirror(expr);
40 self.expr_as_rvalue(block, scope, expr)
45 mut block: BasicBlock,
46 scope: Option<region::Scope>,
48 ) -> BlockAnd<Rvalue<'tcx>> {
50 "expr_as_rvalue(block={:?}, scope={:?}, expr={:?})",
55 let expr_span = expr.span;
56 let source_info = this.source_info(expr_span);
64 let region_scope = (region_scope, source_info);
65 this.in_scope(region_scope, lint_level, |this| {
66 this.as_rvalue(block, scope, value)
69 ExprKind::Repeat { value, count } => {
70 let value_operand = unpack!(block = this.as_operand(block, scope, value));
71 block.and(Rvalue::Repeat(value_operand, count))
73 ExprKind::Binary { op, lhs, rhs } => {
74 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
75 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
76 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
78 ExprKind::Unary { op, arg } => {
79 let arg = unpack!(block = this.as_operand(block, scope, arg));
80 // Check for -MIN on signed integers
81 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
82 let bool_ty = this.hir.bool_ty();
84 let minval = this.minval_literal(expr_span, expr.ty);
85 let is_min = this.temp(bool_ty, expr_span);
91 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval),
96 Operand::Move(is_min),
98 PanicInfo::OverflowNeg,
102 block.and(Rvalue::UnaryOp(op, arg))
104 ExprKind::Box { value } => {
105 let value = this.hir.mirror(value);
106 // The `Box<T>` temporary created here is not a part of the HIR,
107 // and therefore is not considered during generator OIBIT
108 // determination. See the comment about `box` at `yield_in_scope`.
111 .push(LocalDecl::new_internal(expr.ty, expr_span));
116 kind: StatementKind::StorageLive(result),
119 if let Some(scope) = scope {
120 // schedule a shallow free of that memory, lest we unwind:
121 this.schedule_drop_storage_and_value(
128 // malloc some memory of suitable type (thus far, uninitialized):
129 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
131 .push_assign(block, source_info, &Place::from(result), box_);
133 // initialize the box contents:
136 &this.hir.tcx().mk_place_deref(Place::from(result)),
140 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
142 ExprKind::Cast { source } => {
143 let source = unpack!(block = this.as_operand(block, scope, source));
144 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
146 ExprKind::Pointer { cast, source } => {
147 let source = unpack!(block = this.as_operand(block, scope, source));
148 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
150 ExprKind::Array { fields } => {
151 // (*) We would (maybe) be closer to codegen if we
152 // handled this and other aggregate cases via
153 // `into()`, not `as_rvalue` -- in that case, instead
158 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
160 // we could just generate
165 // The problem is that then we would need to:
167 // (a) have a more complex mechanism for handling
169 // (b) distinguish the case where the type `Foo` has a
170 // destructor, in which case creating an instance
171 // as a whole "arms" the destructor, and you can't
172 // write individual fields; and,
173 // (c) handle the case where the type Foo has no
174 // fields. We don't want `let x: ();` to compile
175 // to the same MIR as `let x = ();`.
177 // first process the set of fields
178 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
179 let fields: Vec<_> = fields
181 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
184 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
186 ExprKind::Tuple { fields } => {
188 // first process the set of fields
189 let fields: Vec<_> = fields
191 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
194 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
203 let operands: Vec<_> = upvars
206 let upvar = this.hir.mirror(upvar);
207 match Category::of(&upvar.kind) {
208 // Use as_place to avoid creating a temporary when
209 // moving a variable into a closure, so that
210 // borrowck knows which variables to mark as being
211 // used as mut. This is OK here because the upvar
212 // expressions have no side effects and act on
214 // This occurs when capturing by copy/move, while
215 // by reference captures use as_operand
216 Some(Category::Place) => {
217 let place = unpack!(block = this.as_place(block, upvar));
218 this.consume_by_copy_or_move(place)
221 // Turn mutable borrow captures into unique
222 // borrow captures when capturing an immutable
223 // variable. This is sound because the mutation
224 // that caused the capture will cause an error.
229 allow_two_phase_borrow: false,
233 block = this.limit_capture_mutability(
234 upvar.span, upvar.ty, scope, block, arg,
237 _ => unpack!(block = this.as_operand(block, scope, upvar)),
242 let result = match substs {
243 UpvarSubsts::Generator(substs) => {
244 // We implicitly set the discriminant to 0. See
245 // librustc_mir/transform/deaggregator.rs for details.
246 let movability = movability.unwrap();
247 box AggregateKind::Generator(closure_id, substs, movability)
249 UpvarSubsts::Closure(substs) => box AggregateKind::Closure(closure_id, substs),
251 block.and(Rvalue::Aggregate(result, operands))
253 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
254 block = unpack!(this.stmt_expr(block, expr, None));
255 block.and(this.unit_rvalue())
257 ExprKind::Yield { value } => {
258 let value = unpack!(block = this.as_operand(block, scope, value));
259 let resume = this.cfg.start_new_block();
260 let cleanup = this.generator_drop_cleanup();
264 TerminatorKind::Yield {
270 resume.and(this.unit_rvalue())
272 ExprKind::Literal { .. }
273 | ExprKind::StaticRef { .. }
274 | ExprKind::Block { .. }
275 | ExprKind::Match { .. }
276 | ExprKind::NeverToAny { .. }
277 | ExprKind::Use { .. }
278 | ExprKind::Borrow { .. }
279 | ExprKind::AddressOf { .. }
280 | ExprKind::Adt { .. }
281 | ExprKind::Loop { .. }
282 | ExprKind::LogicalOp { .. }
283 | ExprKind::Call { .. }
284 | ExprKind::Field { .. }
285 | ExprKind::Deref { .. }
286 | ExprKind::Index { .. }
287 | ExprKind::VarRef { .. }
289 | ExprKind::Break { .. }
290 | ExprKind::Continue { .. }
291 | ExprKind::Return { .. }
292 | ExprKind::InlineAsm { .. }
293 | ExprKind::PlaceTypeAscription { .. }
294 | ExprKind::ValueTypeAscription { .. } => {
295 // these do not have corresponding `Rvalue` variants,
296 // so make an operand and then return that
297 debug_assert!(match Category::of(&expr.kind) {
298 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
301 let operand = unpack!(block = this.as_operand(block, scope, expr));
302 block.and(Rvalue::Use(operand))
307 pub fn build_binary_op(
309 mut block: BasicBlock,
315 ) -> BlockAnd<Rvalue<'tcx>> {
316 let source_info = self.source_info(span);
317 let bool_ty = self.hir.bool_ty();
318 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
319 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
320 let result_value = self.temp(result_tup, span);
322 self.cfg.push_assign(
326 Rvalue::CheckedBinaryOp(op, lhs, rhs),
328 let val_fld = Field::new(0);
329 let of_fld = Field::new(1);
331 let tcx = self.hir.tcx();
332 let val = tcx.mk_place_field(result_value.clone(), val_fld, ty);
333 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
335 let err = PanicInfo::Overflow(op);
337 block = self.assert(block, Operand::Move(of), false, err, span);
339 block.and(Rvalue::Use(Operand::Move(val)))
341 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
342 // Checking division and remainder is more complex, since we 1. always check
343 // and 2. there are two possible failure cases, divide-by-zero and overflow.
345 let zero_err = if op == BinOp::Div {
346 PanicInfo::DivisionByZero
348 PanicInfo::RemainderByZero
350 let overflow_err = PanicInfo::Overflow(op);
353 let is_zero = self.temp(bool_ty, span);
354 let zero = self.zero_literal(span, ty);
355 self.cfg.push_assign(
359 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
362 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
364 // We only need to check for the overflow in one case:
365 // MIN / -1, and only for signed values.
367 let neg_1 = self.neg_1_literal(span, ty);
368 let min = self.minval_literal(span, ty);
370 let is_neg_1 = self.temp(bool_ty, span);
371 let is_min = self.temp(bool_ty, span);
372 let of = self.temp(bool_ty, span);
374 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
376 self.cfg.push_assign(
380 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
382 self.cfg.push_assign(
386 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
389 let is_neg_1 = Operand::Move(is_neg_1);
390 let is_min = Operand::Move(is_min);
391 self.cfg.push_assign(
395 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
398 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
402 block.and(Rvalue::BinaryOp(op, lhs, rhs))
406 fn limit_capture_mutability(
410 temp_lifetime: Option<region::Scope>,
411 mut block: BasicBlock,
413 ) -> BlockAnd<Operand<'tcx>> {
416 let source_info = this.source_info(upvar_span);
419 .push(LocalDecl::new_temp(upvar_ty, upvar_span));
425 kind: StatementKind::StorageLive(temp),
429 let arg_place = unpack!(block = this.as_place(block, arg));
431 let mutability = match arg_place.as_ref() {
433 base: &PlaceBase::Local(local),
435 } => this.local_decls[local].mutability,
437 base: &PlaceBase::Local(local),
438 projection: &[ProjectionElem::Deref],
441 this.local_decls[local].is_ref_for_guard(),
442 "Unexpected capture place",
444 this.local_decls[local].mutability
448 projection: &[ref proj_base @ .., ProjectionElem::Field(upvar_index, _)],
454 ProjectionElem::Field(upvar_index, _),
455 ProjectionElem::Deref
458 let place = PlaceRef {
460 projection: proj_base,
463 // Not projected from the implicit `self` in a closure.
465 match place.local_or_deref_local() {
466 Some(local) => local == Local::new(1),
469 "Unexpected capture place"
473 this.upvar_mutbls.len() > upvar_index.index(),
474 "Unexpected capture place"
476 this.upvar_mutbls[upvar_index.index()]
478 _ => bug!("Unexpected capture place"),
481 let borrow_kind = match mutability {
482 Mutability::Not => BorrowKind::Unique,
483 Mutability::Mut => BorrowKind::Mut {
484 allow_two_phase_borrow: false,
488 this.cfg.push_assign(
492 Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
495 // In constants, temp_lifetime is None. We should not need to drop
496 // anything because no values with a destructor can be created in
497 // a constant at this time, even if the type may need dropping.
498 if let Some(temp_lifetime) = temp_lifetime {
499 this.schedule_drop_storage_and_value(
506 block.and(Operand::Move(Place::from(temp)))
509 // Helper to get a `-1` value of the appropriate type
510 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
511 let param_ty = ty::ParamEnv::empty().and(ty);
512 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
513 let n = (!0u128) >> (128 - bits);
514 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
516 self.literal_operand(span, literal)
519 // Helper to get the minimum value of the appropriate type
520 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
521 assert!(ty.is_signed());
522 let param_ty = ty::ParamEnv::empty().and(ty);
523 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
524 let n = 1 << (bits - 1);
525 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
527 self.literal_operand(span, literal)