1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Inlining pass for MIR functions
14 use rustc::hir::CodegenFnAttrFlags;
15 use rustc::hir::def_id::DefId;
17 use rustc_data_structures::bitvec::BitVector;
18 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
21 use rustc::mir::visit::*;
22 use rustc::ty::{self, Instance, Ty, TyCtxt};
23 use rustc::ty::subst::{Subst,Substs};
25 use std::collections::VecDeque;
27 use transform::{MirPass, MirSource};
28 use super::simplify::{remove_dead_blocks, CfgSimplifier};
31 use rustc_target::spec::abi::Abi;
33 const DEFAULT_THRESHOLD: usize = 50;
34 const HINT_THRESHOLD: usize = 100;
36 const INSTR_COST: usize = 5;
37 const CALL_PENALTY: usize = 25;
39 const UNKNOWN_SIZE_COST: usize = 10;
43 #[derive(Copy, Clone, Debug)]
44 struct CallSite<'tcx> {
46 substs: &'tcx Substs<'tcx>,
51 impl MirPass for Inline {
52 fn run_pass<'a, 'tcx>(&self,
53 tcx: TyCtxt<'a, 'tcx, 'tcx>,
55 mir: &mut Mir<'tcx>) {
56 if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
57 Inliner { tcx, source }.run_pass(mir);
62 struct Inliner<'a, 'tcx: 'a> {
63 tcx: TyCtxt<'a, 'tcx, 'tcx>,
67 impl<'a, 'tcx> Inliner<'a, 'tcx> {
68 fn run_pass(&self, caller_mir: &mut Mir<'tcx>) {
69 // Keep a queue of callsites to try inlining on. We take
70 // advantage of the fact that queries detect cycles here to
71 // allow us to try and fetch the fully optimized MIR of a
72 // call; if it succeeds, we can inline it and we know that
73 // they do not call us. Otherwise, we just don't try to
76 // We use a queue so that we inline "broadly" before we inline
77 // in depth. It is unclear if this is the best heuristic,
78 // really, but that's true of all the heuristics in this
81 let mut callsites = VecDeque::new();
83 let param_env = self.tcx.param_env(self.source.def_id);
85 // Only do inlining into fn bodies.
86 let id = self.tcx.hir.as_local_node_id(self.source.def_id).unwrap();
87 let body_owner_kind = self.tcx.hir.body_owner_kind(id);
88 if let (hir::BodyOwnerKind::Fn, None) = (body_owner_kind, self.source.promoted) {
90 for (bb, bb_data) in caller_mir.basic_blocks().iter_enumerated() {
91 // Don't inline calls that are in cleanup blocks.
92 if bb_data.is_cleanup { continue; }
94 // Only consider direct calls to functions
95 let terminator = bb_data.terminator();
96 if let TerminatorKind::Call {
97 func: Operand::Constant(ref f), .. } = terminator.kind {
98 if let ty::TyFnDef(callee_def_id, substs) = f.ty.sty {
99 if let Some(instance) = Instance::resolve(self.tcx,
103 callsites.push_back(CallSite {
104 callee: instance.def_id(),
105 substs: instance.substs,
107 location: terminator.source_info
117 let mut local_change;
118 let mut changed = false;
121 local_change = false;
122 while let Some(callsite) = callsites.pop_front() {
123 debug!("checking whether to inline callsite {:?}", callsite);
124 if !self.tcx.is_mir_available(callsite.callee) {
125 debug!("checking whether to inline callsite {:?} - MIR unavailable", callsite);
129 let callee_mir = match self.tcx.try_optimized_mir(callsite.location.span,
131 Ok(callee_mir) if self.should_inline(callsite, callee_mir) => {
132 self.tcx.subst_and_normalize_erasing_regions(
141 // FIXME(#43542) shouldn't have to cancel an error
147 let start = caller_mir.basic_blocks().len();
148 debug!("attempting to inline callsite {:?} - mir={:?}", callsite, callee_mir);
149 if !self.inline_call(callsite, caller_mir, callee_mir) {
150 debug!("attempting to inline callsite {:?} - failure", callsite);
153 debug!("attempting to inline callsite {:?} - success", callsite);
155 // Add callsites from inlined function
156 for (bb, bb_data) in caller_mir.basic_blocks().iter_enumerated().skip(start) {
157 // Only consider direct calls to functions
158 let terminator = bb_data.terminator();
159 if let TerminatorKind::Call {
160 func: Operand::Constant(ref f), .. } = terminator.kind {
161 if let ty::TyFnDef(callee_def_id, substs) = f.ty.sty {
162 // Don't inline the same function multiple times.
163 if callsite.callee != callee_def_id {
164 callsites.push_back(CallSite {
165 callee: callee_def_id,
168 location: terminator.source_info
184 // Simplify if we inlined anything.
186 debug!("Running simplify cfg on {:?}", self.source);
187 CfgSimplifier::new(caller_mir).simplify();
188 remove_dead_blocks(caller_mir);
192 fn should_inline(&self,
193 callsite: CallSite<'tcx>,
194 callee_mir: &Mir<'tcx>)
197 debug!("should_inline({:?})", callsite);
200 // Don't inline closures that have captures
201 // FIXME: Handle closures better
202 if callee_mir.upvar_decls.len() > 0 {
203 debug!(" upvar decls present - not inlining");
207 // Cannot inline generators which haven't been transformed yet
208 if callee_mir.yield_ty.is_some() {
209 debug!(" yield ty present - not inlining");
213 // Do not inline {u,i}128 lang items, codegen const eval depends
214 // on detecting calls to these lang items and intercepting them
215 if tcx.is_binop_lang_item(callsite.callee).is_some() {
216 debug!(" not inlining 128bit integer lang item");
220 let codegen_fn_attrs = tcx.codegen_fn_attrs(callsite.callee);
222 let hinted = match codegen_fn_attrs.inline {
223 // Just treat inline(always) as a hint for now,
224 // there are cases that prevent inlining that we
225 // need to check for first.
226 attr::InlineAttr::Always => true,
227 attr::InlineAttr::Never => {
228 debug!("#[inline(never)] present - not inlining");
231 attr::InlineAttr::Hint => true,
232 attr::InlineAttr::None => false,
235 // Only inline local functions if they would be eligible for cross-crate
236 // inlining. This is to ensure that the final crate doesn't have MIR that
237 // reference unexported symbols
238 if callsite.callee.is_local() {
239 if callsite.substs.types().count() == 0 && !hinted {
240 debug!(" callee is an exported function - not inlining");
245 let mut threshold = if hinted {
251 // Significantly lower the threshold for inlining cold functions
252 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
256 // Give a bonus functions with a small number of blocks,
257 // We normally have two or three blocks for even
258 // very small functions.
259 if callee_mir.basic_blocks().len() <= 3 {
260 threshold += threshold / 4;
262 debug!(" final inline threshold = {}", threshold);
264 // FIXME: Give a bonus to functions with only a single caller
266 let param_env = tcx.param_env(self.source.def_id);
268 let mut first_block = true;
271 // Traverse the MIR manually so we can account for the effects of
272 // inlining on the CFG.
273 let mut work_list = vec![START_BLOCK];
274 let mut visited = BitVector::new(callee_mir.basic_blocks().len());
275 while let Some(bb) = work_list.pop() {
276 if !visited.insert(bb.index()) { continue; }
277 let blk = &callee_mir.basic_blocks()[bb];
279 for stmt in &blk.statements {
280 // Don't count StorageLive/StorageDead in the inlining cost.
282 StatementKind::StorageLive(_) |
283 StatementKind::StorageDead(_) |
284 StatementKind::Nop => {}
285 _ => cost += INSTR_COST
288 let term = blk.terminator();
289 let mut is_drop = false;
291 TerminatorKind::Drop { ref location, target, unwind } |
292 TerminatorKind::DropAndReplace { ref location, target, unwind, .. } => {
294 work_list.push(target);
295 // If the location doesn't actually need dropping, treat it like
297 let ty = location.ty(callee_mir, tcx).subst(tcx, callsite.substs);
298 let ty = ty.to_ty(tcx);
299 if ty.needs_drop(tcx, param_env) {
300 cost += CALL_PENALTY;
301 if let Some(unwind) = unwind {
302 work_list.push(unwind);
309 TerminatorKind::Unreachable |
310 TerminatorKind::Call { destination: None, .. } if first_block => {
311 // If the function always diverges, don't inline
312 // unless the cost is zero
316 TerminatorKind::Call {func: Operand::Constant(ref f), .. } => {
317 if let ty::TyFnDef(def_id, _) = f.ty.sty {
318 // Don't give intrinsics the extra penalty for calls
319 let f = tcx.fn_sig(def_id);
320 if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
323 cost += CALL_PENALTY;
327 TerminatorKind::Assert { .. } => cost += CALL_PENALTY,
328 _ => cost += INSTR_COST
332 for &succ in term.successors() {
333 work_list.push(succ);
340 // Count up the cost of local variables and temps, if we know the size
341 // use that, otherwise we use a moderately-large dummy cost.
343 let ptr_size = tcx.data_layout.pointer_size.bytes();
345 for v in callee_mir.vars_and_temps_iter() {
346 let v = &callee_mir.local_decls[v];
347 let ty = v.ty.subst(tcx, callsite.substs);
348 // Cost of the var is the size in machine-words, if we know
350 if let Some(size) = type_size_of(tcx, param_env.clone(), ty) {
351 cost += (size / ptr_size) as usize;
353 cost += UNKNOWN_SIZE_COST;
357 if let attr::InlineAttr::Always = codegen_fn_attrs.inline {
358 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
361 if cost <= threshold {
362 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
365 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
371 fn inline_call(&self,
372 callsite: CallSite<'tcx>,
373 caller_mir: &mut Mir<'tcx>,
374 mut callee_mir: Mir<'tcx>) -> bool {
375 let terminator = caller_mir[callsite.bb].terminator.take().unwrap();
376 match terminator.kind {
377 // FIXME: Handle inlining of diverging calls
378 TerminatorKind::Call { args, destination: Some(destination), cleanup, .. } => {
379 debug!("Inlined {:?} into {:?}", callsite.callee, self.source);
381 let mut local_map = IndexVec::with_capacity(callee_mir.local_decls.len());
382 let mut scope_map = IndexVec::with_capacity(callee_mir.source_scopes.len());
383 let mut promoted_map = IndexVec::with_capacity(callee_mir.promoted.len());
385 for mut scope in callee_mir.source_scopes.iter().cloned() {
386 if scope.parent_scope.is_none() {
387 scope.parent_scope = Some(callsite.location.scope);
388 scope.span = callee_mir.span;
391 scope.span = callsite.location.span;
393 let idx = caller_mir.source_scopes.push(scope);
397 for loc in callee_mir.vars_and_temps_iter() {
398 let mut local = callee_mir.local_decls[loc].clone();
400 local.source_info.scope =
401 scope_map[local.source_info.scope];
402 local.source_info.span = callsite.location.span;
403 local.visibility_scope = scope_map[local.visibility_scope];
405 let idx = caller_mir.local_decls.push(local);
410 callee_mir.promoted.iter().cloned().map(|p| caller_mir.promoted.push(p))
413 // If the call is something like `a[*i] = f(i)`, where
414 // `i : &mut usize`, then just duplicating the `a[*i]`
415 // Place could result in two different locations if `f`
416 // writes to `i`. To prevent this we need to create a temporary
417 // borrow of the place and pass the destination as `*temp` instead.
418 fn dest_needs_borrow(place: &Place) -> bool {
420 Place::Projection(ref p) => {
422 ProjectionElem::Deref |
423 ProjectionElem::Index(_) => true,
424 _ => dest_needs_borrow(&p.base)
427 // Static variables need a borrow because the callee
428 // might modify the same static.
429 Place::Static(_) => true,
434 let dest = if dest_needs_borrow(&destination.0) {
435 debug!("Creating temp for return destination");
436 let dest = Rvalue::Ref(
437 self.tcx.types.re_erased,
438 BorrowKind::Mut { allow_two_phase_borrow: false },
441 let ty = dest.ty(caller_mir, self.tcx);
443 let temp = LocalDecl::new_temp(ty, callsite.location.span);
445 let tmp = caller_mir.local_decls.push(temp);
446 let tmp = Place::Local(tmp);
448 let stmt = Statement {
449 source_info: callsite.location,
450 kind: StatementKind::Assign(tmp.clone(), dest)
452 caller_mir[callsite.bb]
453 .statements.push(stmt);
459 let return_block = destination.1;
461 // Copy the arguments if needed.
462 let args: Vec<_> = self.make_call_args(args, &callsite, caller_mir);
464 let bb_len = caller_mir.basic_blocks().len();
465 let mut integrator = Integrator {
474 cleanup_block: cleanup,
475 in_cleanup_block: false
479 for (bb, mut block) in callee_mir.basic_blocks_mut().drain_enumerated(..) {
480 integrator.visit_basic_block_data(bb, &mut block);
481 caller_mir.basic_blocks_mut().push(block);
484 let terminator = Terminator {
485 source_info: callsite.location,
486 kind: TerminatorKind::Goto { target: BasicBlock::new(bb_len) }
489 caller_mir[callsite.bb].terminator = Some(terminator);
494 caller_mir[callsite.bb].terminator = Some(Terminator {
495 source_info: terminator.source_info,
505 args: Vec<Operand<'tcx>>,
506 callsite: &CallSite<'tcx>,
507 caller_mir: &mut Mir<'tcx>,
511 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
512 // The caller provides the arguments wrapped up in a tuple:
514 // tuple_tmp = (a, b, c)
515 // Fn::call(closure_ref, tuple_tmp)
517 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
518 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
519 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
522 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
524 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
525 // if we "spill" that into *another* temporary, so that we can map the argument
526 // variable in the callee MIR directly to an argument variable on our side.
527 // So we introduce temporaries like:
529 // tmp0 = tuple_tmp.0
530 // tmp1 = tuple_tmp.1
531 // tmp2 = tuple_tmp.2
533 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
534 if tcx.is_closure(callsite.callee) {
535 let mut args = args.into_iter();
536 let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_mir);
537 let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_mir);
538 assert!(args.next().is_none());
540 let tuple = Place::Local(tuple);
541 let tuple_tys = if let ty::TyTuple(s) = tuple.ty(caller_mir, tcx).to_ty(tcx).sty {
544 bug!("Closure arguments are not passed as a tuple");
547 // The `closure_ref` in our example above.
548 let closure_ref_arg = iter::once(self_);
550 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
552 tuple_tys.iter().enumerate().map(|(i, ty)| {
553 // This is e.g. `tuple_tmp.0` in our example above.
554 let tuple_field = Operand::Move(tuple.clone().field(Field::new(i), ty));
556 // Spill to a local to make e.g. `tmp0`.
557 self.create_temp_if_necessary(tuple_field, callsite, caller_mir)
560 closure_ref_arg.chain(tuple_tmp_args).collect()
563 .map(|a| self.create_temp_if_necessary(a, callsite, caller_mir))
568 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
569 /// temporary `T` and an instruction `T = arg`, and returns `T`.
570 fn create_temp_if_necessary(
573 callsite: &CallSite<'tcx>,
574 caller_mir: &mut Mir<'tcx>,
576 // FIXME: Analysis of the usage of the arguments to avoid
577 // unnecessary temporaries.
579 if let Operand::Move(Place::Local(local)) = arg {
580 if caller_mir.local_kind(local) == LocalKind::Temp {
581 // Reuse the operand if it's a temporary already
586 debug!("Creating temp for argument {:?}", arg);
587 // Otherwise, create a temporary for the arg
588 let arg = Rvalue::Use(arg);
590 let ty = arg.ty(caller_mir, self.tcx);
592 let arg_tmp = LocalDecl::new_temp(ty, callsite.location.span);
593 let arg_tmp = caller_mir.local_decls.push(arg_tmp);
595 let stmt = Statement {
596 source_info: callsite.location,
597 kind: StatementKind::Assign(Place::Local(arg_tmp), arg),
599 caller_mir[callsite.bb].statements.push(stmt);
604 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
605 param_env: ty::ParamEnv<'tcx>,
606 ty: Ty<'tcx>) -> Option<u64> {
607 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
613 * Integrates blocks from the callee function into the calling function.
614 * Updates block indices, references to locals and other control flow
617 struct Integrator<'a, 'tcx: 'a> {
620 local_map: IndexVec<Local, Local>,
621 scope_map: IndexVec<SourceScope, SourceScope>,
622 promoted_map: IndexVec<Promoted, Promoted>,
623 _callsite: CallSite<'tcx>,
624 destination: Place<'tcx>,
625 return_block: BasicBlock,
626 cleanup_block: Option<BasicBlock>,
627 in_cleanup_block: bool,
630 impl<'a, 'tcx> Integrator<'a, 'tcx> {
631 fn update_target(&self, tgt: BasicBlock) -> BasicBlock {
632 let new = BasicBlock::new(tgt.index() + self.block_idx);
633 debug!("Updating target `{:?}`, new: `{:?}`", tgt, new);
638 impl<'a, 'tcx> MutVisitor<'tcx> for Integrator<'a, 'tcx> {
639 fn visit_local(&mut self,
641 _ctxt: PlaceContext<'tcx>,
642 _location: Location) {
643 if *local == RETURN_PLACE {
644 match self.destination {
649 ref place => bug!("Return place is {:?}, not local", place)
652 let idx = local.index() - 1;
653 if idx < self.args.len() {
654 *local = self.args[idx];
657 *local = self.local_map[Local::new(idx - self.args.len())];
660 fn visit_place(&mut self,
661 place: &mut Place<'tcx>,
662 _ctxt: PlaceContext<'tcx>,
663 _location: Location) {
666 Place::Local(RETURN_PLACE) => {
667 // Return pointer; update the place itself
668 *place = self.destination.clone();
670 Place::Promoted(ref mut promoted) => {
671 if let Some(p) = self.promoted_map.get(promoted.0).cloned() {
675 _ => self.super_place(place, _ctxt, _location),
679 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
680 self.in_cleanup_block = data.is_cleanup;
681 self.super_basic_block_data(block, data);
682 self.in_cleanup_block = false;
685 fn visit_terminator_kind(&mut self, block: BasicBlock,
686 kind: &mut TerminatorKind<'tcx>, loc: Location) {
687 self.super_terminator_kind(block, kind, loc);
690 TerminatorKind::GeneratorDrop |
691 TerminatorKind::Yield { .. } => bug!(),
692 TerminatorKind::Goto { ref mut target} => {
693 *target = self.update_target(*target);
695 TerminatorKind::SwitchInt { ref mut targets, .. } => {
697 *tgt = self.update_target(*tgt);
700 TerminatorKind::Drop { ref mut target, ref mut unwind, .. } |
701 TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
702 *target = self.update_target(*target);
703 if let Some(tgt) = *unwind {
704 *unwind = Some(self.update_target(tgt));
705 } else if !self.in_cleanup_block {
706 // Unless this drop is in a cleanup block, add an unwind edge to
707 // the orignal call's cleanup block
708 *unwind = self.cleanup_block;
711 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
712 if let Some((_, ref mut tgt)) = *destination {
713 *tgt = self.update_target(*tgt);
715 if let Some(tgt) = *cleanup {
716 *cleanup = Some(self.update_target(tgt));
717 } else if !self.in_cleanup_block {
718 // Unless this call is in a cleanup block, add an unwind edge to
719 // the orignal call's cleanup block
720 *cleanup = self.cleanup_block;
723 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
724 *target = self.update_target(*target);
725 if let Some(tgt) = *cleanup {
726 *cleanup = Some(self.update_target(tgt));
727 } else if !self.in_cleanup_block {
728 // Unless this assert is in a cleanup block, add an unwind edge to
729 // the orignal call's cleanup block
730 *cleanup = self.cleanup_block;
733 TerminatorKind::Return => {
734 *kind = TerminatorKind::Goto { target: self.return_block };
736 TerminatorKind::Resume => {
737 if let Some(tgt) = self.cleanup_block {
738 *kind = TerminatorKind::Goto { target: tgt }
741 TerminatorKind::Abort => { }
742 TerminatorKind::Unreachable => { }
743 TerminatorKind::FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
744 *real_target = self.update_target(*real_target);
745 for target in imaginary_targets {
746 *target = self.update_target(*target);
749 TerminatorKind::FalseUnwind { real_target: _ , unwind: _ } =>
750 // see the ordering of passes in the optimized_mir query.
751 bug!("False unwinds should have been removed before inlining")
755 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
756 *scope = self.scope_map[*scope];