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),
75 this.expr_into_dest(destination, then_blk, then_expr)
77 then_block.and(else_block)
82 else_blk = if let Some(else_opt) = else_opt {
83 unpack!(this.expr_into_dest(destination, else_blk, &this.thir[else_opt]))
85 // Body of the `if` expression without an `else` clause must return `()`, thus
86 // we implicitly generate an `else {}` if it is not specified.
87 let correct_si = this.source_info(expr_span.shrink_to_hi());
88 this.cfg.push_assign_unit(else_blk, correct_si, destination, this.tcx);
92 let join_block = this.cfg.start_new_block();
93 this.cfg.goto(then_blk, source_info, join_block);
94 this.cfg.goto(else_blk, source_info, join_block);
97 ExprKind::Let { expr, ref pat } => {
98 let scope = this.local_scope();
99 let (true_block, false_block) = this.in_if_then_scope(scope, |this| {
100 this.lower_let_expr(block, &this.thir[expr], pat, scope, expr_span)
103 this.cfg.push_assign_constant(
110 literal: ConstantKind::from_bool(this.tcx, true),
114 this.cfg.push_assign_constant(
121 literal: ConstantKind::from_bool(this.tcx, false),
125 let join_block = this.cfg.start_new_block();
126 this.cfg.goto(true_block, source_info, join_block);
127 this.cfg.goto(false_block, source_info, join_block);
130 ExprKind::NeverToAny { source } => {
131 let source = &this.thir[source];
133 matches!(source.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. });
135 // (#66975) Source could be a const of type `!`, so has to
136 // exist in the generated MIR.
138 block = this.as_temp(block, Some(this.local_scope()), source, Mutability::Mut,)
141 // This is an optimization. If the expression was a call then we already have an
142 // unreachable block. Don't bother to terminate it and create a new one.
146 this.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
147 let end_block = this.cfg.start_new_block();
151 ExprKind::LogicalOp { op, lhs, rhs } => {
154 // [block: If(lhs)] -true-> [else_block: dest = (rhs)]
156 // [shortcurcuit_block: dest = false]
160 // [block: If(lhs)] -false-> [else_block: dest = (rhs)]
162 // [shortcurcuit_block: dest = true]
164 let (shortcircuit_block, mut else_block, join_block) = (
165 this.cfg.start_new_block(),
166 this.cfg.start_new_block(),
167 this.cfg.start_new_block(),
170 let lhs = unpack!(block = this.as_local_operand(block, &this.thir[lhs]));
171 let blocks = match op {
172 LogicalOp::And => (else_block, shortcircuit_block),
173 LogicalOp::Or => (shortcircuit_block, else_block),
175 let term = TerminatorKind::if_(this.tcx, lhs, blocks.0, blocks.1);
176 this.cfg.terminate(block, source_info, term);
178 this.cfg.push_assign_constant(
186 LogicalOp::And => ConstantKind::from_bool(this.tcx, false),
187 LogicalOp::Or => ConstantKind::from_bool(this.tcx, true),
191 this.cfg.goto(shortcircuit_block, source_info, join_block);
193 let rhs = unpack!(else_block = this.as_local_operand(else_block, &this.thir[rhs]));
194 this.cfg.push_assign(else_block, source_info, destination, Rvalue::Use(rhs));
195 this.cfg.goto(else_block, source_info, join_block);
199 ExprKind::Loop { body } => {
202 // [loop_block] -> [body_block] -/eval. body/-> [body_block_end]
205 // | +-----------------------------------------+
206 // +-> [diverge_cleanup]
207 // The false link is required to make sure borrowck considers unwinds through the
208 // body, even when the exact code in the body cannot unwind
210 let loop_block = this.cfg.start_new_block();
213 this.cfg.goto(block, source_info, loop_block);
215 this.in_breakable_scope(Some(loop_block), destination, expr_span, move |this| {
216 // conduct the test, if necessary
217 let body_block = this.cfg.start_new_block();
221 TerminatorKind::FalseUnwind { real_target: body_block, unwind: None },
223 this.diverge_from(loop_block);
225 // The “return” value of the loop body must always be a unit. We therefore
226 // introduce a unit temporary as the destination for the loop body.
227 let tmp = this.get_unit_temp();
228 // Execute the body, branching back to the test.
230 unpack!(this.expr_into_dest(tmp, body_block, &this.thir[body]));
231 this.cfg.goto(body_block_end, source_info, loop_block);
233 // Loops are only exited by `break` expressions.
237 ExprKind::Call { ty: _, fun, ref args, from_hir_call, fn_span } => {
238 let fun = unpack!(block = this.as_local_operand(block, &this.thir[fun]));
239 let args: Vec<_> = args
242 .map(|arg| unpack!(block = this.as_local_call_operand(block, &this.thir[arg])))
245 let success = this.cfg.start_new_block();
247 this.record_operands_moved(&args);
249 debug!("expr_into_dest: fn_span={:?}", fn_span);
254 TerminatorKind::Call {
259 // The presence or absence of a return edge affects control-flow sensitive
260 // MIR checks and ultimately whether code is accepted or not. We can only
261 // omit the return edge if a return type is visibly uninhabited to a module
262 // that makes the call.
263 target: if this.tcx.is_ty_uninhabited_from(
276 this.diverge_from(block);
279 ExprKind::Use { source } => this.expr_into_dest(destination, block, &this.thir[source]),
280 ExprKind::Borrow { arg, borrow_kind } => {
281 let arg = &this.thir[arg];
282 // We don't do this in `as_rvalue` because we use `as_place`
283 // for borrow expressions, so we cannot create an `RValue` that
284 // remains valid across user code. `as_rvalue` is usually called
285 // by this method anyway, so this shouldn't cause too many
286 // unnecessary temporaries.
287 let arg_place = match borrow_kind {
288 BorrowKind::Shared => unpack!(block = this.as_read_only_place(block, arg)),
289 _ => unpack!(block = this.as_place(block, arg)),
291 let borrow = Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place);
292 this.cfg.push_assign(block, source_info, destination, borrow);
295 ExprKind::AddressOf { mutability, arg } => {
296 let arg = &this.thir[arg];
297 let place = match mutability {
298 hir::Mutability::Not => this.as_read_only_place(block, arg),
299 hir::Mutability::Mut => this.as_place(block, arg),
301 let address_of = Rvalue::AddressOf(mutability, unpack!(block = place));
302 this.cfg.push_assign(block, source_info, destination, address_of);
305 ExprKind::Adt(box Adt {
313 // See the notes for `ExprKind::Array` in `as_rvalue` and for
314 // `ExprKind::Borrow` above.
315 let is_union = adt_def.is_union();
316 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
318 let scope = this.local_scope();
320 // first process the set of fields that were provided
321 // (evaluating them in order given by user)
322 let fields_map: FxHashMap<_, _> = fields
325 let local_info = Box::new(LocalInfo::AggregateTemp);
329 block = this.as_operand(
334 NeedsTemporary::Maybe,
341 let field_names: Vec<_> =
342 (0..adt_def.variant(variant_index).fields.len()).map(Field::new).collect();
344 let fields: Vec<_> = if let Some(FruInfo { base, field_types }) = base {
346 unpack!(block = this.as_place_builder(block, &this.thir[*base]));
348 // MIR does not natively support FRU, so for each
349 // base-supplied field, generate an operand that
350 // reads it from the base.
351 iter::zip(field_names, &**field_types)
352 .map(|(n, ty)| match fields_map.get(&n) {
353 Some(v) => v.clone(),
355 let place_builder = place_builder.clone();
356 this.consume_by_copy_or_move(
359 .into_place(this.tcx, this.typeck_results),
365 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
368 let inferred_ty = expr.ty;
369 let user_ty = user_ty.map(|ty| {
370 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
371 span: source_info.span,
376 let adt = Box::new(AggregateKind::Adt(
383 this.cfg.push_assign(
387 Rvalue::Aggregate(adt, fields),
391 ExprKind::InlineAsm { template, ref operands, options, line_spans } => {
392 use rustc_middle::{mir, thir};
393 let operands = operands
395 .map(|op| match *op {
396 thir::InlineAsmOperand::In { reg, expr } => mir::InlineAsmOperand::In {
398 value: unpack!(block = this.as_local_operand(block, &this.thir[expr])),
400 thir::InlineAsmOperand::Out { reg, late, expr } => {
401 mir::InlineAsmOperand::Out {
404 place: expr.map(|expr| {
405 unpack!(block = this.as_place(block, &this.thir[expr]))
409 thir::InlineAsmOperand::InOut { reg, late, expr } => {
410 let place = unpack!(block = this.as_place(block, &this.thir[expr]));
411 mir::InlineAsmOperand::InOut {
414 // This works because asm operands must be Copy
415 in_value: Operand::Copy(place),
416 out_place: Some(place),
419 thir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
420 mir::InlineAsmOperand::InOut {
424 block = this.as_local_operand(block, &this.thir[in_expr])
426 out_place: out_expr.map(|out_expr| {
427 unpack!(block = this.as_place(block, &this.thir[out_expr]))
431 thir::InlineAsmOperand::Const { value, span } => {
432 mir::InlineAsmOperand::Const {
433 value: Box::new(Constant { span, user_ty: None, literal: value }),
436 thir::InlineAsmOperand::SymFn { value, span } => {
437 mir::InlineAsmOperand::SymFn {
438 value: Box::new(Constant { span, user_ty: None, literal: value }),
441 thir::InlineAsmOperand::SymStatic { def_id } => {
442 mir::InlineAsmOperand::SymStatic { def_id }
447 if !options.contains(InlineAsmOptions::NORETURN) {
448 this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
451 let destination_block = this.cfg.start_new_block();
455 TerminatorKind::InlineAsm {
460 destination: if options.contains(InlineAsmOptions::NORETURN) {
463 Some(destination_block)
468 if options.contains(InlineAsmOptions::MAY_UNWIND) {
469 this.diverge_from(block);
471 destination_block.unit()
474 // These cases don't actually need a destination
475 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
476 unpack!(block = this.stmt_expr(block, expr, None));
477 this.cfg.push_assign_unit(block, source_info, destination, this.tcx);
481 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Return { .. } => {
482 unpack!(block = this.stmt_expr(block, expr, None));
483 // No assign, as these have type `!`.
487 // Avoid creating a temporary
488 ExprKind::VarRef { .. }
489 | ExprKind::UpvarRef { .. }
490 | ExprKind::PlaceTypeAscription { .. }
491 | ExprKind::ValueTypeAscription { .. } => {
492 debug_assert!(Category::of(&expr.kind) == Some(Category::Place));
494 let place = unpack!(block = this.as_place(block, expr));
495 let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place));
496 this.cfg.push_assign(block, source_info, destination, rvalue);
499 ExprKind::Index { .. } | ExprKind::Deref { .. } | ExprKind::Field { .. } => {
500 debug_assert_eq!(Category::of(&expr.kind), Some(Category::Place));
502 // Create a "fake" temporary variable so that we check that the
503 // value is Sized. Usually, this is caught in type checking, but
504 // in the case of box expr there is no such check.
505 if !destination.projection.is_empty() {
506 this.local_decls.push(LocalDecl::new(expr.ty, expr.span));
509 let place = unpack!(block = this.as_place(block, expr));
510 let rvalue = Rvalue::Use(this.consume_by_copy_or_move(place));
511 this.cfg.push_assign(block, source_info, destination, rvalue);
515 ExprKind::Yield { value } => {
516 let scope = this.local_scope();
518 block = this.as_operand(
526 let resume = this.cfg.start_new_block();
530 TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None },
532 this.generator_drop_cleanup(block);
536 // these are the cases that are more naturally handled by some other mode
537 ExprKind::Unary { .. }
538 | ExprKind::Binary { .. }
539 | ExprKind::Box { .. }
540 | ExprKind::Cast { .. }
541 | ExprKind::Pointer { .. }
542 | ExprKind::Repeat { .. }
543 | ExprKind::Array { .. }
544 | ExprKind::Tuple { .. }
545 | ExprKind::Closure { .. }
546 | ExprKind::ConstBlock { .. }
547 | ExprKind::Literal { .. }
548 | ExprKind::NamedConst { .. }
549 | ExprKind::NonHirLiteral { .. }
550 | ExprKind::ConstParam { .. }
551 | ExprKind::ThreadLocalRef(_)
552 | ExprKind::StaticRef { .. } => {
553 debug_assert!(match Category::of(&expr.kind).unwrap() {
554 // should be handled above
555 Category::Rvalue(RvalueFunc::Into) => false,
557 // must be handled above or else we get an
558 // infinite loop in the builder; see
559 // e.g., `ExprKind::VarRef` above
560 Category::Place => false,
565 let rvalue = unpack!(block = this.as_local_rvalue(block, expr));
566 this.cfg.push_assign(block, source_info, destination, rvalue);
571 if !expr_is_block_or_scope {
572 let popped = this.block_context.pop();
573 assert!(popped.is_some());