1 //! Inlining pass for MIR functions
3 use rustc_attr as attr;
4 use rustc_index::bit_set::BitSet;
5 use rustc_index::vec::Idx;
6 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
7 use rustc_middle::mir::visit::*;
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::subst::Subst;
10 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
11 use rustc_target::spec::abi::Abi;
13 use super::simplify::{remove_dead_blocks, CfgSimplifier};
14 use crate::transform::MirPass;
15 use std::collections::VecDeque;
17 use std::ops::RangeFrom;
19 const DEFAULT_THRESHOLD: usize = 50;
20 const HINT_THRESHOLD: usize = 100;
22 const INSTR_COST: usize = 5;
23 const CALL_PENALTY: usize = 25;
24 const LANDINGPAD_PENALTY: usize = 50;
25 const RESUME_PENALTY: usize = 45;
27 const UNKNOWN_SIZE_COST: usize = 10;
31 #[derive(Copy, Clone, Debug)]
32 struct CallSite<'tcx> {
33 callee: Instance<'tcx>,
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 {
41 if tcx.sess.opts.debugging_opts.instrument_coverage {
42 // The current implementation of source code coverage injects code region counters
43 // into the MIR, and assumes a 1-to-1 correspondence between MIR and source-code-
45 debug!("function inlining is disabled when compiling with `instrument_coverage`");
49 param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
50 codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
58 struct Inliner<'tcx> {
60 param_env: ParamEnv<'tcx>,
61 codegen_fn_attrs: &'tcx CodegenFnAttrs,
65 fn run_pass(&self, caller_body: &mut Body<'tcx>) {
66 // Keep a queue of callsites to try inlining on. We take
67 // advantage of the fact that queries detect cycles here to
68 // allow us to try and fetch the fully optimized MIR of a
69 // call; if it succeeds, we can inline it and we know that
70 // they do not call us. Otherwise, we just don't try to
73 // We use a queue so that we inline "broadly" before we inline
74 // in depth. It is unclear if this is the best heuristic,
75 // really, but that's true of all the heuristics in this
78 let mut callsites = VecDeque::new();
80 let def_id = caller_body.source.def_id();
82 // Only do inlining into fn bodies.
83 let self_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
84 if self.tcx.hir().body_owner_kind(self_hir_id).is_fn_or_closure()
85 && caller_body.source.promoted.is_none()
87 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
88 if let Some(callsite) = self.get_valid_function_call(bb, bb_data, caller_body) {
89 callsites.push_back(callsite);
97 let mut changed = false;
100 local_change = false;
101 while let Some(callsite) = callsites.pop_front() {
102 debug!("checking whether to inline callsite {:?}", callsite);
104 if let InstanceDef::Item(_) = callsite.callee.def {
105 if !self.tcx.is_mir_available(callsite.callee.def_id()) {
107 "checking whether to inline callsite {:?} - MIR unavailable",
114 let callee_body = if let Some(callee_def_id) = callsite.callee.def_id().as_local() {
115 let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
116 // Avoid a cycle here by only using `instance_mir` only if we have
117 // a lower `HirId` than the callee. This ensures that the callee will
118 // not inline us. This trick only works without incremental compilation.
119 // So don't do it if that is enabled. Also avoid inlining into generators,
120 // since their `optimized_mir` is used for layout computation, which can
121 // create a cycle, even when no attempt is made to inline the function
122 // in the other direction.
123 if !self.tcx.dep_graph.is_fully_enabled()
124 && self_hir_id < callee_hir_id
125 && caller_body.generator_kind.is_none()
127 self.tcx.instance_mir(callsite.callee.def)
132 // This cannot result in a cycle since the callee MIR is from another crate
133 // and is already optimized.
134 self.tcx.instance_mir(callsite.callee.def)
137 let callee_body: &Body<'tcx> = &*callee_body;
139 let callee_body = if self.consider_optimizing(callsite, callee_body) {
140 self.tcx.subst_and_normalize_erasing_regions(
141 &callsite.callee.substs,
149 // Copy only unevaluated constants from the callee_body into the caller_body.
150 // Although we are only pushing `ConstKind::Unevaluated` consts to
151 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
152 // because we are calling `subst_and_normalize_erasing_regions`.
153 caller_body.required_consts.extend(
154 callee_body.required_consts.iter().copied().filter(|&constant| {
155 matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
159 let start = caller_body.basic_blocks().len();
160 debug!("attempting to inline callsite {:?} - body={:?}", callsite, callee_body);
161 if !self.inline_call(callsite, caller_body, callee_body) {
162 debug!("attempting to inline callsite {:?} - failure", callsite);
165 debug!("attempting to inline callsite {:?} - success", callsite);
167 // Add callsites from inlined function
168 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated().skip(start) {
169 if let Some(new_callsite) =
170 self.get_valid_function_call(bb, bb_data, caller_body)
172 // Don't inline the same function multiple times.
173 if callsite.callee != new_callsite.callee {
174 callsites.push_back(new_callsite);
188 // Simplify if we inlined anything.
190 debug!("running simplify cfg on {:?}", caller_body.source);
191 CfgSimplifier::new(caller_body).simplify();
192 remove_dead_blocks(caller_body);
196 fn get_valid_function_call(
199 bb_data: &BasicBlockData<'tcx>,
200 caller_body: &Body<'tcx>,
201 ) -> Option<CallSite<'tcx>> {
202 // Don't inline calls that are in cleanup blocks.
203 if bb_data.is_cleanup {
207 // Only consider direct calls to functions
208 let terminator = bb_data.terminator();
209 if let TerminatorKind::Call { func: ref op, .. } = terminator.kind {
210 if let ty::FnDef(callee_def_id, substs) = *op.ty(caller_body, self.tcx).kind() {
211 // To resolve an instance its substs have to be fully normalized, so
213 let normalized_substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
215 Instance::resolve(self.tcx, self.param_env, callee_def_id, normalized_substs)
219 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
223 return Some(CallSite { callee, bb, source_info: terminator.source_info });
230 fn consider_optimizing(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
231 debug!("consider_optimizing({:?})", callsite);
232 self.should_inline(callsite, callee_body)
233 && self.tcx.consider_optimizing(|| {
234 format!("Inline {:?} into {:?}", callee_body.span, callsite)
238 fn should_inline(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
239 debug!("should_inline({:?})", callsite);
242 // Cannot inline generators which haven't been transformed yet
243 if callee_body.yield_ty.is_some() {
244 debug!(" yield ty present - not inlining");
248 let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee.def_id());
250 let self_features = &self.codegen_fn_attrs.target_features;
251 let callee_features = &codegen_fn_attrs.target_features;
252 if callee_features.iter().any(|feature| !self_features.contains(feature)) {
253 debug!("`callee has extra target features - not inlining");
257 let self_no_sanitize =
258 self.codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
259 let callee_no_sanitize =
260 codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
261 if self_no_sanitize != callee_no_sanitize {
262 debug!("`callee has incompatible no_sanitize attribute - not inlining");
266 let hinted = match codegen_fn_attrs.inline {
267 // Just treat inline(always) as a hint for now,
268 // there are cases that prevent inlining that we
269 // need to check for first.
270 attr::InlineAttr::Always => true,
271 attr::InlineAttr::Never => {
272 debug!("`#[inline(never)]` present - not inlining");
275 attr::InlineAttr::Hint => true,
276 attr::InlineAttr::None => false,
279 // Only inline local functions if they would be eligible for cross-crate
280 // inlining. This is to ensure that the final crate doesn't have MIR that
281 // reference unexported symbols
282 if callsite.callee.def_id().is_local() {
283 if callsite.callee.substs.non_erasable_generics().count() == 0 && !hinted {
284 debug!(" callee is an exported function - not inlining");
289 let mut threshold = if hinted { HINT_THRESHOLD } else { DEFAULT_THRESHOLD };
291 // Significantly lower the threshold for inlining cold functions
292 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
296 // Give a bonus functions with a small number of blocks,
297 // We normally have two or three blocks for even
298 // very small functions.
299 if callee_body.basic_blocks().len() <= 3 {
300 threshold += threshold / 4;
302 debug!(" final inline threshold = {}", threshold);
304 // FIXME: Give a bonus to functions with only a single caller
305 let mut first_block = true;
308 // Traverse the MIR manually so we can account for the effects of
309 // inlining on the CFG.
310 let mut work_list = vec![START_BLOCK];
311 let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
312 while let Some(bb) = work_list.pop() {
313 if !visited.insert(bb.index()) {
316 let blk = &callee_body.basic_blocks()[bb];
318 for stmt in &blk.statements {
319 // Don't count StorageLive/StorageDead in the inlining cost.
321 StatementKind::StorageLive(_)
322 | StatementKind::StorageDead(_)
323 | StatementKind::Nop => {}
324 _ => cost += INSTR_COST,
327 let term = blk.terminator();
328 let mut is_drop = false;
330 TerminatorKind::Drop { ref place, target, unwind }
331 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
333 work_list.push(target);
334 // If the place doesn't actually need dropping, treat it like
336 let ty = place.ty(callee_body, tcx).subst(tcx, callsite.callee.substs).ty;
337 if ty.needs_drop(tcx, self.param_env) {
338 cost += CALL_PENALTY;
339 if let Some(unwind) = unwind {
340 cost += LANDINGPAD_PENALTY;
341 work_list.push(unwind);
348 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
351 // If the function always diverges, don't inline
352 // unless the cost is zero
356 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
357 if let ty::FnDef(def_id, _) = *f.literal.ty.kind() {
358 // Don't give intrinsics the extra penalty for calls
359 let f = tcx.fn_sig(def_id);
360 if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
363 cost += CALL_PENALTY;
366 cost += CALL_PENALTY;
368 if cleanup.is_some() {
369 cost += LANDINGPAD_PENALTY;
372 TerminatorKind::Assert { cleanup, .. } => {
373 cost += CALL_PENALTY;
375 if cleanup.is_some() {
376 cost += LANDINGPAD_PENALTY;
379 TerminatorKind::Resume => cost += RESUME_PENALTY,
380 _ => cost += INSTR_COST,
384 for &succ in term.successors() {
385 work_list.push(succ);
392 // Count up the cost of local variables and temps, if we know the size
393 // use that, otherwise we use a moderately-large dummy cost.
395 let ptr_size = tcx.data_layout.pointer_size.bytes();
397 for v in callee_body.vars_and_temps_iter() {
398 let v = &callee_body.local_decls[v];
399 let ty = v.ty.subst(tcx, callsite.callee.substs);
400 // Cost of the var is the size in machine-words, if we know
402 if let Some(size) = type_size_of(tcx, self.param_env, ty) {
403 cost += (size / ptr_size) as usize;
405 cost += UNKNOWN_SIZE_COST;
409 if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
410 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
413 if cost <= threshold {
414 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
417 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
425 callsite: CallSite<'tcx>,
426 caller_body: &mut Body<'tcx>,
427 mut callee_body: Body<'tcx>,
429 let terminator = caller_body[callsite.bb].terminator.take().unwrap();
430 match terminator.kind {
431 // FIXME: Handle inlining of diverging calls
432 TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
433 debug!("inlined {:?} into {:?}", callsite.callee, caller_body.source);
435 // If the call is something like `a[*i] = f(i)`, where
436 // `i : &mut usize`, then just duplicating the `a[*i]`
437 // Place could result in two different locations if `f`
438 // writes to `i`. To prevent this we need to create a temporary
439 // borrow of the place and pass the destination as `*temp` instead.
440 fn dest_needs_borrow(place: Place<'_>) -> bool {
441 for elem in place.projection.iter() {
443 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
451 let dest = if dest_needs_borrow(destination.0) {
452 debug!("creating temp for return destination");
453 let dest = Rvalue::Ref(
454 self.tcx.lifetimes.re_erased,
455 BorrowKind::Mut { allow_two_phase_borrow: false },
459 let ty = dest.ty(caller_body, self.tcx);
461 let temp = LocalDecl::new(ty, callsite.source_info.span);
463 let tmp = caller_body.local_decls.push(temp);
464 let tmp = Place::from(tmp);
466 let stmt = Statement {
467 source_info: callsite.source_info,
468 kind: StatementKind::Assign(box (tmp, dest)),
470 caller_body[callsite.bb].statements.push(stmt);
471 self.tcx.mk_place_deref(tmp)
476 let return_block = destination.1;
478 // Copy the arguments if needed.
479 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, return_block);
481 let mut integrator = Integrator {
483 new_locals: Local::new(caller_body.local_decls.len())..,
484 new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
485 new_blocks: BasicBlock::new(caller_body.basic_blocks().len())..,
488 cleanup_block: cleanup,
489 in_cleanup_block: false,
493 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
494 // (or existing ones, in a few special cases) in the caller.
495 integrator.visit_body(&mut callee_body);
497 for scope in &mut callee_body.source_scopes {
498 // FIXME(eddyb) move this into a `fn visit_scope_data` in `Integrator`.
499 if scope.parent_scope.is_none() {
500 let callsite_scope = &caller_body.source_scopes[callsite.source_info.scope];
502 // Attach the outermost callee scope as a child of the callsite
503 // scope, via the `parent_scope` and `inlined_parent_scope` chains.
504 scope.parent_scope = Some(callsite.source_info.scope);
505 assert_eq!(scope.inlined_parent_scope, None);
506 scope.inlined_parent_scope = if callsite_scope.inlined.is_some() {
507 Some(callsite.source_info.scope)
509 callsite_scope.inlined_parent_scope
512 // Mark the outermost callee scope as an inlined one.
513 assert_eq!(scope.inlined, None);
514 scope.inlined = Some((callsite.callee, callsite.source_info.span));
515 } else if scope.inlined_parent_scope.is_none() {
516 // Make it easy to find the scope with `inlined` set above.
517 scope.inlined_parent_scope =
518 Some(integrator.map_scope(OUTERMOST_SOURCE_SCOPE));
522 // Insert all of the (mapped) parts of the callee body into the caller.
523 caller_body.local_decls.extend(
524 // FIXME(eddyb) make `Range<Local>` iterable so that we can use
525 // `callee_body.local_decls.drain(callee_body.vars_and_temps())`
527 .vars_and_temps_iter()
528 .map(|local| callee_body.local_decls[local].clone()),
530 caller_body.source_scopes.extend(callee_body.source_scopes.drain(..));
531 caller_body.var_debug_info.extend(callee_body.var_debug_info.drain(..));
532 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
534 caller_body[callsite.bb].terminator = Some(Terminator {
535 source_info: callsite.source_info,
536 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
542 caller_body[callsite.bb].terminator =
543 Some(Terminator { source_info: terminator.source_info, kind });
551 args: Vec<Operand<'tcx>>,
552 callsite: &CallSite<'tcx>,
553 caller_body: &mut Body<'tcx>,
554 return_block: BasicBlock,
558 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
559 // The caller provides the arguments wrapped up in a tuple:
561 // tuple_tmp = (a, b, c)
562 // Fn::call(closure_ref, tuple_tmp)
564 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
565 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
566 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
569 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
571 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
572 // if we "spill" that into *another* temporary, so that we can map the argument
573 // variable in the callee MIR directly to an argument variable on our side.
574 // So we introduce temporaries like:
576 // tmp0 = tuple_tmp.0
577 // tmp1 = tuple_tmp.1
578 // tmp2 = tuple_tmp.2
580 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
581 // FIXME(eddyb) make this check for `"rust-call"` ABI combined with
582 // `callee_body.spread_arg == None`, instead of special-casing closures.
583 if tcx.is_closure(callsite.callee.def_id()) {
584 let mut args = args.into_iter();
585 let self_ = self.create_temp_if_necessary(
586 args.next().unwrap(),
591 let tuple = self.create_temp_if_necessary(
592 args.next().unwrap(),
597 assert!(args.next().is_none());
599 let tuple = Place::from(tuple);
600 let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
603 bug!("Closure arguments are not passed as a tuple");
606 // The `closure_ref` in our example above.
607 let closure_ref_arg = iter::once(self_);
609 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
610 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
611 // This is e.g., `tuple_tmp.0` in our example above.
613 Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
615 // Spill to a local to make e.g., `tmp0`.
616 self.create_temp_if_necessary(tuple_field, callsite, caller_body, return_block)
619 closure_ref_arg.chain(tuple_tmp_args).collect()
622 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body, return_block))
627 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
628 /// temporary `T` and an instruction `T = arg`, and returns `T`.
629 fn create_temp_if_necessary(
632 callsite: &CallSite<'tcx>,
633 caller_body: &mut Body<'tcx>,
634 return_block: BasicBlock,
636 // FIXME: Analysis of the usage of the arguments to avoid
637 // unnecessary temporaries.
639 if let Operand::Move(place) = &arg {
640 if let Some(local) = place.as_local() {
641 if caller_body.local_kind(local) == LocalKind::Temp {
642 // Reuse the operand if it's a temporary already
648 debug!("creating temp for argument {:?}", arg);
649 // Otherwise, create a temporary for the arg
650 let arg = Rvalue::Use(arg);
652 let ty = arg.ty(caller_body, self.tcx);
654 let arg_tmp = LocalDecl::new(ty, callsite.source_info.span);
655 let arg_tmp = caller_body.local_decls.push(arg_tmp);
657 caller_body[callsite.bb].statements.push(Statement {
658 source_info: callsite.source_info,
659 kind: StatementKind::StorageLive(arg_tmp),
661 caller_body[callsite.bb].statements.push(Statement {
662 source_info: callsite.source_info,
663 kind: StatementKind::Assign(box (Place::from(arg_tmp), arg)),
665 caller_body[return_block].statements.insert(
668 source_info: callsite.source_info,
669 kind: StatementKind::StorageDead(arg_tmp),
677 fn type_size_of<'tcx>(
679 param_env: ty::ParamEnv<'tcx>,
682 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
688 * Integrates blocks from the callee function into the calling function.
689 * Updates block indices, references to locals and other control flow
692 struct Integrator<'a, 'tcx> {
694 new_locals: RangeFrom<Local>,
695 new_scopes: RangeFrom<SourceScope>,
696 new_blocks: RangeFrom<BasicBlock>,
697 destination: Place<'tcx>,
698 return_block: BasicBlock,
699 cleanup_block: Option<BasicBlock>,
700 in_cleanup_block: bool,
704 impl<'a, 'tcx> Integrator<'a, 'tcx> {
705 fn map_local(&self, local: Local) -> Local {
706 let new = if local == RETURN_PLACE {
707 self.destination.local
709 let idx = local.index() - 1;
710 if idx < self.args.len() {
713 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
716 debug!("mapping local `{:?}` to `{:?}`", local, new);
720 fn map_scope(&self, scope: SourceScope) -> SourceScope {
721 let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
722 debug!("mapping scope `{:?}` to `{:?}`", scope, new);
726 fn map_block(&self, block: BasicBlock) -> BasicBlock {
727 let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
728 debug!("mapping block `{:?}` to `{:?}`", block, new);
733 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
734 fn tcx(&self) -> TyCtxt<'tcx> {
738 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
739 *local = self.map_local(*local);
742 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
743 *scope = self.map_scope(*scope);
746 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
747 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
748 let dest_proj_len = self.destination.projection.len();
749 if place.local == RETURN_PLACE && dest_proj_len > 0 {
750 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
751 projs.extend(self.destination.projection);
752 projs.extend(place.projection);
754 place.projection = self.tcx.intern_place_elems(&*projs);
756 // Handles integrating any locals that occur in the base
758 self.super_place(place, context, location)
761 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
762 self.in_cleanup_block = data.is_cleanup;
763 self.super_basic_block_data(block, data);
764 self.in_cleanup_block = false;
767 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
768 self.super_retag(kind, place, loc);
770 // We have to patch all inlined retags to be aware that they are no longer
771 // happening on function entry.
772 if *kind == RetagKind::FnEntry {
773 *kind = RetagKind::Default;
777 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
778 // Don't try to modify the implicit `_0` access on return (`return` terminators are
779 // replaced down below anyways).
780 if !matches!(terminator.kind, TerminatorKind::Return) {
781 self.super_terminator(terminator, loc);
784 match terminator.kind {
785 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
786 TerminatorKind::Goto { ref mut target } => {
787 *target = self.map_block(*target);
789 TerminatorKind::SwitchInt { ref mut targets, .. } => {
790 for tgt in targets.all_targets_mut() {
791 *tgt = self.map_block(*tgt);
794 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
795 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
796 *target = self.map_block(*target);
797 if let Some(tgt) = *unwind {
798 *unwind = Some(self.map_block(tgt));
799 } else if !self.in_cleanup_block {
800 // Unless this drop is in a cleanup block, add an unwind edge to
801 // the original call's cleanup block
802 *unwind = self.cleanup_block;
805 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
806 if let Some((_, ref mut tgt)) = *destination {
807 *tgt = self.map_block(*tgt);
809 if let Some(tgt) = *cleanup {
810 *cleanup = Some(self.map_block(tgt));
811 } else if !self.in_cleanup_block {
812 // Unless this call is in a cleanup block, add an unwind edge to
813 // the original call's cleanup block
814 *cleanup = self.cleanup_block;
817 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
818 *target = self.map_block(*target);
819 if let Some(tgt) = *cleanup {
820 *cleanup = Some(self.map_block(tgt));
821 } else if !self.in_cleanup_block {
822 // Unless this assert is in a cleanup block, add an unwind edge to
823 // the original call's cleanup block
824 *cleanup = self.cleanup_block;
827 TerminatorKind::Return => {
828 terminator.kind = TerminatorKind::Goto { target: self.return_block };
830 TerminatorKind::Resume => {
831 if let Some(tgt) = self.cleanup_block {
832 terminator.kind = TerminatorKind::Goto { target: tgt }
835 TerminatorKind::Abort => {}
836 TerminatorKind::Unreachable => {}
837 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
838 *real_target = self.map_block(*real_target);
839 *imaginary_target = self.map_block(*imaginary_target);
841 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
842 // see the ordering of passes in the optimized_mir query.
844 bug!("False unwinds should have been removed before inlining")
846 TerminatorKind::InlineAsm { ref mut destination, .. } => {
847 if let Some(ref mut tgt) = *destination {
848 *tgt = self.map_block(*tgt);