]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/into.rs
Revert "More minimal changes"
[rust.git] / compiler / rustc_mir_build / src / build / expr / into.rs
1 //! See docs in build/expr/mod.rs
2
3 use crate::build::expr::category::{Category, RvalueFunc};
4 use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary};
5 use rustc_ast::InlineAsmOptions;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stack::ensure_sufficient_stack;
8 use rustc_hir as hir;
9 use rustc_index::vec::Idx;
10 use rustc_middle::mir::*;
11 use rustc_middle::thir::*;
12 use rustc_middle::ty::CanonicalUserTypeAnnotation;
13 use std::iter;
14
15 impl<'a, 'tcx> Builder<'a, 'tcx> {
16     /// Compile `expr`, storing the result into `destination`, which
17     /// is assumed to be uninitialized.
18     pub(crate) fn expr_into_dest(
19         &mut self,
20         destination: Place<'tcx>,
21         mut block: BasicBlock,
22         expr: &Expr<'tcx>,
23     ) -> BlockAnd<()> {
24         debug!("expr_into_dest(destination={:?}, block={:?}, expr={:?})", destination, block, expr);
25
26         // since we frequently have to reference `self` from within a
27         // closure, where `self` would be shadowed, it's easier to
28         // just use the name `this` uniformly
29         let this = self;
30         let expr_span = expr.span;
31         let source_info = this.source_info(expr_span);
32
33         let expr_is_block_or_scope =
34             matches!(expr.kind, ExprKind::Block { .. } | ExprKind::Scope { .. });
35
36         if !expr_is_block_or_scope {
37             this.block_context.push(BlockFrame::SubExpr);
38         }
39
40         let block_and = match expr.kind {
41             ExprKind::Scope { region_scope, lint_level, value } => {
42                 let region_scope = (region_scope, source_info);
43                 ensure_sufficient_stack(|| {
44                     this.in_scope(region_scope, lint_level, |this| {
45                         this.expr_into_dest(destination, block, &this.thir[value])
46                     })
47                 })
48             }
49             ExprKind::Block { body: ref ast_block } => {
50                 this.ast_block(destination, block, ast_block, source_info)
51             }
52             ExprKind::Match { scrutinee, ref arms } => {
53                 this.match_expr(destination, expr_span, block, &this.thir[scrutinee], arms)
54             }
55             ExprKind::If { cond, then, else_opt, if_then_scope } => {
56                 let then_blk;
57                 let then_expr = &this.thir[then];
58                 let then_source_info = this.source_info(then_expr.span);
59                 let condition_scope = this.local_scope();
60
61                 let mut else_blk = unpack!(
62                     then_blk = this.in_scope(
63                         (if_then_scope, then_source_info),
64                         LintLevel::Inherited,
65                         |this| {
66                             let (then_block, else_block) =
67                                 this.in_if_then_scope(condition_scope, |this| {
68                                     let then_blk = unpack!(this.then_else_break(
69                                         block,
70                                         &this.thir[cond],
71                                         Some(condition_scope),
72                                         condition_scope,
73                                         then_expr.span
74                                     ));
75
76                                     this.expr_into_dest(destination, then_blk, then_expr)
77                                 });
78                             then_block.and(else_block)
79                         },
80                     )
81                 );
82
83                 else_blk = if let Some(else_opt) = else_opt {
84                     unpack!(this.expr_into_dest(destination, else_blk, &this.thir[else_opt]))
85                 } else {
86                     // Body of the `if` expression without an `else` clause must return `()`, thus
87                     // we implicitly generate an `else {}` if it is not specified.
88                     let correct_si = this.source_info(expr_span.shrink_to_hi());
89                     this.cfg.push_assign_unit(else_blk, correct_si, destination, this.tcx);
90                     else_blk
91                 };
92
93                 let join_block = this.cfg.start_new_block();
94                 this.cfg.goto(then_blk, source_info, join_block);
95                 this.cfg.goto(else_blk, source_info, join_block);
96                 join_block.unit()
97             }
98             ExprKind::Let { expr, ref pat } => {
99                 let scope = this.local_scope();
100                 let (true_block, false_block) = this.in_if_then_scope(scope, |this| {
101                     this.lower_let_expr(block, &this.thir[expr], pat, scope, None, expr_span)
102                 });
103
104                 this.cfg.push_assign_constant(
105                     true_block,
106                     source_info,
107                     destination,
108                     Constant {
109                         span: expr_span,
110                         user_ty: None,
111                         literal: ConstantKind::from_bool(this.tcx, true),
112                     },
113                 );
114
115                 this.cfg.push_assign_constant(
116                     false_block,
117                     source_info,
118                     destination,
119                     Constant {
120                         span: expr_span,
121                         user_ty: None,
122                         literal: ConstantKind::from_bool(this.tcx, false),
123                     },
124                 );
125
126                 let join_block = this.cfg.start_new_block();
127                 this.cfg.goto(true_block, source_info, join_block);
128                 this.cfg.goto(false_block, source_info, join_block);
129                 join_block.unit()
130             }
131             ExprKind::NeverToAny { source } => {
132                 let source = &this.thir[source];
133                 let is_call =
134                     matches!(source.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. });
135
136                 // (#66975) Source could be a const of type `!`, so has to
137                 // exist in the generated MIR.
138                 unpack!(
139                     block = this.as_temp(block, Some(this.local_scope()), source, Mutability::Mut,)
140                 );
141
142                 // This is an optimization. If the expression was a call then we already have an
143                 // unreachable block. Don't bother to terminate it and create a new one.
144                 if is_call {
145                     block.unit()
146                 } else {
147                     this.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
148                     let end_block = this.cfg.start_new_block();
149                     end_block.unit()
150                 }
151             }
152             ExprKind::LogicalOp { op, lhs, rhs } => {
153                 // And:
154                 //
155                 // [block: If(lhs)] -true-> [else_block: dest = (rhs)]
156                 //        | (false)
157                 //  [shortcurcuit_block: dest = false]
158                 //
159                 // Or:
160                 //
161                 // [block: If(lhs)] -false-> [else_block: dest = (rhs)]
162                 //        | (true)
163                 //  [shortcurcuit_block: dest = true]
164
165                 let (shortcircuit_block, mut else_block, join_block) = (
166                     this.cfg.start_new_block(),
167                     this.cfg.start_new_block(),
168                     this.cfg.start_new_block(),
169                 );
170
171                 let lhs = unpack!(block = this.as_local_operand(block, &this.thir[lhs]));
172                 let blocks = match op {
173                     LogicalOp::And => (else_block, shortcircuit_block),
174                     LogicalOp::Or => (shortcircuit_block, else_block),
175                 };
176                 let term = TerminatorKind::if_(this.tcx, lhs, blocks.0, blocks.1);
177                 this.cfg.terminate(block, source_info, term);
178
179                 this.cfg.push_assign_constant(
180                     shortcircuit_block,
181                     source_info,
182                     destination,
183                     Constant {
184                         span: expr_span,
185                         user_ty: None,
186                         literal: match op {
187                             LogicalOp::And => ConstantKind::from_bool(this.tcx, false),
188                             LogicalOp::Or => ConstantKind::from_bool(this.tcx, true),
189                         },
190                     },
191                 );
192                 this.cfg.goto(shortcircuit_block, source_info, join_block);
193
194                 let rhs = unpack!(else_block = this.as_local_operand(else_block, &this.thir[rhs]));
195                 this.cfg.push_assign(else_block, source_info, destination, Rvalue::Use(rhs));
196                 this.cfg.goto(else_block, source_info, join_block);
197
198                 join_block.unit()
199             }
200             ExprKind::Loop { body } => {
201                 // [block]
202                 //    |
203                 //   [loop_block] -> [body_block] -/eval. body/-> [body_block_end]
204                 //    |        ^                                         |
205                 // false link  |                                         |
206                 //    |        +-----------------------------------------+
207                 //    +-> [diverge_cleanup]
208                 // The false link is required to make sure borrowck considers unwinds through the
209                 // body, even when the exact code in the body cannot unwind
210
211                 let loop_block = this.cfg.start_new_block();
212
213                 // Start the loop.
214                 this.cfg.goto(block, source_info, loop_block);
215
216                 this.in_breakable_scope(Some(loop_block), destination, expr_span, move |this| {
217                     // conduct the test, if necessary
218                     let body_block = this.cfg.start_new_block();
219                     this.cfg.terminate(
220                         loop_block,
221                         source_info,
222                         TerminatorKind::FalseUnwind { real_target: body_block, unwind: None },
223                     );
224                     this.diverge_from(loop_block);
225
226                     // The “return” value of the loop body must always be a unit. We therefore
227                     // introduce a unit temporary as the destination for the loop body.
228                     let tmp = this.get_unit_temp();
229                     // Execute the body, branching back to the test.
230                     let body_block_end =
231                         unpack!(this.expr_into_dest(tmp, body_block, &this.thir[body]));
232                     this.cfg.goto(body_block_end, source_info, loop_block);
233
234                     // Loops are only exited by `break` expressions.
235                     None
236                 })
237             }
238             ExprKind::Call { ty: _, fun, ref args, from_hir_call, fn_span } => {
239                 let fun = unpack!(block = this.as_local_operand(block, &this.thir[fun]));
240                 let args: Vec<_> = args
241                     .into_iter()
242                     .copied()
243                     .map(|arg| unpack!(block = this.as_local_call_operand(block, &this.thir[arg])))
244                     .collect();
245
246                 let success = this.cfg.start_new_block();
247
248                 this.record_operands_moved(&args);
249
250                 debug!("expr_into_dest: fn_span={:?}", fn_span);
251
252                 this.cfg.terminate(
253                     block,
254                     source_info,
255                     TerminatorKind::Call {
256                         func: fun,
257                         args,
258                         cleanup: None,
259                         destination,
260                         // The presence or absence of a return edge affects control-flow sensitive
261                         // MIR checks and ultimately whether code is accepted or not. We can only
262                         // omit the return edge if a return type is visibly uninhabited to a module
263                         // that makes the call.
264                         target: if this.tcx.is_ty_uninhabited_from(
265                             this.parent_module,
266                             expr.ty,
267                             this.param_env,
268                         ) {
269                             None
270                         } else {
271                             Some(success)
272                         },
273                         from_hir_call,
274                         fn_span,
275                     },
276                 );
277                 this.diverge_from(block);
278                 success.unit()
279             }
280             ExprKind::Use { source } => this.expr_into_dest(destination, block, &this.thir[source]),
281             ExprKind::Borrow { arg, borrow_kind } => {
282                 let arg = &this.thir[arg];
283                 // We don't do this in `as_rvalue` because we use `as_place`
284                 // for borrow expressions, so we cannot create an `RValue` that
285                 // remains valid across user code. `as_rvalue` is usually called
286                 // by this method anyway, so this shouldn't cause too many
287                 // unnecessary temporaries.
288                 let arg_place = match borrow_kind {
289                     BorrowKind::Shared => unpack!(block = this.as_read_only_place(block, arg)),
290                     _ => unpack!(block = this.as_place(block, arg)),
291                 };
292                 let borrow = Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place);
293                 this.cfg.push_assign(block, source_info, destination, borrow);
294                 block.unit()
295             }
296             ExprKind::AddressOf { mutability, arg } => {
297                 let arg = &this.thir[arg];
298                 let place = match mutability {
299                     hir::Mutability::Not => this.as_read_only_place(block, arg),
300                     hir::Mutability::Mut => this.as_place(block, arg),
301                 };
302                 let address_of = Rvalue::AddressOf(mutability, unpack!(block = place));
303                 this.cfg.push_assign(block, source_info, destination, address_of);
304                 block.unit()
305             }
306             ExprKind::Adt(box Adt {
307                 adt_def,
308                 variant_index,
309                 substs,
310                 user_ty,
311                 ref fields,
312                 ref base,
313             }) => {
314                 // See the notes for `ExprKind::Array` in `as_rvalue` and for
315                 // `ExprKind::Borrow` above.
316                 let is_union = adt_def.is_union();
317                 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
318
319                 let scope = this.local_scope();
320
321                 // first process the set of fields that were provided
322                 // (evaluating them in order given by user)
323                 let fields_map: FxHashMap<_, _> = fields
324                     .into_iter()
325                     .map(|f| {
326                         let local_info = Box::new(LocalInfo::AggregateTemp);
327                         (
328                             f.name,
329                             unpack!(
330                                 block = this.as_operand(
331                                     block,
332                                     Some(scope),
333                                     &this.thir[f.expr],
334                                     Some(local_info),
335                                     NeedsTemporary::Maybe,
336                                 )
337                             ),
338                         )
339                     })
340                     .collect();
341
342                 let field_names: Vec<_> =
343                     (0..adt_def.variant(variant_index).fields.len()).map(Field::new).collect();
344
345                 let fields: Vec<_> = if let Some(FruInfo { base, field_types }) = base {
346                     let place_builder =
347                         unpack!(block = this.as_place_builder(block, &this.thir[*base]));
348
349                     // MIR does not natively support FRU, so for each
350                     // base-supplied field, generate an operand that
351                     // reads it from the base.
352                     iter::zip(field_names, &**field_types)
353                         .map(|(n, ty)| match fields_map.get(&n) {
354                             Some(v) => v.clone(),
355                             None => {
356                                 let place_builder = place_builder.clone();
357                                 this.consume_by_copy_or_move(
358                                     place_builder
359                                         .field(n, *ty)
360                                         .into_place(this.tcx, this.typeck_results),
361                                 )
362                             }
363                         })
364                         .collect()
365                 } else {
366                     field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
367                 };
368
369                 let inferred_ty = expr.ty;
370                 let user_ty = user_ty.map(|ty| {
371                     this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
372                         span: source_info.span,
373                         user_ty: ty,
374                         inferred_ty,
375                     })
376                 });
377                 let adt = Box::new(AggregateKind::Adt(
378                     adt_def.did(),
379                     variant_index,
380                     substs,
381                     user_ty,
382                     active_field_index,
383                 ));
384                 this.cfg.push_assign(
385                     block,
386                     source_info,
387                     destination,
388                     Rvalue::Aggregate(adt, fields),
389                 );
390                 block.unit()
391             }
392             ExprKind::InlineAsm { template, ref operands, options, line_spans } => {
393                 use rustc_middle::{mir, thir};
394                 let operands = operands
395                     .into_iter()
396                     .map(|op| match *op {
397                         thir::InlineAsmOperand::In { reg, expr } => mir::InlineAsmOperand::In {
398                             reg,
399                             value: unpack!(block = this.as_local_operand(block, &this.thir[expr])),
400                         },
401                         thir::InlineAsmOperand::Out { reg, late, expr } => {
402                             mir::InlineAsmOperand::Out {
403                                 reg,
404                                 late,
405                                 place: expr.map(|expr| {
406                                     unpack!(block = this.as_place(block, &this.thir[expr]))
407                                 }),
408                             }
409                         }
410                         thir::InlineAsmOperand::InOut { reg, late, expr } => {
411                             let place = unpack!(block = this.as_place(block, &this.thir[expr]));
412                             mir::InlineAsmOperand::InOut {
413                                 reg,
414                                 late,
415                                 // This works because asm operands must be Copy
416                                 in_value: Operand::Copy(place),
417                                 out_place: Some(place),
418                             }
419                         }
420                         thir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
421                             mir::InlineAsmOperand::InOut {
422                                 reg,
423                                 late,
424                                 in_value: unpack!(
425                                     block = this.as_local_operand(block, &this.thir[in_expr])
426                                 ),
427                                 out_place: out_expr.map(|out_expr| {
428                                     unpack!(block = this.as_place(block, &this.thir[out_expr]))
429                                 }),
430                             }
431                         }
432                         thir::InlineAsmOperand::Const { value, span } => {
433                             mir::InlineAsmOperand::Const {
434                                 value: Box::new(Constant { span, user_ty: None, literal: value }),
435                             }
436                         }
437                         thir::InlineAsmOperand::SymFn { value, span } => {
438                             mir::InlineAsmOperand::SymFn {
439                                 value: Box::new(Constant { span, user_ty: None, literal: value }),
440                             }
441                         }
442                         thir::InlineAsmOperand::SymStatic { def_id } => {
443                             mir::InlineAsmOperand::SymStatic { def_id }
444                         }
445                     })
446                     .collect();
447
448                 if !options.contains(InlineAsmOptions::NORETURN) {
449                     this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
450                 }
451
452                 let destination_block = this.cfg.start_new_block();
453                 this.cfg.terminate(
454                     block,
455                     source_info,
456                     TerminatorKind::InlineAsm {
457                         template,
458                         operands,
459                         options,
460                         line_spans,
461                         destination: if options.contains(InlineAsmOptions::NORETURN) {
462                             None
463                         } else {
464                             Some(destination_block)
465                         },
466                         cleanup: None,
467                     },
468                 );
469                 if options.contains(InlineAsmOptions::MAY_UNWIND) {
470                     this.diverge_from(block);
471                 }
472                 destination_block.unit()
473             }
474
475             // These cases don't actually need a destination
476             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
477                 unpack!(block = this.stmt_expr(block, expr, None));
478                 this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
479                 block.unit()
480             }
481
482             ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Return { .. } => {
483                 unpack!(block = this.stmt_expr(block, expr, None));
484                 // No assign, as these have type `!`.
485                 block.unit()
486             }
487
488             // Avoid creating a temporary
489             ExprKind::VarRef { .. }
490             | ExprKind::UpvarRef { .. }
491             | ExprKind::PlaceTypeAscription { .. }
492             | ExprKind::ValueTypeAscription { .. } => {
493                 debug_assert!(Category::of(&expr.kind) == Some(Category::Place));
494
495                 let place = unpack!(block = this.as_place(block, expr));
496                 let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place));
497                 this.cfg.push_assign(block, source_info, destination, rvalue);
498                 block.unit()
499             }
500             ExprKind::Index { .. } | ExprKind::Deref { .. } | ExprKind::Field { .. } => {
501                 debug_assert_eq!(Category::of(&expr.kind), Some(Category::Place));
502
503                 // Create a "fake" temporary variable so that we check that the
504                 // value is Sized. Usually, this is caught in type checking, but
505                 // in the case of box expr there is no such check.
506                 if !destination.projection.is_empty() {
507                     this.local_decls.push(LocalDecl::new(expr.ty, expr.span));
508                 }
509
510                 let place = unpack!(block = this.as_place(block, expr));
511                 let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place));
512                 this.cfg.push_assign(block, source_info, destination, rvalue);
513                 block.unit()
514             }
515
516             ExprKind::Yield { value } => {
517                 let scope = this.local_scope();
518                 let value = unpack!(
519                     block = this.as_operand(
520                         block,
521                         Some(scope),
522                         &this.thir[value],
523                         None,
524                         NeedsTemporary::No
525                     )
526                 );
527                 let resume = this.cfg.start_new_block();
528                 this.cfg.terminate(
529                     block,
530                     source_info,
531                     TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None },
532                 );
533                 this.generator_drop_cleanup(block);
534                 resume.unit()
535             }
536
537             // these are the cases that are more naturally handled by some other mode
538             ExprKind::Unary { .. }
539             | ExprKind::Binary { .. }
540             | ExprKind::Box { .. }
541             | ExprKind::Cast { .. }
542             | ExprKind::Pointer { .. }
543             | ExprKind::Repeat { .. }
544             | ExprKind::Array { .. }
545             | ExprKind::Tuple { .. }
546             | ExprKind::Closure { .. }
547             | ExprKind::ConstBlock { .. }
548             | ExprKind::Literal { .. }
549             | ExprKind::NamedConst { .. }
550             | ExprKind::NonHirLiteral { .. }
551             | ExprKind::ConstParam { .. }
552             | ExprKind::ThreadLocalRef(_)
553             | ExprKind::StaticRef { .. } => {
554                 debug_assert!(match Category::of(&expr.kind).unwrap() {
555                     // should be handled above
556                     Category::Rvalue(RvalueFunc::Into) => false,
557
558                     // must be handled above or else we get an
559                     // infinite loop in the builder; see
560                     // e.g., `ExprKind::VarRef` above
561                     Category::Place => false,
562
563                     _ => true,
564                 });
565
566                 let rvalue = unpack!(block = this.as_local_rvalue(block, expr));
567                 this.cfg.push_assign(block, source_info, destination, rvalue);
568                 block.unit()
569             }
570         };
571
572         if !expr_is_block_or_scope {
573             let popped = this.block_context.pop();
574             assert!(popped.is_some());
575         }
576
577         block_and
578     }
579 }