1 //! Inlining pass for MIR functions
3 use rustc_attr as attr;
5 use rustc_index::bit_set::BitSet;
6 use rustc_index::vec::Idx;
7 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
8 use rustc_middle::mir::visit::*;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::subst::Subst;
11 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc_span::{hygiene::ExpnKind, ExpnData, Span};
13 use rustc_target::spec::abi::Abi;
15 use super::simplify::{remove_dead_blocks, CfgSimplifier};
16 use crate::transform::MirPass;
18 use std::ops::{Range, RangeFrom};
20 const INSTR_COST: usize = 5;
21 const CALL_PENALTY: usize = 25;
22 const LANDINGPAD_PENALTY: usize = 50;
23 const RESUME_PENALTY: usize = 45;
25 const UNKNOWN_SIZE_COST: usize = 10;
29 #[derive(Copy, Clone, Debug)]
30 struct CallSite<'tcx> {
31 callee: Instance<'tcx>,
32 fn_sig: ty::PolyFnSig<'tcx>,
34 target: Option<BasicBlock>,
35 source_info: SourceInfo,
38 impl<'tcx> MirPass<'tcx> for Inline {
39 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
40 if tcx.sess.opts.debugging_opts.mir_opt_level < 2 {
44 if tcx.sess.opts.debugging_opts.instrument_coverage {
45 // Since `Inline` happens after `InstrumentCoverage`, the function-specific coverage
46 // counters can be invalidated, such as by merging coverage counter statements from
47 // a pre-inlined function into a different function. This kind of change is invalid,
48 // so inlining must be skipped. Note: This check is performed here so inlining can
49 // be disabled without preventing other optimizations (regardless of `mir_opt_level`).
53 if inline(tcx, body) {
54 debug!("running simplify cfg on {:?}", body.source);
55 CfgSimplifier::new(body).simplify();
56 remove_dead_blocks(body);
61 fn inline(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
62 let def_id = body.source.def_id();
63 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
65 // Only do inlining into fn bodies.
66 if !tcx.hir().body_owner_kind(hir_id).is_fn_or_closure() {
69 if body.source.promoted.is_some() {
73 let mut this = Inliner {
75 param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
76 codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
81 let blocks = BasicBlock::new(0)..body.basic_blocks().next_index();
82 this.process_blocks(body, blocks);
86 struct Inliner<'tcx> {
88 param_env: ParamEnv<'tcx>,
89 /// Caller codegen attributes.
90 codegen_fn_attrs: &'tcx CodegenFnAttrs,
93 /// Stack of inlined instances.
94 history: Vec<Instance<'tcx>>,
95 /// Indicates that the caller body has been modified.
100 fn process_blocks(&mut self, caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>) {
102 let callsite = match self.get_valid_function_call(bb, &caller_body[bb], caller_body) {
107 if !self.is_mir_available(&callsite.callee, caller_body) {
108 debug!("MIR unavailable {}", callsite.callee);
112 let callee_body = self.tcx.instance_mir(callsite.callee.def);
113 if !self.should_inline(callsite, callee_body) {
117 if !self.tcx.consider_optimizing(|| {
118 format!("Inline {:?} into {}", callee_body.span, callsite.callee)
123 let callee_body = callsite.callee.subst_mir_and_normalize_erasing_regions(
129 let old_blocks = caller_body.basic_blocks().next_index();
130 self.inline_call(callsite, caller_body, callee_body);
131 let new_blocks = old_blocks..caller_body.basic_blocks().next_index();
134 self.history.push(callsite.callee);
135 self.process_blocks(caller_body, new_blocks);
140 fn is_mir_available(&self, callee: &Instance<'tcx>, caller_body: &Body<'tcx>) -> bool {
141 if let InstanceDef::Item(_) = callee.def {
142 if !self.tcx.is_mir_available(callee.def_id()) {
147 if let Some(callee_def_id) = callee.def_id().as_local() {
148 let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
149 // Avoid a cycle here by only using `instance_mir` only if we have
150 // a lower `HirId` than the callee. This ensures that the callee will
151 // not inline us. This trick only works without incremental compilation.
152 // So don't do it if that is enabled. Also avoid inlining into generators,
153 // since their `optimized_mir` is used for layout computation, which can
154 // create a cycle, even when no attempt is made to inline the function
155 // in the other direction.
156 !self.tcx.dep_graph.is_fully_enabled()
157 && self.hir_id < callee_hir_id
158 && caller_body.generator_kind.is_none()
160 // This cannot result in a cycle since the callee MIR is from another crate
161 // and is already optimized.
166 fn get_valid_function_call(
169 bb_data: &BasicBlockData<'tcx>,
170 caller_body: &Body<'tcx>,
171 ) -> Option<CallSite<'tcx>> {
172 // Don't inline calls that are in cleanup blocks.
173 if bb_data.is_cleanup {
177 // Only consider direct calls to functions
178 let terminator = bb_data.terminator();
179 if let TerminatorKind::Call { ref func, ref destination, .. } = terminator.kind {
180 let func_ty = func.ty(caller_body, self.tcx);
181 if let ty::FnDef(def_id, substs) = *func_ty.kind() {
182 // To resolve an instance its substs have to be fully normalized.
183 let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
185 Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?;
187 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
191 let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
193 return Some(CallSite {
197 target: destination.map(|(_, target)| target),
198 source_info: terminator.source_info,
206 fn should_inline(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
207 debug!("should_inline({:?})", callsite);
210 if callsite.fn_sig.c_variadic() {
211 debug!("callee is variadic - not inlining");
215 let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee.def_id());
217 let self_features = &self.codegen_fn_attrs.target_features;
218 let callee_features = &codegen_fn_attrs.target_features;
219 if callee_features.iter().any(|feature| !self_features.contains(feature)) {
220 debug!("`callee has extra target features - not inlining");
224 if self.codegen_fn_attrs.no_sanitize != codegen_fn_attrs.no_sanitize {
225 debug!("`callee has incompatible no_sanitize attribute - not inlining");
229 let hinted = match codegen_fn_attrs.inline {
230 // Just treat inline(always) as a hint for now,
231 // there are cases that prevent inlining that we
232 // need to check for first.
233 attr::InlineAttr::Always => true,
234 attr::InlineAttr::Never => {
235 debug!("`#[inline(never)]` present - not inlining");
238 attr::InlineAttr::Hint => true,
239 attr::InlineAttr::None => false,
242 // Only inline local functions if they would be eligible for cross-crate
243 // inlining. This is to ensure that the final crate doesn't have MIR that
244 // reference unexported symbols
245 if callsite.callee.def_id().is_local() {
246 if callsite.callee.substs.non_erasable_generics().count() == 0 && !hinted {
247 debug!(" callee is an exported function - not inlining");
252 let mut threshold = if hinted {
253 self.tcx.sess.opts.debugging_opts.inline_mir_hint_threshold
255 self.tcx.sess.opts.debugging_opts.inline_mir_threshold
258 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
259 debug!("#[naked] present - not inlining");
263 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
264 debug!("#[cold] present - not inlining");
268 // Give a bonus functions with a small number of blocks,
269 // We normally have two or three blocks for even
270 // very small functions.
271 if callee_body.basic_blocks().len() <= 3 {
272 threshold += threshold / 4;
274 debug!(" final inline threshold = {}", threshold);
276 // FIXME: Give a bonus to functions with only a single caller
277 let mut first_block = true;
280 // Traverse the MIR manually so we can account for the effects of
281 // inlining on the CFG.
282 let mut work_list = vec![START_BLOCK];
283 let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
284 while let Some(bb) = work_list.pop() {
285 if !visited.insert(bb.index()) {
288 let blk = &callee_body.basic_blocks()[bb];
290 for stmt in &blk.statements {
291 // Don't count StorageLive/StorageDead in the inlining cost.
293 StatementKind::StorageLive(_)
294 | StatementKind::StorageDead(_)
295 | StatementKind::Nop => {}
296 _ => cost += INSTR_COST,
299 let term = blk.terminator();
300 let mut is_drop = false;
302 TerminatorKind::Drop { ref place, target, unwind }
303 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
305 work_list.push(target);
306 // If the place doesn't actually need dropping, treat it like
308 let ty = callsite.callee.subst_mir(self.tcx, &place.ty(callee_body, tcx).ty);
309 if ty.needs_drop(tcx, self.param_env) {
310 cost += CALL_PENALTY;
311 if let Some(unwind) = unwind {
312 cost += LANDINGPAD_PENALTY;
313 work_list.push(unwind);
320 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
323 // If the function always diverges, don't inline
324 // unless the cost is zero
328 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
329 if let ty::FnDef(def_id, substs) =
330 *callsite.callee.subst_mir(self.tcx, &f.literal.ty).kind()
332 let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
333 if let Ok(Some(instance)) =
334 Instance::resolve(self.tcx, self.param_env, def_id, substs)
336 if callsite.callee == instance || self.history.contains(&instance) {
337 debug!("`callee is recursive - not inlining");
341 // Don't give intrinsics the extra penalty for calls
342 let f = tcx.fn_sig(def_id);
343 if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
346 cost += CALL_PENALTY;
349 cost += CALL_PENALTY;
351 if cleanup.is_some() {
352 cost += LANDINGPAD_PENALTY;
355 TerminatorKind::Assert { cleanup, .. } => {
356 cost += CALL_PENALTY;
358 if cleanup.is_some() {
359 cost += LANDINGPAD_PENALTY;
362 TerminatorKind::Resume => cost += RESUME_PENALTY,
363 _ => cost += INSTR_COST,
367 for &succ in term.successors() {
368 work_list.push(succ);
375 // Count up the cost of local variables and temps, if we know the size
376 // use that, otherwise we use a moderately-large dummy cost.
378 let ptr_size = tcx.data_layout.pointer_size.bytes();
380 for v in callee_body.vars_and_temps_iter() {
381 let ty = callsite.callee.subst_mir(self.tcx, &callee_body.local_decls[v].ty);
382 // Cost of the var is the size in machine-words, if we know
384 if let Some(size) = type_size_of(tcx, self.param_env, ty) {
385 cost += (size / ptr_size) as usize;
387 cost += UNKNOWN_SIZE_COST;
391 if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
392 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
395 if cost <= threshold {
396 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
399 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
407 callsite: CallSite<'tcx>,
408 caller_body: &mut Body<'tcx>,
409 mut callee_body: Body<'tcx>,
411 let terminator = caller_body[callsite.block].terminator.take().unwrap();
412 match terminator.kind {
413 TerminatorKind::Call { args, destination, cleanup, .. } => {
414 // If the call is something like `a[*i] = f(i)`, where
415 // `i : &mut usize`, then just duplicating the `a[*i]`
416 // Place could result in two different locations if `f`
417 // writes to `i`. To prevent this we need to create a temporary
418 // borrow of the place and pass the destination as `*temp` instead.
419 fn dest_needs_borrow(place: Place<'_>) -> bool {
420 for elem in place.projection.iter() {
422 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
430 let dest = if let Some((destination_place, _)) = destination {
431 if dest_needs_borrow(destination_place) {
432 trace!("creating temp for return destination");
433 let dest = Rvalue::Ref(
434 self.tcx.lifetimes.re_erased,
435 BorrowKind::Mut { allow_two_phase_borrow: false },
438 let dest_ty = dest.ty(caller_body, self.tcx);
439 let temp = Place::from(self.new_call_temp(caller_body, &callsite, dest_ty));
440 caller_body[callsite.block].statements.push(Statement {
441 source_info: callsite.source_info,
442 kind: StatementKind::Assign(box (temp, dest)),
444 self.tcx.mk_place_deref(temp)
449 trace!("creating temp for return place");
450 Place::from(self.new_call_temp(caller_body, &callsite, callee_body.return_ty()))
453 // Copy the arguments if needed.
454 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, &callee_body);
456 let mut integrator = Integrator {
458 new_locals: Local::new(caller_body.local_decls.len())..,
459 new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
460 new_blocks: BasicBlock::new(caller_body.basic_blocks().len())..,
462 return_block: callsite.target,
463 cleanup_block: cleanup,
464 in_cleanup_block: false,
466 callsite_span: callsite.source_info.span,
467 body_span: callee_body.span,
468 always_live_locals: BitSet::new_filled(callee_body.local_decls.len()),
471 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
472 // (or existing ones, in a few special cases) in the caller.
473 integrator.visit_body(&mut callee_body);
475 for scope in &mut callee_body.source_scopes {
476 // FIXME(eddyb) move this into a `fn visit_scope_data` in `Integrator`.
477 if scope.parent_scope.is_none() {
478 let callsite_scope = &caller_body.source_scopes[callsite.source_info.scope];
480 // Attach the outermost callee scope as a child of the callsite
481 // scope, via the `parent_scope` and `inlined_parent_scope` chains.
482 scope.parent_scope = Some(callsite.source_info.scope);
483 assert_eq!(scope.inlined_parent_scope, None);
484 scope.inlined_parent_scope = if callsite_scope.inlined.is_some() {
485 Some(callsite.source_info.scope)
487 callsite_scope.inlined_parent_scope
490 // Mark the outermost callee scope as an inlined one.
491 assert_eq!(scope.inlined, None);
492 scope.inlined = Some((callsite.callee, callsite.source_info.span));
493 } else if scope.inlined_parent_scope.is_none() {
494 // Make it easy to find the scope with `inlined` set above.
495 scope.inlined_parent_scope =
496 Some(integrator.map_scope(OUTERMOST_SOURCE_SCOPE));
500 // If there are any locals without storage markers, give them storage only for the
501 // duration of the call.
502 for local in callee_body.vars_and_temps_iter() {
503 if integrator.always_live_locals.contains(local) {
504 let new_local = integrator.map_local(local);
505 caller_body[callsite.block].statements.push(Statement {
506 source_info: callsite.source_info,
507 kind: StatementKind::StorageLive(new_local),
511 if let Some(block) = callsite.target {
512 // To avoid repeated O(n) insert, push any new statements to the end and rotate
515 for local in callee_body.vars_and_temps_iter().rev() {
516 if integrator.always_live_locals.contains(local) {
517 let new_local = integrator.map_local(local);
518 caller_body[block].statements.push(Statement {
519 source_info: callsite.source_info,
520 kind: StatementKind::StorageDead(new_local),
525 caller_body[block].statements.rotate_right(n);
528 // Insert all of the (mapped) parts of the callee body into the caller.
529 caller_body.local_decls.extend(
530 // FIXME(eddyb) make `Range<Local>` iterable so that we can use
531 // `callee_body.local_decls.drain(callee_body.vars_and_temps())`
533 .vars_and_temps_iter()
534 .map(|local| callee_body.local_decls[local].clone()),
536 caller_body.source_scopes.extend(callee_body.source_scopes.drain(..));
537 caller_body.var_debug_info.extend(callee_body.var_debug_info.drain(..));
538 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
540 caller_body[callsite.block].terminator = Some(Terminator {
541 source_info: callsite.source_info,
542 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
545 // Copy only unevaluated constants from the callee_body into the caller_body.
546 // Although we are only pushing `ConstKind::Unevaluated` consts to
547 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
548 // because we are calling `subst_and_normalize_erasing_regions`.
549 caller_body.required_consts.extend(
550 callee_body.required_consts.iter().copied().filter(|&constant| {
551 matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
555 kind => bug!("unexpected terminator kind {:?}", kind),
561 args: Vec<Operand<'tcx>>,
562 callsite: &CallSite<'tcx>,
563 caller_body: &mut Body<'tcx>,
564 callee_body: &Body<'tcx>,
568 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
569 // The caller provides the arguments wrapped up in a tuple:
571 // tuple_tmp = (a, b, c)
572 // Fn::call(closure_ref, tuple_tmp)
574 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
575 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
576 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
579 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
581 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
582 // if we "spill" that into *another* temporary, so that we can map the argument
583 // variable in the callee MIR directly to an argument variable on our side.
584 // So we introduce temporaries like:
586 // tmp0 = tuple_tmp.0
587 // tmp1 = tuple_tmp.1
588 // tmp2 = tuple_tmp.2
590 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
591 if callsite.fn_sig.abi() == Abi::RustCall && callee_body.spread_arg.is_none() {
592 let mut args = args.into_iter();
593 let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
594 let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
595 assert!(args.next().is_none());
597 let tuple = Place::from(tuple);
598 let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
601 bug!("Closure arguments are not passed as a tuple");
604 // The `closure_ref` in our example above.
605 let closure_ref_arg = iter::once(self_);
607 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
608 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
609 // This is e.g., `tuple_tmp.0` in our example above.
611 Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
613 // Spill to a local to make e.g., `tmp0`.
614 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
617 closure_ref_arg.chain(tuple_tmp_args).collect()
620 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
625 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
626 /// temporary `T` and an instruction `T = arg`, and returns `T`.
627 fn create_temp_if_necessary(
630 callsite: &CallSite<'tcx>,
631 caller_body: &mut Body<'tcx>,
633 // Reuse the operand if it is a moved temporary.
634 if let Operand::Move(place) = &arg {
635 if let Some(local) = place.as_local() {
636 if caller_body.local_kind(local) == LocalKind::Temp {
642 // Otherwise, create a temporary for the argument.
643 trace!("creating temp for argument {:?}", arg);
644 let arg_ty = arg.ty(caller_body, self.tcx);
645 let local = self.new_call_temp(caller_body, callsite, arg_ty);
646 caller_body[callsite.block].statements.push(Statement {
647 source_info: callsite.source_info,
648 kind: StatementKind::Assign(box (Place::from(local), Rvalue::Use(arg))),
653 /// Introduces a new temporary into the caller body that is live for the duration of the call.
656 caller_body: &mut Body<'tcx>,
657 callsite: &CallSite<'tcx>,
660 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
662 caller_body[callsite.block].statements.push(Statement {
663 source_info: callsite.source_info,
664 kind: StatementKind::StorageLive(local),
667 if let Some(block) = callsite.target {
668 caller_body[block].statements.insert(
671 source_info: callsite.source_info,
672 kind: StatementKind::StorageDead(local),
681 fn type_size_of<'tcx>(
683 param_env: ty::ParamEnv<'tcx>,
686 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
692 * Integrates blocks from the callee function into the calling function.
693 * Updates block indices, references to locals and other control flow
696 struct Integrator<'a, 'tcx> {
698 new_locals: RangeFrom<Local>,
699 new_scopes: RangeFrom<SourceScope>,
700 new_blocks: RangeFrom<BasicBlock>,
701 destination: Place<'tcx>,
702 return_block: Option<BasicBlock>,
703 cleanup_block: Option<BasicBlock>,
704 in_cleanup_block: bool,
708 always_live_locals: BitSet<Local>,
711 impl<'a, 'tcx> Integrator<'a, 'tcx> {
712 fn map_local(&self, local: Local) -> Local {
713 let new = if local == RETURN_PLACE {
714 self.destination.local
716 let idx = local.index() - 1;
717 if idx < self.args.len() {
720 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
723 trace!("mapping local `{:?}` to `{:?}`", local, new);
727 fn map_scope(&self, scope: SourceScope) -> SourceScope {
728 let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
729 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
733 fn map_block(&self, block: BasicBlock) -> BasicBlock {
734 let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
735 trace!("mapping block `{:?}` to `{:?}`", block, new);
740 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
741 fn tcx(&self) -> TyCtxt<'tcx> {
745 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
746 *local = self.map_local(*local);
749 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
750 *scope = self.map_scope(*scope);
753 fn visit_span(&mut self, span: &mut Span) {
755 ExpnData::default(ExpnKind::Inlined, *span, self.tcx.sess.edition(), None);
756 expn_data.def_site = self.body_span;
757 // Make sure that all spans track the fact that they were inlined.
758 *span = self.callsite_span.fresh_expansion(expn_data);
761 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
762 for elem in place.projection {
763 // FIXME: Make sure that return place is not used in an indexing projection, since it
764 // won't be rebased as it is supposed to be.
765 assert_ne!(ProjectionElem::Index(RETURN_PLACE), elem);
768 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
769 let dest_proj_len = self.destination.projection.len();
770 if place.local == RETURN_PLACE && dest_proj_len > 0 {
771 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
772 projs.extend(self.destination.projection);
773 projs.extend(place.projection);
775 place.projection = self.tcx.intern_place_elems(&*projs);
777 // Handles integrating any locals that occur in the base
779 self.super_place(place, context, location)
782 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
783 self.in_cleanup_block = data.is_cleanup;
784 self.super_basic_block_data(block, data);
785 self.in_cleanup_block = false;
788 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
789 self.super_retag(kind, place, loc);
791 // We have to patch all inlined retags to be aware that they are no longer
792 // happening on function entry.
793 if *kind == RetagKind::FnEntry {
794 *kind = RetagKind::Default;
798 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
799 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
802 self.always_live_locals.remove(local);
804 self.super_statement(statement, location);
807 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
808 // Don't try to modify the implicit `_0` access on return (`return` terminators are
809 // replaced down below anyways).
810 if !matches!(terminator.kind, TerminatorKind::Return) {
811 self.super_terminator(terminator, loc);
814 match terminator.kind {
815 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
816 TerminatorKind::Goto { ref mut target } => {
817 *target = self.map_block(*target);
819 TerminatorKind::SwitchInt { ref mut targets, .. } => {
820 for tgt in targets.all_targets_mut() {
821 *tgt = self.map_block(*tgt);
824 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
825 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
826 *target = self.map_block(*target);
827 if let Some(tgt) = *unwind {
828 *unwind = Some(self.map_block(tgt));
829 } else if !self.in_cleanup_block {
830 // Unless this drop is in a cleanup block, add an unwind edge to
831 // the original call's cleanup block
832 *unwind = self.cleanup_block;
835 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
836 if let Some((_, ref mut tgt)) = *destination {
837 *tgt = self.map_block(*tgt);
839 if let Some(tgt) = *cleanup {
840 *cleanup = Some(self.map_block(tgt));
841 } else if !self.in_cleanup_block {
842 // Unless this call is in a cleanup block, add an unwind edge to
843 // the original call's cleanup block
844 *cleanup = self.cleanup_block;
847 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
848 *target = self.map_block(*target);
849 if let Some(tgt) = *cleanup {
850 *cleanup = Some(self.map_block(tgt));
851 } else if !self.in_cleanup_block {
852 // Unless this assert is in a cleanup block, add an unwind edge to
853 // the original call's cleanup block
854 *cleanup = self.cleanup_block;
857 TerminatorKind::Return => {
858 terminator.kind = if let Some(tgt) = self.return_block {
859 TerminatorKind::Goto { target: tgt }
861 TerminatorKind::Unreachable
864 TerminatorKind::Resume => {
865 if let Some(tgt) = self.cleanup_block {
866 terminator.kind = TerminatorKind::Goto { target: tgt }
869 TerminatorKind::Abort => {}
870 TerminatorKind::Unreachable => {}
871 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
872 *real_target = self.map_block(*real_target);
873 *imaginary_target = self.map_block(*imaginary_target);
875 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
876 // see the ordering of passes in the optimized_mir query.
878 bug!("False unwinds should have been removed before inlining")
880 TerminatorKind::InlineAsm { ref mut destination, .. } => {
881 if let Some(ref mut tgt) = *destination {
882 *tgt = self.map_block(*tgt);