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