]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_rvalue.rs
Rollup merge of #92316 - petrochenkov:extmangle, r=wesleywiser
[rust.git] / compiler / rustc_mir_build / src / build / expr / as_rvalue.rs
1 //! See docs in `build/expr/mod.rs`.
2
3 use rustc_index::vec::Idx;
4
5 use crate::build::expr::as_place::PlaceBase;
6 use crate::build::expr::category::{Category, RvalueFunc};
7 use crate::build::{BlockAnd, BlockAndExtension, Builder};
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::{self, Ty, UpvarSubsts};
15 use rustc_span::Span;
16
17 impl<'a, 'tcx> Builder<'a, 'tcx> {
18     /// Returns an rvalue suitable for use until the end of the current
19     /// scope expression.
20     ///
21     /// The operand returned from this function will *not be valid* after
22     /// an ExprKind::Scope is passed, so please do *not* return it from
23     /// functions to avoid bad miscompiles.
24     crate fn as_local_rvalue(
25         &mut self,
26         block: BasicBlock,
27         expr: &Expr<'tcx>,
28     ) -> BlockAnd<Rvalue<'tcx>> {
29         let local_scope = self.local_scope();
30         self.as_rvalue(block, Some(local_scope), expr)
31     }
32
33     /// Compile `expr`, yielding an rvalue.
34     crate fn as_rvalue(
35         &mut self,
36         mut block: BasicBlock,
37         scope: Option<region::Scope>,
38         expr: &Expr<'tcx>,
39     ) -> BlockAnd<Rvalue<'tcx>> {
40         debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
41
42         let this = self;
43         let expr_span = expr.span;
44         let source_info = this.source_info(expr_span);
45
46         match expr.kind {
47             ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
48             ExprKind::Scope { region_scope, lint_level, value } => {
49                 let region_scope = (region_scope, source_info);
50                 this.in_scope(region_scope, lint_level, |this| {
51                     this.as_rvalue(block, scope, &this.thir[value])
52                 })
53             }
54             ExprKind::Repeat { value, count } => {
55                 let value_operand =
56                     unpack!(block = this.as_operand(block, scope, &this.thir[value], None));
57                 block.and(Rvalue::Repeat(value_operand, count))
58             }
59             ExprKind::Binary { op, lhs, rhs } => {
60                 let lhs = unpack!(block = this.as_operand(block, scope, &this.thir[lhs], None));
61                 let rhs = unpack!(block = this.as_operand(block, scope, &this.thir[rhs], None));
62                 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
63             }
64             ExprKind::Unary { op, arg } => {
65                 let arg = unpack!(block = this.as_operand(block, scope, &this.thir[arg], None));
66                 // Check for -MIN on signed integers
67                 if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
68                     let bool_ty = this.tcx.types.bool;
69
70                     let minval = this.minval_literal(expr_span, expr.ty);
71                     let is_min = this.temp(bool_ty, expr_span);
72
73                     this.cfg.push_assign(
74                         block,
75                         source_info,
76                         is_min,
77                         Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
78                     );
79
80                     block = this.assert(
81                         block,
82                         Operand::Move(is_min),
83                         false,
84                         AssertKind::OverflowNeg(arg.to_copy()),
85                         expr_span,
86                     );
87                 }
88                 block.and(Rvalue::UnaryOp(op, arg))
89             }
90             ExprKind::Box { value } => {
91                 let value = &this.thir[value];
92                 let tcx = this.tcx;
93
94                 // `exchange_malloc` is unsafe but box is safe, so need a new scope.
95                 let synth_scope = this.new_source_scope(
96                     expr_span,
97                     LintLevel::Inherited,
98                     Some(Safety::BuiltinUnsafe),
99                 );
100                 let synth_info = SourceInfo { span: expr_span, scope: synth_scope };
101
102                 let size = this.temp(tcx.types.usize, expr_span);
103                 this.cfg.push_assign(
104                     block,
105                     synth_info,
106                     size,
107                     Rvalue::NullaryOp(NullOp::SizeOf, value.ty),
108                 );
109
110                 let align = this.temp(tcx.types.usize, expr_span);
111                 this.cfg.push_assign(
112                     block,
113                     synth_info,
114                     align,
115                     Rvalue::NullaryOp(NullOp::AlignOf, value.ty),
116                 );
117
118                 // malloc some memory of suitable size and align:
119                 let exchange_malloc = Operand::function_handle(
120                     tcx,
121                     tcx.require_lang_item(LangItem::ExchangeMalloc, Some(expr_span)),
122                     ty::List::empty(),
123                     expr_span,
124                 );
125                 let storage = this.temp(tcx.mk_mut_ptr(tcx.types.u8), expr_span);
126                 let success = this.cfg.start_new_block();
127                 this.cfg.terminate(
128                     block,
129                     synth_info,
130                     TerminatorKind::Call {
131                         func: exchange_malloc,
132                         args: vec![Operand::Move(size), Operand::Move(align)],
133                         destination: Some((storage, success)),
134                         cleanup: None,
135                         from_hir_call: false,
136                         fn_span: expr_span,
137                     },
138                 );
139                 this.diverge_from(block);
140                 block = success;
141
142                 // The `Box<T>` temporary created here is not a part of the HIR,
143                 // and therefore is not considered during generator auto-trait
144                 // determination. See the comment about `box` at `yield_in_scope`.
145                 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
146                 this.cfg.push(
147                     block,
148                     Statement { source_info, kind: StatementKind::StorageLive(result) },
149                 );
150                 if let Some(scope) = scope {
151                     // schedule a shallow free of that memory, lest we unwind:
152                     this.schedule_drop_storage_and_value(expr_span, scope, result);
153                 }
154
155                 // Transmute `*mut u8` to the box (thus far, uninitialized):
156                 let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value.ty);
157                 this.cfg.push_assign(block, source_info, Place::from(result), box_);
158
159                 // initialize the box contents:
160                 unpack!(
161                     block = this.expr_into_dest(
162                         this.tcx.mk_place_deref(Place::from(result)),
163                         block,
164                         value
165                     )
166                 );
167                 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
168             }
169             ExprKind::Cast { source } => {
170                 let source =
171                     unpack!(block = this.as_operand(block, scope, &this.thir[source], None));
172                 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
173             }
174             ExprKind::Pointer { cast, source } => {
175                 let source =
176                     unpack!(block = this.as_operand(block, scope, &this.thir[source], None));
177                 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
178             }
179             ExprKind::Array { ref fields } => {
180                 // (*) We would (maybe) be closer to codegen if we
181                 // handled this and other aggregate cases via
182                 // `into()`, not `as_rvalue` -- in that case, instead
183                 // of generating
184                 //
185                 //     let tmp1 = ...1;
186                 //     let tmp2 = ...2;
187                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
188                 //
189                 // we could just generate
190                 //
191                 //     dest.f = ...1;
192                 //     dest.g = ...2;
193                 //
194                 // The problem is that then we would need to:
195                 //
196                 // (a) have a more complex mechanism for handling
197                 //     partial cleanup;
198                 // (b) distinguish the case where the type `Foo` has a
199                 //     destructor, in which case creating an instance
200                 //     as a whole "arms" the destructor, and you can't
201                 //     write individual fields; and,
202                 // (c) handle the case where the type Foo has no
203                 //     fields. We don't want `let x: ();` to compile
204                 //     to the same MIR as `let x = ();`.
205
206                 // first process the set of fields
207                 let el_ty = expr.ty.sequence_element_type(this.tcx);
208                 let fields: Vec<_> = fields
209                     .into_iter()
210                     .copied()
211                     .map(|f| unpack!(block = this.as_operand(block, scope, &this.thir[f], None)))
212                     .collect();
213
214                 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
215             }
216             ExprKind::Tuple { ref fields } => {
217                 // see (*) above
218                 // first process the set of fields
219                 let fields: Vec<_> = fields
220                     .into_iter()
221                     .copied()
222                     .map(|f| unpack!(block = this.as_operand(block, scope, &this.thir[f], None)))
223                     .collect();
224
225                 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
226             }
227             ExprKind::Closure { closure_id, substs, ref upvars, movability, ref fake_reads } => {
228                 // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
229                 // and push the fake reads.
230                 // This must come before creating the operands. This is required in case
231                 // there is a fake read and a borrow of the same path, since otherwise the
232                 // fake read might interfere with the borrow. Consider an example like this
233                 // one:
234                 // ```
235                 // let mut x = 0;
236                 // let c = || {
237                 //     &mut x; // mutable borrow of `x`
238                 //     match x { _ => () } // fake read of `x`
239                 // };
240                 // ```
241                 //
242                 for (thir_place, cause, hir_id) in fake_reads.into_iter() {
243                     let place_builder =
244                         unpack!(block = this.as_place_builder(block, &this.thir[*thir_place]));
245
246                     if let Ok(place_builder_resolved) =
247                         place_builder.try_upvars_resolved(this.tcx, this.typeck_results)
248                     {
249                         let mir_place =
250                             place_builder_resolved.into_place(this.tcx, this.typeck_results);
251                         this.cfg.push_fake_read(
252                             block,
253                             this.source_info(this.tcx.hir().span(*hir_id)),
254                             *cause,
255                             mir_place,
256                         );
257                     }
258                 }
259
260                 // see (*) above
261                 let operands: Vec<_> = upvars
262                     .into_iter()
263                     .copied()
264                     .map(|upvar| {
265                         let upvar = &this.thir[upvar];
266                         match Category::of(&upvar.kind) {
267                             // Use as_place to avoid creating a temporary when
268                             // moving a variable into a closure, so that
269                             // borrowck knows which variables to mark as being
270                             // used as mut. This is OK here because the upvar
271                             // expressions have no side effects and act on
272                             // disjoint places.
273                             // This occurs when capturing by copy/move, while
274                             // by reference captures use as_operand
275                             Some(Category::Place) => {
276                                 let place = unpack!(block = this.as_place(block, upvar));
277                                 this.consume_by_copy_or_move(place)
278                             }
279                             _ => {
280                                 // Turn mutable borrow captures into unique
281                                 // borrow captures when capturing an immutable
282                                 // variable. This is sound because the mutation
283                                 // that caused the capture will cause an error.
284                                 match upvar.kind {
285                                     ExprKind::Borrow {
286                                         borrow_kind:
287                                             BorrowKind::Mut { allow_two_phase_borrow: false },
288                                         arg,
289                                     } => unpack!(
290                                         block = this.limit_capture_mutability(
291                                             upvar.span,
292                                             upvar.ty,
293                                             scope,
294                                             block,
295                                             &this.thir[arg],
296                                         )
297                                     ),
298                                     _ => {
299                                         unpack!(block = this.as_operand(block, scope, upvar, None))
300                                     }
301                                 }
302                             }
303                         }
304                     })
305                     .collect();
306
307                 let result = match substs {
308                     UpvarSubsts::Generator(substs) => {
309                         // We implicitly set the discriminant to 0. See
310                         // librustc_mir/transform/deaggregator.rs for details.
311                         let movability = movability.unwrap();
312                         Box::new(AggregateKind::Generator(closure_id, substs, movability))
313                     }
314                     UpvarSubsts::Closure(substs) => {
315                         Box::new(AggregateKind::Closure(closure_id, substs))
316                     }
317                 };
318                 block.and(Rvalue::Aggregate(result, operands))
319             }
320             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
321                 block = unpack!(this.stmt_expr(block, expr, None));
322                 block.and(Rvalue::Use(Operand::Constant(Box::new(Constant {
323                     span: expr_span,
324                     user_ty: None,
325                     literal: ty::Const::zero_sized(this.tcx, this.tcx.types.unit).into(),
326                 }))))
327             }
328             ExprKind::Yield { .. }
329             | ExprKind::Literal { .. }
330             | ExprKind::ConstBlock { .. }
331             | ExprKind::StaticRef { .. }
332             | ExprKind::Block { .. }
333             | ExprKind::Match { .. }
334             | ExprKind::If { .. }
335             | ExprKind::NeverToAny { .. }
336             | ExprKind::Use { .. }
337             | ExprKind::Borrow { .. }
338             | ExprKind::AddressOf { .. }
339             | ExprKind::Adt { .. }
340             | ExprKind::Loop { .. }
341             | ExprKind::LogicalOp { .. }
342             | ExprKind::Call { .. }
343             | ExprKind::Field { .. }
344             | ExprKind::Let { .. }
345             | ExprKind::Deref { .. }
346             | ExprKind::Index { .. }
347             | ExprKind::VarRef { .. }
348             | ExprKind::UpvarRef { .. }
349             | ExprKind::Break { .. }
350             | ExprKind::Continue { .. }
351             | ExprKind::Return { .. }
352             | ExprKind::InlineAsm { .. }
353             | ExprKind::PlaceTypeAscription { .. }
354             | ExprKind::ValueTypeAscription { .. } => {
355                 // these do not have corresponding `Rvalue` variants,
356                 // so make an operand and then return that
357                 debug_assert!(!matches!(
358                     Category::of(&expr.kind),
359                     Some(Category::Rvalue(RvalueFunc::AsRvalue))
360                 ));
361                 let operand = unpack!(block = this.as_operand(block, scope, expr, None));
362                 block.and(Rvalue::Use(operand))
363             }
364         }
365     }
366
367     crate fn build_binary_op(
368         &mut self,
369         mut block: BasicBlock,
370         op: BinOp,
371         span: Span,
372         ty: Ty<'tcx>,
373         lhs: Operand<'tcx>,
374         rhs: Operand<'tcx>,
375     ) -> BlockAnd<Rvalue<'tcx>> {
376         let source_info = self.source_info(span);
377         let bool_ty = self.tcx.types.bool;
378         if self.check_overflow && op.is_checkable() && ty.is_integral() {
379             let result_tup = self.tcx.intern_tup(&[ty, bool_ty]);
380             let result_value = self.temp(result_tup, span);
381
382             self.cfg.push_assign(
383                 block,
384                 source_info,
385                 result_value,
386                 Rvalue::CheckedBinaryOp(op, Box::new((lhs.to_copy(), rhs.to_copy()))),
387             );
388             let val_fld = Field::new(0);
389             let of_fld = Field::new(1);
390
391             let tcx = self.tcx;
392             let val = tcx.mk_place_field(result_value, val_fld, ty);
393             let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
394
395             let err = AssertKind::Overflow(op, lhs, rhs);
396
397             block = self.assert(block, Operand::Move(of), false, err, span);
398
399             block.and(Rvalue::Use(Operand::Move(val)))
400         } else {
401             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
402                 // Checking division and remainder is more complex, since we 1. always check
403                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
404
405                 let zero_err = if op == BinOp::Div {
406                     AssertKind::DivisionByZero(lhs.to_copy())
407                 } else {
408                     AssertKind::RemainderByZero(lhs.to_copy())
409                 };
410                 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
411
412                 // Check for / 0
413                 let is_zero = self.temp(bool_ty, span);
414                 let zero = self.zero_literal(span, ty);
415                 self.cfg.push_assign(
416                     block,
417                     source_info,
418                     is_zero,
419                     Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
420                 );
421
422                 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
423
424                 // We only need to check for the overflow in one case:
425                 // MIN / -1, and only for signed values.
426                 if ty.is_signed() {
427                     let neg_1 = self.neg_1_literal(span, ty);
428                     let min = self.minval_literal(span, ty);
429
430                     let is_neg_1 = self.temp(bool_ty, span);
431                     let is_min = self.temp(bool_ty, span);
432                     let of = self.temp(bool_ty, span);
433
434                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
435
436                     self.cfg.push_assign(
437                         block,
438                         source_info,
439                         is_neg_1,
440                         Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
441                     );
442                     self.cfg.push_assign(
443                         block,
444                         source_info,
445                         is_min,
446                         Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
447                     );
448
449                     let is_neg_1 = Operand::Move(is_neg_1);
450                     let is_min = Operand::Move(is_min);
451                     self.cfg.push_assign(
452                         block,
453                         source_info,
454                         of,
455                         Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
456                     );
457
458                     block = self.assert(block, Operand::Move(of), false, overflow_err, span);
459                 }
460             }
461
462             block.and(Rvalue::BinaryOp(op, Box::new((lhs, rhs))))
463         }
464     }
465
466     fn limit_capture_mutability(
467         &mut self,
468         upvar_span: Span,
469         upvar_ty: Ty<'tcx>,
470         temp_lifetime: Option<region::Scope>,
471         mut block: BasicBlock,
472         arg: &Expr<'tcx>,
473     ) -> BlockAnd<Operand<'tcx>> {
474         let this = self;
475
476         let source_info = this.source_info(upvar_span);
477         let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
478
479         this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
480
481         let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
482
483         let mutability = match arg_place_builder.base() {
484             // We are capturing a path that starts off a local variable in the parent.
485             // The mutability of the current capture is same as the mutability
486             // of the local declaration in the parent.
487             PlaceBase::Local(local) => this.local_decls[local].mutability,
488             // Parent is a closure and we are capturing a path that is captured
489             // by the parent itself. The mutability of the current capture
490             // is same as that of the capture in the parent closure.
491             PlaceBase::Upvar { .. } => {
492                 let enclosing_upvars_resolved =
493                     arg_place_builder.clone().into_place(this.tcx, this.typeck_results);
494
495                 match enclosing_upvars_resolved.as_ref() {
496                     PlaceRef {
497                         local,
498                         projection: &[ProjectionElem::Field(upvar_index, _), ..],
499                     }
500                     | PlaceRef {
501                         local,
502                         projection:
503                             &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
504                     } => {
505                         // Not in a closure
506                         debug_assert!(
507                             local == ty::CAPTURE_STRUCT_LOCAL,
508                             "Expected local to be Local(1), found {:?}",
509                             local
510                         );
511                         // Not in a closure
512                         debug_assert!(
513                             this.upvar_mutbls.len() > upvar_index.index(),
514                             "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
515                             this.upvar_mutbls,
516                             upvar_index
517                         );
518                         this.upvar_mutbls[upvar_index.index()]
519                     }
520                     _ => bug!("Unexpected capture place"),
521                 }
522             }
523         };
524
525         let borrow_kind = match mutability {
526             Mutability::Not => BorrowKind::Unique,
527             Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
528         };
529
530         let arg_place = arg_place_builder.into_place(this.tcx, this.typeck_results);
531
532         this.cfg.push_assign(
533             block,
534             source_info,
535             Place::from(temp),
536             Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
537         );
538
539         // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
540         // this can be `None`.
541         if let Some(temp_lifetime) = temp_lifetime {
542             this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
543         }
544
545         block.and(Operand::Move(Place::from(temp)))
546     }
547
548     // Helper to get a `-1` value of the appropriate type
549     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
550         let param_ty = ty::ParamEnv::empty().and(ty);
551         let size = self.tcx.layout_of(param_ty).unwrap().size;
552         let literal = ty::Const::from_bits(self.tcx, size.unsigned_int_max(), param_ty);
553
554         self.literal_operand(span, literal)
555     }
556
557     // Helper to get the minimum value of the appropriate type
558     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
559         assert!(ty.is_signed());
560         let param_ty = ty::ParamEnv::empty().and(ty);
561         let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
562         let n = 1 << (bits - 1);
563         let literal = ty::Const::from_bits(self.tcx, n, param_ty);
564
565         self.literal_operand(span, literal)
566     }
567 }