]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/inline.rs
Refactor how SwitchInt stores jump targets
[rust.git] / compiler / rustc_mir / src / transform / inline.rs
1 //! Inlining pass for MIR functions
2
3 use rustc_attr as attr;
4 use rustc_hir::def_id::DefId;
5 use rustc_index::bit_set::BitSet;
6 use rustc_index::vec::{Idx, IndexVec};
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, SubstsRef};
11 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc_target::spec::abi::Abi;
13
14 use super::simplify::{remove_dead_blocks, CfgSimplifier};
15 use crate::transform::MirPass;
16 use std::collections::VecDeque;
17 use std::iter;
18
19 const DEFAULT_THRESHOLD: usize = 50;
20 const HINT_THRESHOLD: usize = 100;
21
22 const INSTR_COST: usize = 5;
23 const CALL_PENALTY: usize = 25;
24 const LANDINGPAD_PENALTY: usize = 50;
25 const RESUME_PENALTY: usize = 45;
26
27 const UNKNOWN_SIZE_COST: usize = 10;
28
29 pub struct Inline;
30
31 #[derive(Copy, Clone, Debug)]
32 struct CallSite<'tcx> {
33     callee: DefId,
34     substs: SubstsRef<'tcx>,
35     bb: BasicBlock,
36     location: SourceInfo,
37 }
38
39 impl<'tcx> MirPass<'tcx> for Inline {
40     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
41         if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
42             if tcx.sess.opts.debugging_opts.instrument_coverage {
43                 // The current implementation of source code coverage injects code region counters
44                 // into the MIR, and assumes a 1-to-1 correspondence between MIR and source-code-
45                 // based function.
46                 debug!("function inlining is disabled when compiling with `instrument_coverage`");
47             } else {
48                 Inliner {
49                     tcx,
50                     param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
51                     codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
52                 }
53                 .run_pass(body);
54             }
55         }
56     }
57 }
58
59 struct Inliner<'tcx> {
60     tcx: TyCtxt<'tcx>,
61     param_env: ParamEnv<'tcx>,
62     codegen_fn_attrs: &'tcx CodegenFnAttrs,
63 }
64
65 impl Inliner<'tcx> {
66     fn run_pass(&self, caller_body: &mut Body<'tcx>) {
67         // Keep a queue of callsites to try inlining on. We take
68         // advantage of the fact that queries detect cycles here to
69         // allow us to try and fetch the fully optimized MIR of a
70         // call; if it succeeds, we can inline it and we know that
71         // they do not call us.  Otherwise, we just don't try to
72         // inline.
73         //
74         // We use a queue so that we inline "broadly" before we inline
75         // in depth. It is unclear if this is the best heuristic,
76         // really, but that's true of all the heuristics in this
77         // file. =)
78
79         let mut callsites = VecDeque::new();
80
81         let def_id = caller_body.source.def_id();
82
83         // Only do inlining into fn bodies.
84         let self_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
85         if self.tcx.hir().body_owner_kind(self_hir_id).is_fn_or_closure()
86             && caller_body.source.promoted.is_none()
87         {
88             for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
89                 if let Some(callsite) = self.get_valid_function_call(bb, bb_data, caller_body) {
90                     callsites.push_back(callsite);
91                 }
92             }
93         } else {
94             return;
95         }
96
97         let mut local_change;
98         let mut changed = false;
99
100         loop {
101             local_change = false;
102             while let Some(callsite) = callsites.pop_front() {
103                 debug!("checking whether to inline callsite {:?}", callsite);
104                 if !self.tcx.is_mir_available(callsite.callee) {
105                     debug!("checking whether to inline callsite {:?} - MIR unavailable", callsite);
106                     continue;
107                 }
108
109                 let callee_body = if let Some(callee_def_id) = callsite.callee.as_local() {
110                     let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
111                     // Avoid a cycle here by only using `optimized_mir` only if we have
112                     // a lower `HirId` than the callee. This ensures that the callee will
113                     // not inline us. This trick only works without incremental compilation.
114                     // So don't do it if that is enabled. Also avoid inlining into generators,
115                     // since their `optimized_mir` is used for layout computation, which can
116                     // create a cycle, even when no attempt is made to inline the function
117                     // in the other direction.
118                     if !self.tcx.dep_graph.is_fully_enabled()
119                         && self_hir_id < callee_hir_id
120                         && caller_body.generator_kind.is_none()
121                     {
122                         self.tcx.optimized_mir(callsite.callee)
123                     } else {
124                         continue;
125                     }
126                 } else {
127                     // This cannot result in a cycle since the callee MIR is from another crate
128                     // and is already optimized.
129                     self.tcx.optimized_mir(callsite.callee)
130                 };
131
132                 let callee_body = if self.consider_optimizing(callsite, callee_body) {
133                     self.tcx.subst_and_normalize_erasing_regions(
134                         &callsite.substs,
135                         self.param_env,
136                         callee_body,
137                     )
138                 } else {
139                     continue;
140                 };
141
142                 // Copy only unevaluated constants from the callee_body into the caller_body.
143                 // Although we are only pushing `ConstKind::Unevaluated` consts to
144                 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
145                 // because we are calling `subst_and_normalize_erasing_regions`.
146                 caller_body.required_consts.extend(
147                     callee_body.required_consts.iter().copied().filter(|&constant| {
148                         matches!(constant.literal.val, ConstKind::Unevaluated(_, _, _))
149                     }),
150                 );
151
152                 let start = caller_body.basic_blocks().len();
153                 debug!("attempting to inline callsite {:?} - body={:?}", callsite, callee_body);
154                 if !self.inline_call(callsite, caller_body, callee_body) {
155                     debug!("attempting to inline callsite {:?} - failure", callsite);
156                     continue;
157                 }
158                 debug!("attempting to inline callsite {:?} - success", callsite);
159
160                 // Add callsites from inlined function
161                 for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated().skip(start) {
162                     if let Some(new_callsite) =
163                         self.get_valid_function_call(bb, bb_data, caller_body)
164                     {
165                         // Don't inline the same function multiple times.
166                         if callsite.callee != new_callsite.callee {
167                             callsites.push_back(new_callsite);
168                         }
169                     }
170                 }
171
172                 local_change = true;
173                 changed = true;
174             }
175
176             if !local_change {
177                 break;
178             }
179         }
180
181         // Simplify if we inlined anything.
182         if changed {
183             debug!("running simplify cfg on {:?}", caller_body.source);
184             CfgSimplifier::new(caller_body).simplify();
185             remove_dead_blocks(caller_body);
186         }
187     }
188
189     fn get_valid_function_call(
190         &self,
191         bb: BasicBlock,
192         bb_data: &BasicBlockData<'tcx>,
193         caller_body: &Body<'tcx>,
194     ) -> Option<CallSite<'tcx>> {
195         // Don't inline calls that are in cleanup blocks.
196         if bb_data.is_cleanup {
197             return None;
198         }
199
200         // Only consider direct calls to functions
201         let terminator = bb_data.terminator();
202         if let TerminatorKind::Call { func: ref op, .. } = terminator.kind {
203             if let ty::FnDef(callee_def_id, substs) = *op.ty(caller_body, self.tcx).kind() {
204                 let instance = Instance::resolve(self.tcx, self.param_env, callee_def_id, substs)
205                     .ok()
206                     .flatten()?;
207
208                 if let InstanceDef::Virtual(..) = instance.def {
209                     return None;
210                 }
211
212                 return Some(CallSite {
213                     callee: instance.def_id(),
214                     substs: instance.substs,
215                     bb,
216                     location: terminator.source_info,
217                 });
218             }
219         }
220
221         None
222     }
223
224     fn consider_optimizing(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
225         debug!("consider_optimizing({:?})", callsite);
226         self.should_inline(callsite, callee_body)
227             && self.tcx.consider_optimizing(|| {
228                 format!("Inline {:?} into {:?}", callee_body.span, callsite)
229             })
230     }
231
232     fn should_inline(&self, callsite: CallSite<'tcx>, callee_body: &Body<'tcx>) -> bool {
233         debug!("should_inline({:?})", callsite);
234         let tcx = self.tcx;
235
236         // Cannot inline generators which haven't been transformed yet
237         if callee_body.yield_ty.is_some() {
238             debug!("    yield ty present - not inlining");
239             return false;
240         }
241
242         let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee);
243
244         if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::TRACK_CALLER) {
245             debug!("`#[track_caller]` present - not inlining");
246             return false;
247         }
248
249         let self_features = &self.codegen_fn_attrs.target_features;
250         let callee_features = &codegen_fn_attrs.target_features;
251         if callee_features.iter().any(|feature| !self_features.contains(feature)) {
252             debug!("`callee has extra target features - not inlining");
253             return false;
254         }
255
256         let self_no_sanitize =
257             self.codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
258         let callee_no_sanitize =
259             codegen_fn_attrs.no_sanitize & self.tcx.sess.opts.debugging_opts.sanitizer;
260         if self_no_sanitize != callee_no_sanitize {
261             debug!("`callee has incompatible no_sanitize attribute - not inlining");
262             return false;
263         }
264
265         let hinted = match codegen_fn_attrs.inline {
266             // Just treat inline(always) as a hint for now,
267             // there are cases that prevent inlining that we
268             // need to check for first.
269             attr::InlineAttr::Always => true,
270             attr::InlineAttr::Never => {
271                 debug!("`#[inline(never)]` present - not inlining");
272                 return false;
273             }
274             attr::InlineAttr::Hint => true,
275             attr::InlineAttr::None => false,
276         };
277
278         // Only inline local functions if they would be eligible for cross-crate
279         // inlining. This is to ensure that the final crate doesn't have MIR that
280         // reference unexported symbols
281         if callsite.callee.is_local() {
282             if callsite.substs.non_erasable_generics().count() == 0 && !hinted {
283                 debug!("    callee is an exported function - not inlining");
284                 return false;
285             }
286         }
287
288         let mut threshold = if hinted { HINT_THRESHOLD } else { DEFAULT_THRESHOLD };
289
290         // Significantly lower the threshold for inlining cold functions
291         if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
292             threshold /= 5;
293         }
294
295         // Give a bonus functions with a small number of blocks,
296         // We normally have two or three blocks for even
297         // very small functions.
298         if callee_body.basic_blocks().len() <= 3 {
299             threshold += threshold / 4;
300         }
301         debug!("    final inline threshold = {}", threshold);
302
303         // FIXME: Give a bonus to functions with only a single caller
304         let mut first_block = true;
305         let mut cost = 0;
306
307         // Traverse the MIR manually so we can account for the effects of
308         // inlining on the CFG.
309         let mut work_list = vec![START_BLOCK];
310         let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
311         while let Some(bb) = work_list.pop() {
312             if !visited.insert(bb.index()) {
313                 continue;
314             }
315             let blk = &callee_body.basic_blocks()[bb];
316
317             for stmt in &blk.statements {
318                 // Don't count StorageLive/StorageDead in the inlining cost.
319                 match stmt.kind {
320                     StatementKind::StorageLive(_)
321                     | StatementKind::StorageDead(_)
322                     | StatementKind::Nop => {}
323                     _ => cost += INSTR_COST,
324                 }
325             }
326             let term = blk.terminator();
327             let mut is_drop = false;
328             match term.kind {
329                 TerminatorKind::Drop { ref place, target, unwind }
330                 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
331                     is_drop = true;
332                     work_list.push(target);
333                     // If the place doesn't actually need dropping, treat it like
334                     // a regular goto.
335                     let ty = place.ty(callee_body, tcx).subst(tcx, callsite.substs).ty;
336                     if ty.needs_drop(tcx, self.param_env) {
337                         cost += CALL_PENALTY;
338                         if let Some(unwind) = unwind {
339                             cost += LANDINGPAD_PENALTY;
340                             work_list.push(unwind);
341                         }
342                     } else {
343                         cost += INSTR_COST;
344                     }
345                 }
346
347                 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
348                     if first_block =>
349                 {
350                     // If the function always diverges, don't inline
351                     // unless the cost is zero
352                     threshold = 0;
353                 }
354
355                 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
356                     if let ty::FnDef(def_id, _) = *f.literal.ty.kind() {
357                         // Don't give intrinsics the extra penalty for calls
358                         let f = tcx.fn_sig(def_id);
359                         if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
360                             cost += INSTR_COST;
361                         } else {
362                             cost += CALL_PENALTY;
363                         }
364                     } else {
365                         cost += CALL_PENALTY;
366                     }
367                     if cleanup.is_some() {
368                         cost += LANDINGPAD_PENALTY;
369                     }
370                 }
371                 TerminatorKind::Assert { cleanup, .. } => {
372                     cost += CALL_PENALTY;
373
374                     if cleanup.is_some() {
375                         cost += LANDINGPAD_PENALTY;
376                     }
377                 }
378                 TerminatorKind::Resume => cost += RESUME_PENALTY,
379                 _ => cost += INSTR_COST,
380             }
381
382             if !is_drop {
383                 for &succ in term.successors() {
384                     work_list.push(succ);
385                 }
386             }
387
388             first_block = false;
389         }
390
391         // Count up the cost of local variables and temps, if we know the size
392         // use that, otherwise we use a moderately-large dummy cost.
393
394         let ptr_size = tcx.data_layout.pointer_size.bytes();
395
396         for v in callee_body.vars_and_temps_iter() {
397             let v = &callee_body.local_decls[v];
398             let ty = v.ty.subst(tcx, callsite.substs);
399             // Cost of the var is the size in machine-words, if we know
400             // it.
401             if let Some(size) = type_size_of(tcx, self.param_env, ty) {
402                 cost += (size / ptr_size) as usize;
403             } else {
404                 cost += UNKNOWN_SIZE_COST;
405             }
406         }
407
408         if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
409             debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
410             true
411         } else {
412             if cost <= threshold {
413                 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
414                 true
415             } else {
416                 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
417                 false
418             }
419         }
420     }
421
422     fn inline_call(
423         &self,
424         callsite: CallSite<'tcx>,
425         caller_body: &mut Body<'tcx>,
426         mut callee_body: Body<'tcx>,
427     ) -> bool {
428         let terminator = caller_body[callsite.bb].terminator.take().unwrap();
429         match terminator.kind {
430             // FIXME: Handle inlining of diverging calls
431             TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
432                 debug!("inlined {:?} into {:?}", callsite.callee, caller_body.source);
433
434                 let mut local_map = IndexVec::with_capacity(callee_body.local_decls.len());
435                 let mut scope_map = IndexVec::with_capacity(callee_body.source_scopes.len());
436
437                 for mut scope in callee_body.source_scopes.iter().cloned() {
438                     if scope.parent_scope.is_none() {
439                         scope.parent_scope = Some(callsite.location.scope);
440                         // FIXME(eddyb) is this really needed?
441                         // (also note that it's always overwritten below)
442                         scope.span = callee_body.span;
443                     }
444
445                     // FIXME(eddyb) this doesn't seem right at all.
446                     // The inlined source scopes should probably be annotated as
447                     // such, but also contain all of the original information.
448                     scope.span = callsite.location.span;
449
450                     let idx = caller_body.source_scopes.push(scope);
451                     scope_map.push(idx);
452                 }
453
454                 for loc in callee_body.vars_and_temps_iter() {
455                     let mut local = callee_body.local_decls[loc].clone();
456
457                     local.source_info.scope = scope_map[local.source_info.scope];
458                     local.source_info.span = callsite.location.span;
459
460                     let idx = caller_body.local_decls.push(local);
461                     local_map.push(idx);
462                 }
463
464                 // If the call is something like `a[*i] = f(i)`, where
465                 // `i : &mut usize`, then just duplicating the `a[*i]`
466                 // Place could result in two different locations if `f`
467                 // writes to `i`. To prevent this we need to create a temporary
468                 // borrow of the place and pass the destination as `*temp` instead.
469                 fn dest_needs_borrow(place: Place<'_>) -> bool {
470                     for elem in place.projection.iter() {
471                         match elem {
472                             ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
473                             _ => {}
474                         }
475                     }
476
477                     false
478                 }
479
480                 let dest = if dest_needs_borrow(destination.0) {
481                     debug!("creating temp for return destination");
482                     let dest = Rvalue::Ref(
483                         self.tcx.lifetimes.re_erased,
484                         BorrowKind::Mut { allow_two_phase_borrow: false },
485                         destination.0,
486                     );
487
488                     let ty = dest.ty(caller_body, self.tcx);
489
490                     let temp = LocalDecl::new(ty, callsite.location.span);
491
492                     let tmp = caller_body.local_decls.push(temp);
493                     let tmp = Place::from(tmp);
494
495                     let stmt = Statement {
496                         source_info: callsite.location,
497                         kind: StatementKind::Assign(box (tmp, dest)),
498                     };
499                     caller_body[callsite.bb].statements.push(stmt);
500                     self.tcx.mk_place_deref(tmp)
501                 } else {
502                     destination.0
503                 };
504
505                 let return_block = destination.1;
506
507                 // Copy the arguments if needed.
508                 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, return_block);
509
510                 let bb_len = caller_body.basic_blocks().len();
511                 let mut integrator = Integrator {
512                     block_idx: bb_len,
513                     args: &args,
514                     local_map,
515                     scope_map,
516                     destination: dest,
517                     return_block,
518                     cleanup_block: cleanup,
519                     in_cleanup_block: false,
520                     tcx: self.tcx,
521                 };
522
523                 for mut var_debug_info in callee_body.var_debug_info.drain(..) {
524                     integrator.visit_var_debug_info(&mut var_debug_info);
525                     caller_body.var_debug_info.push(var_debug_info);
526                 }
527
528                 for (bb, mut block) in callee_body.basic_blocks_mut().drain_enumerated(..) {
529                     integrator.visit_basic_block_data(bb, &mut block);
530                     caller_body.basic_blocks_mut().push(block);
531                 }
532
533                 let terminator = Terminator {
534                     source_info: callsite.location,
535                     kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) },
536                 };
537
538                 caller_body[callsite.bb].terminator = Some(terminator);
539
540                 true
541             }
542             kind => {
543                 caller_body[callsite.bb].terminator =
544                     Some(Terminator { source_info: terminator.source_info, kind });
545                 false
546             }
547         }
548     }
549
550     fn make_call_args(
551         &self,
552         args: Vec<Operand<'tcx>>,
553         callsite: &CallSite<'tcx>,
554         caller_body: &mut Body<'tcx>,
555         return_block: BasicBlock,
556     ) -> Vec<Local> {
557         let tcx = self.tcx;
558
559         // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
560         // The caller provides the arguments wrapped up in a tuple:
561         //
562         //     tuple_tmp = (a, b, c)
563         //     Fn::call(closure_ref, tuple_tmp)
564         //
565         // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
566         // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
567         // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
568         // a vector like
569         //
570         //     [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
571         //
572         // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
573         // if we "spill" that into *another* temporary, so that we can map the argument
574         // variable in the callee MIR directly to an argument variable on our side.
575         // So we introduce temporaries like:
576         //
577         //     tmp0 = tuple_tmp.0
578         //     tmp1 = tuple_tmp.1
579         //     tmp2 = tuple_tmp.2
580         //
581         // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
582         if tcx.is_closure(callsite.callee) {
583             let mut args = args.into_iter();
584             let self_ = self.create_temp_if_necessary(
585                 args.next().unwrap(),
586                 callsite,
587                 caller_body,
588                 return_block,
589             );
590             let tuple = self.create_temp_if_necessary(
591                 args.next().unwrap(),
592                 callsite,
593                 caller_body,
594                 return_block,
595             );
596             assert!(args.next().is_none());
597
598             let tuple = Place::from(tuple);
599             let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
600                 s
601             } else {
602                 bug!("Closure arguments are not passed as a tuple");
603             };
604
605             // The `closure_ref` in our example above.
606             let closure_ref_arg = iter::once(self_);
607
608             // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
609             let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
610                 // This is e.g., `tuple_tmp.0` in our example above.
611                 let tuple_field =
612                     Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
613
614                 // Spill to a local to make e.g., `tmp0`.
615                 self.create_temp_if_necessary(tuple_field, callsite, caller_body, return_block)
616             });
617
618             closure_ref_arg.chain(tuple_tmp_args).collect()
619         } else {
620             args.into_iter()
621                 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body, return_block))
622                 .collect()
623         }
624     }
625
626     /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
627     /// temporary `T` and an instruction `T = arg`, and returns `T`.
628     fn create_temp_if_necessary(
629         &self,
630         arg: Operand<'tcx>,
631         callsite: &CallSite<'tcx>,
632         caller_body: &mut Body<'tcx>,
633         return_block: BasicBlock,
634     ) -> Local {
635         // FIXME: Analysis of the usage of the arguments to avoid
636         // unnecessary temporaries.
637
638         if let Operand::Move(place) = &arg {
639             if let Some(local) = place.as_local() {
640                 if caller_body.local_kind(local) == LocalKind::Temp {
641                     // Reuse the operand if it's a temporary already
642                     return local;
643                 }
644             }
645         }
646
647         debug!("creating temp for argument {:?}", arg);
648         // Otherwise, create a temporary for the arg
649         let arg = Rvalue::Use(arg);
650
651         let ty = arg.ty(caller_body, self.tcx);
652
653         let arg_tmp = LocalDecl::new(ty, callsite.location.span);
654         let arg_tmp = caller_body.local_decls.push(arg_tmp);
655
656         caller_body[callsite.bb].statements.push(Statement {
657             source_info: callsite.location,
658             kind: StatementKind::StorageLive(arg_tmp),
659         });
660         caller_body[callsite.bb].statements.push(Statement {
661             source_info: callsite.location,
662             kind: StatementKind::Assign(box (Place::from(arg_tmp), arg)),
663         });
664         caller_body[return_block].statements.insert(
665             0,
666             Statement { source_info: callsite.location, kind: StatementKind::StorageDead(arg_tmp) },
667         );
668
669         arg_tmp
670     }
671 }
672
673 fn type_size_of<'tcx>(
674     tcx: TyCtxt<'tcx>,
675     param_env: ty::ParamEnv<'tcx>,
676     ty: Ty<'tcx>,
677 ) -> Option<u64> {
678     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
679 }
680
681 /**
682  * Integrator.
683  *
684  * Integrates blocks from the callee function into the calling function.
685  * Updates block indices, references to locals and other control flow
686  * stuff.
687 */
688 struct Integrator<'a, 'tcx> {
689     block_idx: usize,
690     args: &'a [Local],
691     local_map: IndexVec<Local, Local>,
692     scope_map: IndexVec<SourceScope, SourceScope>,
693     destination: Place<'tcx>,
694     return_block: BasicBlock,
695     cleanup_block: Option<BasicBlock>,
696     in_cleanup_block: bool,
697     tcx: TyCtxt<'tcx>,
698 }
699
700 impl<'a, 'tcx> Integrator<'a, 'tcx> {
701     fn update_target(&self, tgt: BasicBlock) -> BasicBlock {
702         let new = BasicBlock::new(tgt.index() + self.block_idx);
703         debug!("updating target `{:?}`, new: `{:?}`", tgt, new);
704         new
705     }
706
707     fn make_integrate_local(&self, local: Local) -> Local {
708         if local == RETURN_PLACE {
709             return self.destination.local;
710         }
711
712         let idx = local.index() - 1;
713         if idx < self.args.len() {
714             return self.args[idx];
715         }
716
717         self.local_map[Local::new(idx - self.args.len())]
718     }
719 }
720
721 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
722     fn tcx(&self) -> TyCtxt<'tcx> {
723         self.tcx
724     }
725
726     fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
727         *local = self.make_integrate_local(*local);
728     }
729
730     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
731         // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
732         let dest_proj_len = self.destination.projection.len();
733         if place.local == RETURN_PLACE && dest_proj_len > 0 {
734             let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
735             projs.extend(self.destination.projection);
736             projs.extend(place.projection);
737
738             place.projection = self.tcx.intern_place_elems(&*projs);
739         }
740         // Handles integrating any locals that occur in the base
741         // or projections
742         self.super_place(place, context, location)
743     }
744
745     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
746         self.in_cleanup_block = data.is_cleanup;
747         self.super_basic_block_data(block, data);
748         self.in_cleanup_block = false;
749     }
750
751     fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
752         self.super_retag(kind, place, loc);
753
754         // We have to patch all inlined retags to be aware that they are no longer
755         // happening on function entry.
756         if *kind == RetagKind::FnEntry {
757             *kind = RetagKind::Default;
758         }
759     }
760
761     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
762         // Don't try to modify the implicit `_0` access on return (`return` terminators are
763         // replaced down below anyways).
764         if !matches!(terminator.kind, TerminatorKind::Return) {
765             self.super_terminator(terminator, loc);
766         }
767
768         match terminator.kind {
769             TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
770             TerminatorKind::Goto { ref mut target } => {
771                 *target = self.update_target(*target);
772             }
773             TerminatorKind::SwitchInt { ref mut targets, .. } => {
774                 for tgt in targets.all_targets_mut() {
775                     *tgt = self.update_target(*tgt);
776                 }
777             }
778             TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
779             | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
780                 *target = self.update_target(*target);
781                 if let Some(tgt) = *unwind {
782                     *unwind = Some(self.update_target(tgt));
783                 } else if !self.in_cleanup_block {
784                     // Unless this drop is in a cleanup block, add an unwind edge to
785                     // the original call's cleanup block
786                     *unwind = self.cleanup_block;
787                 }
788             }
789             TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
790                 if let Some((_, ref mut tgt)) = *destination {
791                     *tgt = self.update_target(*tgt);
792                 }
793                 if let Some(tgt) = *cleanup {
794                     *cleanup = Some(self.update_target(tgt));
795                 } else if !self.in_cleanup_block {
796                     // Unless this call is in a cleanup block, add an unwind edge to
797                     // the original call's cleanup block
798                     *cleanup = self.cleanup_block;
799                 }
800             }
801             TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
802                 *target = self.update_target(*target);
803                 if let Some(tgt) = *cleanup {
804                     *cleanup = Some(self.update_target(tgt));
805                 } else if !self.in_cleanup_block {
806                     // Unless this assert is in a cleanup block, add an unwind edge to
807                     // the original call's cleanup block
808                     *cleanup = self.cleanup_block;
809                 }
810             }
811             TerminatorKind::Return => {
812                 terminator.kind = TerminatorKind::Goto { target: self.return_block };
813             }
814             TerminatorKind::Resume => {
815                 if let Some(tgt) = self.cleanup_block {
816                     terminator.kind = TerminatorKind::Goto { target: tgt }
817                 }
818             }
819             TerminatorKind::Abort => {}
820             TerminatorKind::Unreachable => {}
821             TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
822                 *real_target = self.update_target(*real_target);
823                 *imaginary_target = self.update_target(*imaginary_target);
824             }
825             TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
826             // see the ordering of passes in the optimized_mir query.
827             {
828                 bug!("False unwinds should have been removed before inlining")
829             }
830             TerminatorKind::InlineAsm { ref mut destination, .. } => {
831                 if let Some(ref mut tgt) = *destination {
832                     *tgt = self.update_target(*tgt);
833                 }
834             }
835         }
836     }
837
838     fn visit_source_scope(&mut self, scope: &mut SourceScope) {
839         *scope = self.scope_map[*scope];
840     }
841 }