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