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::middle::region;
9 use rustc_middle::mir::AssertKind;
10 use rustc_middle::mir::*;
11 use rustc_middle::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 crate 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>> {
49 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
52 let expr_span = expr.span;
53 let source_info = this.source_info(expr_span);
56 ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
57 ExprKind::Scope { region_scope, lint_level, value } => {
58 let region_scope = (region_scope, source_info);
59 this.in_scope(region_scope, lint_level, |this| this.as_rvalue(block, scope, value))
61 ExprKind::Repeat { value, count } => {
62 let value_operand = unpack!(block = this.as_operand(block, scope, value));
63 block.and(Rvalue::Repeat(value_operand, count))
65 ExprKind::Binary { op, lhs, rhs } => {
66 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
67 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
68 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
70 ExprKind::Unary { op, arg } => {
71 let arg = unpack!(block = this.as_operand(block, scope, arg));
72 // Check for -MIN on signed integers
73 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
74 let bool_ty = this.hir.bool_ty();
76 let minval = this.minval_literal(expr_span, expr.ty);
77 let is_min = this.temp(bool_ty, expr_span);
83 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval),
88 Operand::Move(is_min),
90 AssertKind::OverflowNeg(arg.to_copy()),
94 block.and(Rvalue::UnaryOp(op, arg))
96 ExprKind::Box { value } => {
97 let value = this.hir.mirror(value);
98 // The `Box<T>` temporary created here is not a part of the HIR,
99 // and therefore is not considered during generator OIBIT
100 // determination. See the comment about `box` at `yield_in_scope`.
101 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
104 Statement { source_info, kind: StatementKind::StorageLive(result) },
106 if let Some(scope) = scope {
107 // schedule a shallow free of that memory, lest we unwind:
108 this.schedule_drop_storage_and_value(expr_span, scope, result);
111 // malloc some memory of suitable type (thus far, uninitialized):
112 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
113 this.cfg.push_assign(block, source_info, Place::from(result), box_);
115 // initialize the box contents:
118 this.into(this.hir.tcx().mk_place_deref(Place::from(result)), block, value)
120 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
122 ExprKind::Cast { source } => {
123 let source = unpack!(block = this.as_operand(block, scope, source));
124 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
126 ExprKind::Pointer { cast, source } => {
127 let source = unpack!(block = this.as_operand(block, scope, source));
128 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
130 ExprKind::Array { fields } => {
131 // (*) We would (maybe) be closer to codegen if we
132 // handled this and other aggregate cases via
133 // `into()`, not `as_rvalue` -- in that case, instead
138 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
140 // we could just generate
145 // The problem is that then we would need to:
147 // (a) have a more complex mechanism for handling
149 // (b) distinguish the case where the type `Foo` has a
150 // destructor, in which case creating an instance
151 // as a whole "arms" the destructor, and you can't
152 // write individual fields; and,
153 // (c) handle the case where the type Foo has no
154 // fields. We don't want `let x: ();` to compile
155 // to the same MIR as `let x = ();`.
157 // first process the set of fields
158 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
159 let fields: Vec<_> = fields
161 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
164 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
166 ExprKind::Tuple { fields } => {
168 // first process the set of fields
169 let fields: Vec<_> = fields
171 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
174 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
176 ExprKind::Closure { closure_id, substs, upvars, movability } => {
178 let operands: Vec<_> = upvars
181 let upvar = this.hir.mirror(upvar);
182 match Category::of(&upvar.kind) {
183 // Use as_place to avoid creating a temporary when
184 // moving a variable into a closure, so that
185 // borrowck knows which variables to mark as being
186 // used as mut. This is OK here because the upvar
187 // expressions have no side effects and act on
189 // This occurs when capturing by copy/move, while
190 // by reference captures use as_operand
191 Some(Category::Place) => {
192 let place = unpack!(block = this.as_place(block, upvar));
193 this.consume_by_copy_or_move(place)
196 // Turn mutable borrow captures into unique
197 // borrow captures when capturing an immutable
198 // variable. This is sound because the mutation
199 // that caused the capture will cause an error.
203 BorrowKind::Mut { allow_two_phase_borrow: false },
206 block = this.limit_capture_mutability(
207 upvar.span, upvar.ty, scope, block, arg,
210 _ => unpack!(block = this.as_operand(block, scope, upvar)),
216 let result = match substs {
217 UpvarSubsts::Generator(substs) => {
218 // We implicitly set the discriminant to 0. See
219 // librustc_mir/transform/deaggregator.rs for details.
220 let movability = movability.unwrap();
221 box AggregateKind::Generator(closure_id, substs, movability)
223 UpvarSubsts::Closure(substs) => box AggregateKind::Closure(closure_id, substs),
225 block.and(Rvalue::Aggregate(result, operands))
227 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
228 block = unpack!(this.stmt_expr(block, expr, None));
229 block.and(Rvalue::Use(Operand::Constant(box Constant {
232 literal: ty::Const::zero_sized(this.hir.tcx(), this.hir.tcx().types.unit),
235 ExprKind::Yield { .. }
236 | ExprKind::Literal { .. }
237 | ExprKind::ConstBlock { .. }
238 | ExprKind::StaticRef { .. }
239 | ExprKind::Block { .. }
240 | ExprKind::Match { .. }
241 | ExprKind::NeverToAny { .. }
242 | ExprKind::Use { .. }
243 | ExprKind::Borrow { .. }
244 | ExprKind::AddressOf { .. }
245 | ExprKind::Adt { .. }
246 | ExprKind::Loop { .. }
247 | ExprKind::LogicalOp { .. }
248 | ExprKind::Call { .. }
249 | ExprKind::Field { .. }
250 | ExprKind::Deref { .. }
251 | ExprKind::Index { .. }
252 | ExprKind::VarRef { .. }
254 | ExprKind::Break { .. }
255 | ExprKind::Continue { .. }
256 | ExprKind::Return { .. }
257 | ExprKind::InlineAsm { .. }
258 | ExprKind::LlvmInlineAsm { .. }
259 | ExprKind::PlaceTypeAscription { .. }
260 | ExprKind::ValueTypeAscription { .. } => {
261 // these do not have corresponding `Rvalue` variants,
262 // so make an operand and then return that
263 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Rvalue(RvalueFunc::AsRvalue))));
264 let operand = unpack!(block = this.as_operand(block, scope, expr));
265 block.and(Rvalue::Use(operand))
270 crate fn build_binary_op(
272 mut block: BasicBlock,
278 ) -> BlockAnd<Rvalue<'tcx>> {
279 let source_info = self.source_info(span);
280 let bool_ty = self.hir.bool_ty();
281 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
282 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
283 let result_value = self.temp(result_tup, span);
285 self.cfg.push_assign(
289 Rvalue::CheckedBinaryOp(op, lhs.to_copy(), rhs.to_copy()),
291 let val_fld = Field::new(0);
292 let of_fld = Field::new(1);
294 let tcx = self.hir.tcx();
295 let val = tcx.mk_place_field(result_value, val_fld, ty);
296 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
298 let err = AssertKind::Overflow(op, lhs, rhs);
300 block = self.assert(block, Operand::Move(of), false, err, span);
302 block.and(Rvalue::Use(Operand::Move(val)))
304 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
305 // Checking division and remainder is more complex, since we 1. always check
306 // and 2. there are two possible failure cases, divide-by-zero and overflow.
308 let zero_err = if op == BinOp::Div {
309 AssertKind::DivisionByZero(lhs.to_copy())
311 AssertKind::RemainderByZero(lhs.to_copy())
313 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
316 let is_zero = self.temp(bool_ty, span);
317 let zero = self.zero_literal(span, ty);
318 self.cfg.push_assign(
322 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
325 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
327 // We only need to check for the overflow in one case:
328 // MIN / -1, and only for signed values.
330 let neg_1 = self.neg_1_literal(span, ty);
331 let min = self.minval_literal(span, ty);
333 let is_neg_1 = self.temp(bool_ty, span);
334 let is_min = self.temp(bool_ty, span);
335 let of = self.temp(bool_ty, span);
337 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
339 self.cfg.push_assign(
343 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
345 self.cfg.push_assign(
349 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
352 let is_neg_1 = Operand::Move(is_neg_1);
353 let is_min = Operand::Move(is_min);
354 self.cfg.push_assign(
358 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
361 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
365 block.and(Rvalue::BinaryOp(op, lhs, rhs))
369 fn limit_capture_mutability(
373 temp_lifetime: Option<region::Scope>,
374 mut block: BasicBlock,
376 ) -> BlockAnd<Operand<'tcx>> {
379 let source_info = this.source_info(upvar_span);
380 let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
382 this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
384 let arg_place = unpack!(block = this.as_place(block, arg));
386 let mutability = match arg_place.as_ref() {
387 PlaceRef { local, projection: &[] } => this.local_decls[local].mutability,
388 PlaceRef { local, projection: &[ProjectionElem::Deref] } => {
390 this.local_decls[local].is_ref_for_guard(),
391 "Unexpected capture place",
393 this.local_decls[local].mutability
397 projection: &[ref proj_base @ .., ProjectionElem::Field(upvar_index, _)],
402 &[ref proj_base @ .., ProjectionElem::Field(upvar_index, _), ProjectionElem::Deref],
404 let place = PlaceRef { local, projection: proj_base };
406 // Not projected from the implicit `self` in a closure.
408 match place.local_or_deref_local() {
409 Some(local) => local == Local::new(1),
412 "Unexpected capture place"
416 this.upvar_mutbls.len() > upvar_index.index(),
417 "Unexpected capture place"
419 this.upvar_mutbls[upvar_index.index()]
421 _ => bug!("Unexpected capture place"),
424 let borrow_kind = match mutability {
425 Mutability::Not => BorrowKind::Unique,
426 Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
429 this.cfg.push_assign(
433 Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
436 // In constants, temp_lifetime is None. We should not need to drop
437 // anything because no values with a destructor can be created in
438 // a constant at this time, even if the type may need dropping.
439 if let Some(temp_lifetime) = temp_lifetime {
440 this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
443 block.and(Operand::Move(Place::from(temp)))
446 // Helper to get a `-1` value of the appropriate type
447 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
448 let param_ty = ty::ParamEnv::empty().and(ty);
449 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
450 let n = (!0u128) >> (128 - bits);
451 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
453 self.literal_operand(span, literal)
456 // Helper to get the minimum value of the appropriate type
457 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
458 assert!(ty.is_signed());
459 let param_ty = ty::ParamEnv::empty().and(ty);
460 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
461 let n = 1 << (bits - 1);
462 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
464 self.literal_operand(span, literal)