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