1 //! See docs in build/expr/mod.rs
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;
9 use rustc_index::vec::Idx;
10 use rustc_middle::mir::*;
11 use rustc_middle::thir::*;
12 use rustc_middle::ty::CanonicalUserTypeAnnotation;
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(
20 destination: Place<'tcx>,
21 mut block: BasicBlock,
24 debug!("expr_into_dest(destination={:?}, block={:?}, expr={:?})", destination, block, expr);
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
30 let expr_span = expr.span;
31 let source_info = this.source_info(expr_span);
33 let expr_is_block_or_scope =
34 matches!(expr.kind, ExprKind::Block { .. } | ExprKind::Scope { .. });
36 if !expr_is_block_or_scope {
37 this.block_context.push(BlockFrame::SubExpr);
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])
49 ExprKind::Block { body: ref ast_block } => {
50 this.ast_block(destination, block, ast_block, source_info)
52 ExprKind::Match { scrutinee, ref arms } => {
53 this.match_expr(destination, expr_span, block, &this.thir[scrutinee], arms)
55 ExprKind::If { cond, then, else_opt, if_then_scope } => {
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();
61 let mut else_blk = unpack!(
62 then_blk = this.in_scope(
63 (if_then_scope, then_source_info),
66 let (then_block, else_block) =
67 this.in_if_then_scope(condition_scope, |this| {
68 let then_blk = unpack!(this.then_else_break(
71 Some(condition_scope),
76 this.expr_into_dest(destination, then_blk, then_expr)
78 then_block.and(else_block)
83 else_blk = if let Some(else_opt) = else_opt {
84 unpack!(this.expr_into_dest(destination, else_blk, &this.thir[else_opt]))
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);
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);
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)
104 this.cfg.push_assign_constant(
111 literal: ConstantKind::from_bool(this.tcx, true),
115 this.cfg.push_assign_constant(
122 literal: ConstantKind::from_bool(this.tcx, false),
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);
131 ExprKind::NeverToAny { source } => {
132 let source = &this.thir[source];
134 matches!(source.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. });
136 // (#66975) Source could be a const of type `!`, so has to
137 // exist in the generated MIR.
139 block = this.as_temp(block, Some(this.local_scope()), source, Mutability::Mut,)
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.
147 this.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
148 let end_block = this.cfg.start_new_block();
152 ExprKind::LogicalOp { op, lhs, rhs } => {
155 // [block: If(lhs)] -true-> [else_block: dest = (rhs)]
157 // [shortcurcuit_block: dest = false]
161 // [block: If(lhs)] -false-> [else_block: dest = (rhs)]
163 // [shortcurcuit_block: dest = true]
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(),
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),
176 let term = TerminatorKind::if_(this.tcx, lhs, blocks.0, blocks.1);
177 this.cfg.terminate(block, source_info, term);
179 this.cfg.push_assign_constant(
187 LogicalOp::And => ConstantKind::from_bool(this.tcx, false),
188 LogicalOp::Or => ConstantKind::from_bool(this.tcx, true),
192 this.cfg.goto(shortcircuit_block, source_info, join_block);
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);
200 ExprKind::Loop { body } => {
203 // [loop_block] -> [body_block] -/eval. body/-> [body_block_end]
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
211 let loop_block = this.cfg.start_new_block();
214 this.cfg.goto(block, source_info, loop_block);
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();
222 TerminatorKind::FalseUnwind { real_target: body_block, unwind: None },
224 this.diverge_from(loop_block);
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.
231 unpack!(this.expr_into_dest(tmp, body_block, &this.thir[body]));
232 this.cfg.goto(body_block_end, source_info, loop_block);
234 // Loops are only exited by `break` expressions.
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
243 .map(|arg| unpack!(block = this.as_local_call_operand(block, &this.thir[arg])))
246 let success = this.cfg.start_new_block();
248 this.record_operands_moved(&args);
250 debug!("expr_into_dest: fn_span={:?}", fn_span);
255 TerminatorKind::Call {
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(
277 this.diverge_from(block);
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)),
292 let borrow = Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place);
293 this.cfg.push_assign(block, source_info, destination, borrow);
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),
302 let address_of = Rvalue::AddressOf(mutability, unpack!(block = place));
303 this.cfg.push_assign(block, source_info, destination, address_of);
306 ExprKind::Adt(box Adt {
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 };
319 let scope = this.local_scope();
321 // first process the set of fields that were provided
322 // (evaluating them in order given by user)
323 let fields_map: FxHashMap<_, _> = fields
326 let local_info = Box::new(LocalInfo::AggregateTemp);
330 block = this.as_operand(
335 NeedsTemporary::Maybe,
342 let field_names: Vec<_> =
343 (0..adt_def.variant(variant_index).fields.len()).map(Field::new).collect();
345 let fields: Vec<_> = if let Some(FruInfo { base, field_types }) = base {
347 unpack!(block = this.as_place_builder(block, &this.thir[*base]));
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(),
356 let place_builder = place_builder.clone();
357 this.consume_by_copy_or_move(
360 .into_place(this.tcx, this.typeck_results),
366 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
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,
377 let adt = Box::new(AggregateKind::Adt(
384 this.cfg.push_assign(
388 Rvalue::Aggregate(adt, fields),
392 ExprKind::InlineAsm { template, ref operands, options, line_spans } => {
393 use rustc_middle::{mir, thir};
394 let operands = operands
396 .map(|op| match *op {
397 thir::InlineAsmOperand::In { reg, expr } => mir::InlineAsmOperand::In {
399 value: unpack!(block = this.as_local_operand(block, &this.thir[expr])),
401 thir::InlineAsmOperand::Out { reg, late, expr } => {
402 mir::InlineAsmOperand::Out {
405 place: expr.map(|expr| {
406 unpack!(block = this.as_place(block, &this.thir[expr]))
410 thir::InlineAsmOperand::InOut { reg, late, expr } => {
411 let place = unpack!(block = this.as_place(block, &this.thir[expr]));
412 mir::InlineAsmOperand::InOut {
415 // This works because asm operands must be Copy
416 in_value: Operand::Copy(place),
417 out_place: Some(place),
420 thir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
421 mir::InlineAsmOperand::InOut {
425 block = this.as_local_operand(block, &this.thir[in_expr])
427 out_place: out_expr.map(|out_expr| {
428 unpack!(block = this.as_place(block, &this.thir[out_expr]))
432 thir::InlineAsmOperand::Const { value, span } => {
433 mir::InlineAsmOperand::Const {
434 value: Box::new(Constant { span, user_ty: None, literal: value }),
437 thir::InlineAsmOperand::SymFn { value, span } => {
438 mir::InlineAsmOperand::SymFn {
439 value: Box::new(Constant { span, user_ty: None, literal: value }),
442 thir::InlineAsmOperand::SymStatic { def_id } => {
443 mir::InlineAsmOperand::SymStatic { def_id }
448 if !options.contains(InlineAsmOptions::NORETURN) {
449 this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
452 let destination_block = this.cfg.start_new_block();
456 TerminatorKind::InlineAsm {
461 destination: if options.contains(InlineAsmOptions::NORETURN) {
464 Some(destination_block)
469 if options.contains(InlineAsmOptions::MAY_UNWIND) {
470 this.diverge_from(block);
472 destination_block.unit()
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);
482 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Return { .. } => {
483 unpack!(block = this.stmt_expr(block, expr, None));
484 // No assign, as these have type `!`.
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));
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);
500 ExprKind::Index { .. } | ExprKind::Deref { .. } | ExprKind::Field { .. } => {
501 debug_assert_eq!(Category::of(&expr.kind), Some(Category::Place));
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));
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);
516 ExprKind::Yield { value } => {
517 let scope = this.local_scope();
519 block = this.as_operand(
527 let resume = this.cfg.start_new_block();
531 TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None },
533 this.generator_drop_cleanup(block);
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,
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,
566 let rvalue = unpack!(block = this.as_local_rvalue(block, expr));
567 this.cfg.push_assign(block, source_info, destination, rvalue);
572 if !expr_is_block_or_scope {
573 let popped = this.block_context.pop();
574 assert!(popped.is_some());