1 //! Inlining pass for MIR functions
3 use rustc_attr::InlineAttr;
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::traits::ObligationCause;
11 use rustc_middle::ty::subst::Subst;
12 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
13 use rustc_span::{hygiene::ExpnKind, ExpnData, Span};
14 use rustc_target::spec::abi::Abi;
16 use super::simplify::{remove_dead_blocks, CfgSimplifier};
19 use std::ops::{Range, RangeFrom};
23 const INSTR_COST: usize = 5;
24 const CALL_PENALTY: usize = 25;
25 const LANDINGPAD_PENALTY: usize = 50;
26 const RESUME_PENALTY: usize = 45;
28 const UNKNOWN_SIZE_COST: usize = 10;
32 #[derive(Copy, Clone, Debug)]
33 struct CallSite<'tcx> {
34 callee: Instance<'tcx>,
35 fn_sig: ty::PolyFnSig<'tcx>,
37 target: Option<BasicBlock>,
38 source_info: SourceInfo,
41 impl<'tcx> MirPass<'tcx> for Inline {
42 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
43 if let Some(enabled) = sess.opts.debugging_opts.inline_mir {
47 sess.opts.mir_opt_level() >= 3
50 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
51 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
52 let _guard = span.enter();
53 if inline(tcx, body) {
54 debug!("running simplify cfg on {:?}", body.source);
55 CfgSimplifier::new(body).simplify();
56 remove_dead_blocks(tcx, body);
61 fn inline<'tcx>(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());
65 // Only do inlining into fn bodies.
66 if !tcx.hir().body_owner_kind(hir_id).is_fn_or_closure() {
69 if body.source.promoted.is_some() {
72 // Avoid inlining into generators, since their `optimized_mir` is used for layout computation,
73 // which can create a cycle, even when no attempt is made to inline the function in the other
75 if body.generator.is_some() {
79 let param_env = tcx.param_env_reveal_all_normalized(def_id);
80 let param_env = rustc_trait_selection::traits::normalize_param_env_or_error(
84 ObligationCause::misc(body.span, hir_id),
87 let mut this = Inliner {
90 codegen_fn_attrs: tcx.codegen_fn_attrs(def_id),
95 let blocks = BasicBlock::new(0)..body.basic_blocks().next_index();
96 this.process_blocks(body, blocks);
100 struct Inliner<'tcx> {
102 param_env: ParamEnv<'tcx>,
103 /// Caller codegen attributes.
104 codegen_fn_attrs: &'tcx CodegenFnAttrs,
107 /// Stack of inlined Instances.
108 history: Vec<ty::Instance<'tcx>>,
109 /// Indicates that the caller body has been modified.
113 impl<'tcx> Inliner<'tcx> {
114 fn process_blocks(&mut self, caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>) {
116 let bb_data = &caller_body[bb];
117 if bb_data.is_cleanup {
121 let Some(callsite) = self.resolve_callsite(caller_body, bb, bb_data) else {
125 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
126 let _guard = span.enter();
128 match self.try_inlining(caller_body, &callsite) {
130 debug!("not-inlined {} [{}]", callsite.callee, reason);
134 debug!("inlined {}", callsite.callee);
136 self.history.push(callsite.callee);
137 self.process_blocks(caller_body, new_blocks);
144 /// Attempts to inline a callsite into the caller body. When successful returns basic blocks
145 /// containing the inlined body. Otherwise returns an error describing why inlining didn't take
149 caller_body: &mut Body<'tcx>,
150 callsite: &CallSite<'tcx>,
151 ) -> Result<std::ops::Range<BasicBlock>, &'static str> {
152 let callee_attrs = self.tcx.codegen_fn_attrs(callsite.callee.def_id());
153 self.check_codegen_attributes(callsite, callee_attrs)?;
154 self.check_mir_is_available(caller_body, &callsite.callee)?;
155 let callee_body = self.tcx.instance_mir(callsite.callee.def);
156 self.check_mir_body(callsite, callee_body, callee_attrs)?;
158 if !self.tcx.consider_optimizing(|| {
159 format!("Inline {:?} into {:?}", callsite.callee, caller_body.source)
161 return Err("optimization fuel exhausted");
164 let callee_body = callsite.callee.subst_mir_and_normalize_erasing_regions(
170 let old_blocks = caller_body.basic_blocks().next_index();
171 self.inline_call(caller_body, &callsite, callee_body);
172 let new_blocks = old_blocks..caller_body.basic_blocks().next_index();
177 fn check_mir_is_available(
179 caller_body: &Body<'tcx>,
180 callee: &Instance<'tcx>,
181 ) -> Result<(), &'static str> {
182 if callee.def_id() == caller_body.source.def_id() {
183 return Err("self-recursion");
187 InstanceDef::Item(_) => {
188 // If there is no MIR available (either because it was not in metadata or
189 // because it has no MIR because it's an extern function), then the inliner
190 // won't cause cycles on this.
191 if !self.tcx.is_mir_available(callee.def_id()) {
192 return Err("item MIR unavailable");
195 // These have no own callable MIR.
196 InstanceDef::Intrinsic(_) | InstanceDef::Virtual(..) => {
197 return Err("instance without MIR (intrinsic / virtual)");
199 // This cannot result in an immediate cycle since the callee MIR is a shim, which does
200 // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
201 // do not need to catch this here, we can wait until the inliner decides to continue
202 // inlining a second time.
203 InstanceDef::VtableShim(_)
204 | InstanceDef::ReifyShim(_)
205 | InstanceDef::FnPtrShim(..)
206 | InstanceDef::ClosureOnceShim { .. }
207 | InstanceDef::DropGlue(..)
208 | InstanceDef::CloneShim(..) => return Ok(()),
211 if self.tcx.is_constructor(callee.def_id()) {
212 trace!("constructors always have MIR");
213 // Constructor functions cannot cause a query cycle.
217 if let Some(callee_def_id) = callee.def_id().as_local() {
218 let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
219 // Avoid a cycle here by only using `instance_mir` only if we have
220 // a lower `HirId` than the callee. This ensures that the callee will
221 // not inline us. This trick only works without incremental compilation.
222 // So don't do it if that is enabled.
223 if !self.tcx.dep_graph.is_fully_enabled() && self.hir_id.index() < callee_hir_id.index()
228 // If we know for sure that the function we're calling will itself try to
229 // call us, then we avoid inlining that function.
232 .mir_callgraph_reachable((*callee, caller_body.source.def_id().expect_local()))
234 return Err("caller might be reachable from callee (query cycle avoidance)");
239 // This cannot result in an immediate cycle since the callee MIR is from another crate
240 // and is already optimized. Any subsequent inlining may cause cycles, but we do
241 // not need to catch this here, we can wait until the inliner decides to continue
242 // inlining a second time.
243 trace!("functions from other crates always have MIR");
250 caller_body: &Body<'tcx>,
252 bb_data: &BasicBlockData<'tcx>,
253 ) -> Option<CallSite<'tcx>> {
254 // Only consider direct calls to functions
255 let terminator = bb_data.terminator();
256 if let TerminatorKind::Call { ref func, ref destination, .. } = terminator.kind {
257 let func_ty = func.ty(caller_body, self.tcx);
258 if let ty::FnDef(def_id, substs) = *func_ty.kind() {
259 // To resolve an instance its substs have to be fully normalized.
260 let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
262 Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?;
264 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
268 let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
270 return Some(CallSite {
274 target: destination.map(|(_, target)| target),
275 source_info: terminator.source_info,
283 /// Returns an error if inlining is not possible based on codegen attributes alone. A success
284 /// indicates that inlining decision should be based on other criteria.
285 fn check_codegen_attributes(
287 callsite: &CallSite<'tcx>,
288 callee_attrs: &CodegenFnAttrs,
289 ) -> Result<(), &'static str> {
290 if let InlineAttr::Never = callee_attrs.inline {
291 return Err("never inline hint");
294 // Only inline local functions if they would be eligible for cross-crate
295 // inlining. This is to ensure that the final crate doesn't have MIR that
296 // reference unexported symbols
297 if callsite.callee.def_id().is_local() {
298 let is_generic = callsite.callee.substs.non_erasable_generics().next().is_some();
299 if !is_generic && !callee_attrs.requests_inline() {
300 return Err("not exported");
304 if callsite.fn_sig.c_variadic() {
305 return Err("C variadic");
308 if callee_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
312 if callee_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
316 if callee_attrs.no_sanitize != self.codegen_fn_attrs.no_sanitize {
317 return Err("incompatible sanitizer set");
320 if callee_attrs.instruction_set != self.codegen_fn_attrs.instruction_set {
321 return Err("incompatible instruction set");
324 for feature in &callee_attrs.target_features {
325 if !self.codegen_fn_attrs.target_features.contains(feature) {
326 return Err("incompatible target feature");
333 /// Returns inlining decision that is based on the examination of callee MIR body.
334 /// Assumes that codegen attributes have been checked for compatibility already.
335 #[instrument(level = "debug", skip(self, callee_body))]
338 callsite: &CallSite<'tcx>,
339 callee_body: &Body<'tcx>,
340 callee_attrs: &CodegenFnAttrs,
341 ) -> Result<(), &'static str> {
344 let mut threshold = if callee_attrs.requests_inline() {
345 self.tcx.sess.opts.debugging_opts.inline_mir_hint_threshold.unwrap_or(100)
347 self.tcx.sess.opts.debugging_opts.inline_mir_threshold.unwrap_or(50)
350 // Give a bonus functions with a small number of blocks,
351 // We normally have two or three blocks for even
352 // very small functions.
353 if callee_body.basic_blocks().len() <= 3 {
354 threshold += threshold / 4;
356 debug!(" final inline threshold = {}", threshold);
358 // FIXME: Give a bonus to functions with only a single caller
359 let mut first_block = true;
362 // Traverse the MIR manually so we can account for the effects of
363 // inlining on the CFG.
364 let mut work_list = vec![START_BLOCK];
365 let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
366 while let Some(bb) = work_list.pop() {
367 if !visited.insert(bb.index()) {
370 let blk = &callee_body.basic_blocks()[bb];
372 for stmt in &blk.statements {
373 // Don't count StorageLive/StorageDead in the inlining cost.
375 StatementKind::StorageLive(_)
376 | StatementKind::StorageDead(_)
377 | StatementKind::Nop => {}
378 _ => cost += INSTR_COST,
381 let term = blk.terminator();
382 let mut is_drop = false;
384 TerminatorKind::Drop { ref place, target, unwind }
385 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
387 work_list.push(target);
388 // If the place doesn't actually need dropping, treat it like
390 let ty = callsite.callee.subst_mir(self.tcx, &place.ty(callee_body, tcx).ty);
391 if ty.needs_drop(tcx, self.param_env) {
392 cost += CALL_PENALTY;
393 if let Some(unwind) = unwind {
394 cost += LANDINGPAD_PENALTY;
395 work_list.push(unwind);
402 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
405 // If the function always diverges, don't inline
406 // unless the cost is zero
410 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
411 if let ty::FnDef(def_id, substs) =
412 *callsite.callee.subst_mir(self.tcx, &f.literal.ty()).kind()
414 let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
415 if let Ok(Some(instance)) =
416 Instance::resolve(self.tcx, self.param_env, def_id, substs)
418 if callsite.callee.def_id() == instance.def_id() {
419 return Err("self-recursion");
420 } else if self.history.contains(&instance) {
421 return Err("already inlined");
424 // Don't give intrinsics the extra penalty for calls
425 let f = tcx.fn_sig(def_id);
426 if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
429 cost += CALL_PENALTY;
432 cost += CALL_PENALTY;
434 if cleanup.is_some() {
435 cost += LANDINGPAD_PENALTY;
438 TerminatorKind::Assert { cleanup, .. } => {
439 cost += CALL_PENALTY;
441 if cleanup.is_some() {
442 cost += LANDINGPAD_PENALTY;
445 TerminatorKind::Resume => cost += RESUME_PENALTY,
446 TerminatorKind::InlineAsm { cleanup, .. } => {
449 if cleanup.is_some() {
450 cost += LANDINGPAD_PENALTY;
453 _ => cost += INSTR_COST,
457 for &succ in term.successors() {
458 work_list.push(succ);
465 // Count up the cost of local variables and temps, if we know the size
466 // use that, otherwise we use a moderately-large dummy cost.
468 let ptr_size = tcx.data_layout.pointer_size.bytes();
470 for v in callee_body.vars_and_temps_iter() {
471 let ty = callsite.callee.subst_mir(self.tcx, &callee_body.local_decls[v].ty);
472 // Cost of the var is the size in machine-words, if we know
474 if let Some(size) = type_size_of(tcx, self.param_env, ty) {
475 cost += ((size + ptr_size - 1) / ptr_size) as usize;
477 cost += UNKNOWN_SIZE_COST;
481 if let InlineAttr::Always = callee_attrs.inline {
482 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
485 if cost <= threshold {
486 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
489 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
490 Err("cost above threshold")
497 caller_body: &mut Body<'tcx>,
498 callsite: &CallSite<'tcx>,
499 mut callee_body: Body<'tcx>,
501 let terminator = caller_body[callsite.block].terminator.take().unwrap();
502 match terminator.kind {
503 TerminatorKind::Call { args, destination, cleanup, .. } => {
504 // If the call is something like `a[*i] = f(i)`, where
505 // `i : &mut usize`, then just duplicating the `a[*i]`
506 // Place could result in two different locations if `f`
507 // writes to `i`. To prevent this we need to create a temporary
508 // borrow of the place and pass the destination as `*temp` instead.
509 fn dest_needs_borrow(place: Place<'_>) -> bool {
510 for elem in place.projection.iter() {
512 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
520 let dest = if let Some((destination_place, _)) = destination {
521 if dest_needs_borrow(destination_place) {
522 trace!("creating temp for return destination");
523 let dest = Rvalue::Ref(
524 self.tcx.lifetimes.re_erased,
525 BorrowKind::Mut { allow_two_phase_borrow: false },
528 let dest_ty = dest.ty(caller_body, self.tcx);
529 let temp = Place::from(self.new_call_temp(caller_body, &callsite, dest_ty));
530 caller_body[callsite.block].statements.push(Statement {
531 source_info: callsite.source_info,
532 kind: StatementKind::Assign(Box::new((temp, dest))),
534 self.tcx.mk_place_deref(temp)
539 trace!("creating temp for return place");
540 Place::from(self.new_call_temp(caller_body, &callsite, callee_body.return_ty()))
543 // Copy the arguments if needed.
544 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, &callee_body);
546 let mut integrator = Integrator {
548 new_locals: Local::new(caller_body.local_decls.len())..,
549 new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
550 new_blocks: BasicBlock::new(caller_body.basic_blocks().len())..,
552 return_block: callsite.target,
553 cleanup_block: cleanup,
554 in_cleanup_block: false,
556 callsite_span: callsite.source_info.span,
557 body_span: callee_body.span,
558 always_live_locals: BitSet::new_filled(callee_body.local_decls.len()),
561 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
562 // (or existing ones, in a few special cases) in the caller.
563 integrator.visit_body(&mut callee_body);
565 for scope in &mut callee_body.source_scopes {
566 // FIXME(eddyb) move this into a `fn visit_scope_data` in `Integrator`.
567 if scope.parent_scope.is_none() {
568 let callsite_scope = &caller_body.source_scopes[callsite.source_info.scope];
570 // Attach the outermost callee scope as a child of the callsite
571 // scope, via the `parent_scope` and `inlined_parent_scope` chains.
572 scope.parent_scope = Some(callsite.source_info.scope);
573 assert_eq!(scope.inlined_parent_scope, None);
574 scope.inlined_parent_scope = if callsite_scope.inlined.is_some() {
575 Some(callsite.source_info.scope)
577 callsite_scope.inlined_parent_scope
580 // Mark the outermost callee scope as an inlined one.
581 assert_eq!(scope.inlined, None);
582 scope.inlined = Some((callsite.callee, callsite.source_info.span));
583 } else if scope.inlined_parent_scope.is_none() {
584 // Make it easy to find the scope with `inlined` set above.
585 scope.inlined_parent_scope =
586 Some(integrator.map_scope(OUTERMOST_SOURCE_SCOPE));
590 // If there are any locals without storage markers, give them storage only for the
591 // duration of the call.
592 for local in callee_body.vars_and_temps_iter() {
593 if integrator.always_live_locals.contains(local) {
594 let new_local = integrator.map_local(local);
595 caller_body[callsite.block].statements.push(Statement {
596 source_info: callsite.source_info,
597 kind: StatementKind::StorageLive(new_local),
601 if let Some(block) = callsite.target {
602 // To avoid repeated O(n) insert, push any new statements to the end and rotate
605 for local in callee_body.vars_and_temps_iter().rev() {
606 if integrator.always_live_locals.contains(local) {
607 let new_local = integrator.map_local(local);
608 caller_body[block].statements.push(Statement {
609 source_info: callsite.source_info,
610 kind: StatementKind::StorageDead(new_local),
615 caller_body[block].statements.rotate_right(n);
618 // Insert all of the (mapped) parts of the callee body into the caller.
619 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
620 caller_body.source_scopes.extend(&mut callee_body.source_scopes.drain(..));
621 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
622 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
624 caller_body[callsite.block].terminator = Some(Terminator {
625 source_info: callsite.source_info,
626 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
629 // Copy only unevaluated constants from the callee_body into the caller_body.
630 // Although we are only pushing `ConstKind::Unevaluated` consts to
631 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
632 // because we are calling `subst_and_normalize_erasing_regions`.
633 caller_body.required_consts.extend(
634 callee_body.required_consts.iter().copied().filter(|&ct| {
635 match ct.literal.const_for_ty() {
636 Some(ct) => matches!(ct.val(), ConstKind::Unevaluated(_)),
642 kind => bug!("unexpected terminator kind {:?}", kind),
648 args: Vec<Operand<'tcx>>,
649 callsite: &CallSite<'tcx>,
650 caller_body: &mut Body<'tcx>,
651 callee_body: &Body<'tcx>,
655 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
656 // The caller provides the arguments wrapped up in a tuple:
658 // tuple_tmp = (a, b, c)
659 // Fn::call(closure_ref, tuple_tmp)
661 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
662 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
663 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
666 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
668 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
669 // if we "spill" that into *another* temporary, so that we can map the argument
670 // variable in the callee MIR directly to an argument variable on our side.
671 // So we introduce temporaries like:
673 // tmp0 = tuple_tmp.0
674 // tmp1 = tuple_tmp.1
675 // tmp2 = tuple_tmp.2
677 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
678 if callsite.fn_sig.abi() == Abi::RustCall && callee_body.spread_arg.is_none() {
679 let mut args = args.into_iter();
680 let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
681 let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
682 assert!(args.next().is_none());
684 let tuple = Place::from(tuple);
685 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
686 bug!("Closure arguments are not passed as a tuple");
689 // The `closure_ref` in our example above.
690 let closure_ref_arg = iter::once(self_);
692 // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
693 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
694 // This is e.g., `tuple_tmp.0` in our example above.
695 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty));
697 // Spill to a local to make e.g., `tmp0`.
698 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
701 closure_ref_arg.chain(tuple_tmp_args).collect()
704 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
709 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
710 /// temporary `T` and an instruction `T = arg`, and returns `T`.
711 fn create_temp_if_necessary(
714 callsite: &CallSite<'tcx>,
715 caller_body: &mut Body<'tcx>,
717 // Reuse the operand if it is a moved temporary.
718 if let Operand::Move(place) = &arg {
719 if let Some(local) = place.as_local() {
720 if caller_body.local_kind(local) == LocalKind::Temp {
726 // Otherwise, create a temporary for the argument.
727 trace!("creating temp for argument {:?}", arg);
728 let arg_ty = arg.ty(caller_body, self.tcx);
729 let local = self.new_call_temp(caller_body, callsite, arg_ty);
730 caller_body[callsite.block].statements.push(Statement {
731 source_info: callsite.source_info,
732 kind: StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg)))),
737 /// Introduces a new temporary into the caller body that is live for the duration of the call.
740 caller_body: &mut Body<'tcx>,
741 callsite: &CallSite<'tcx>,
744 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
746 caller_body[callsite.block].statements.push(Statement {
747 source_info: callsite.source_info,
748 kind: StatementKind::StorageLive(local),
751 if let Some(block) = callsite.target {
752 caller_body[block].statements.insert(
755 source_info: callsite.source_info,
756 kind: StatementKind::StorageDead(local),
765 fn type_size_of<'tcx>(
767 param_env: ty::ParamEnv<'tcx>,
770 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
776 * Integrates blocks from the callee function into the calling function.
777 * Updates block indices, references to locals and other control flow
780 struct Integrator<'a, 'tcx> {
782 new_locals: RangeFrom<Local>,
783 new_scopes: RangeFrom<SourceScope>,
784 new_blocks: RangeFrom<BasicBlock>,
785 destination: Place<'tcx>,
786 return_block: Option<BasicBlock>,
787 cleanup_block: Option<BasicBlock>,
788 in_cleanup_block: bool,
792 always_live_locals: BitSet<Local>,
795 impl Integrator<'_, '_> {
796 fn map_local(&self, local: Local) -> Local {
797 let new = if local == RETURN_PLACE {
798 self.destination.local
800 let idx = local.index() - 1;
801 if idx < self.args.len() {
804 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
807 trace!("mapping local `{:?}` to `{:?}`", local, new);
811 fn map_scope(&self, scope: SourceScope) -> SourceScope {
812 let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
813 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
817 fn map_block(&self, block: BasicBlock) -> BasicBlock {
818 let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
819 trace!("mapping block `{:?}` to `{:?}`", block, new);
824 impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
825 fn tcx(&self) -> TyCtxt<'tcx> {
829 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
830 *local = self.map_local(*local);
833 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
834 *scope = self.map_scope(*scope);
837 fn visit_span(&mut self, span: &mut Span) {
839 ExpnData::default(ExpnKind::Inlined, *span, self.tcx.sess.edition(), None, None);
840 expn_data.def_site = self.body_span;
841 // Make sure that all spans track the fact that they were inlined.
843 self.callsite_span.fresh_expansion(expn_data, self.tcx.create_stable_hashing_context());
846 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
847 for elem in place.projection {
848 // FIXME: Make sure that return place is not used in an indexing projection, since it
849 // won't be rebased as it is supposed to be.
850 assert_ne!(ProjectionElem::Index(RETURN_PLACE), elem);
853 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
854 let dest_proj_len = self.destination.projection.len();
855 if place.local == RETURN_PLACE && dest_proj_len > 0 {
856 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
857 projs.extend(self.destination.projection);
858 projs.extend(place.projection);
860 place.projection = self.tcx.intern_place_elems(&*projs);
862 // Handles integrating any locals that occur in the base
864 self.super_place(place, context, location)
867 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
868 self.in_cleanup_block = data.is_cleanup;
869 self.super_basic_block_data(block, data);
870 self.in_cleanup_block = false;
873 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
874 self.super_retag(kind, place, loc);
876 // We have to patch all inlined retags to be aware that they are no longer
877 // happening on function entry.
878 if *kind == RetagKind::FnEntry {
879 *kind = RetagKind::Default;
883 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
884 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
887 self.always_live_locals.remove(local);
889 self.super_statement(statement, location);
892 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
893 // Don't try to modify the implicit `_0` access on return (`return` terminators are
894 // replaced down below anyways).
895 if !matches!(terminator.kind, TerminatorKind::Return) {
896 self.super_terminator(terminator, loc);
899 match terminator.kind {
900 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
901 TerminatorKind::Goto { ref mut target } => {
902 *target = self.map_block(*target);
904 TerminatorKind::SwitchInt { ref mut targets, .. } => {
905 for tgt in targets.all_targets_mut() {
906 *tgt = self.map_block(*tgt);
909 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
910 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
911 *target = self.map_block(*target);
912 if let Some(tgt) = *unwind {
913 *unwind = Some(self.map_block(tgt));
914 } else if !self.in_cleanup_block {
915 // Unless this drop is in a cleanup block, add an unwind edge to
916 // the original call's cleanup block
917 *unwind = self.cleanup_block;
920 TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
921 if let Some((_, ref mut tgt)) = *destination {
922 *tgt = self.map_block(*tgt);
924 if let Some(tgt) = *cleanup {
925 *cleanup = Some(self.map_block(tgt));
926 } else if !self.in_cleanup_block {
927 // Unless this call is in a cleanup block, add an unwind edge to
928 // the original call's cleanup block
929 *cleanup = self.cleanup_block;
932 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
933 *target = self.map_block(*target);
934 if let Some(tgt) = *cleanup {
935 *cleanup = Some(self.map_block(tgt));
936 } else if !self.in_cleanup_block {
937 // Unless this assert is in a cleanup block, add an unwind edge to
938 // the original call's cleanup block
939 *cleanup = self.cleanup_block;
942 TerminatorKind::Return => {
943 terminator.kind = if let Some(tgt) = self.return_block {
944 TerminatorKind::Goto { target: tgt }
946 TerminatorKind::Unreachable
949 TerminatorKind::Resume => {
950 if let Some(tgt) = self.cleanup_block {
951 terminator.kind = TerminatorKind::Goto { target: tgt }
954 TerminatorKind::Abort => {}
955 TerminatorKind::Unreachable => {}
956 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
957 *real_target = self.map_block(*real_target);
958 *imaginary_target = self.map_block(*imaginary_target);
960 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
961 // see the ordering of passes in the optimized_mir query.
963 bug!("False unwinds should have been removed before inlining")
965 TerminatorKind::InlineAsm { ref mut destination, ref mut cleanup, .. } => {
966 if let Some(ref mut tgt) = *destination {
967 *tgt = self.map_block(*tgt);
968 } else if !self.in_cleanup_block {
969 // Unless this inline asm is in a cleanup block, add an unwind edge to
970 // the original call's cleanup block
971 *cleanup = self.cleanup_block;