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