1 //! Inlining pass for MIR functions
2 use crate::deref_separator::deref_finder;
3 use rustc_attr::InlineAttr;
4 use rustc_index::bit_set::BitSet;
5 use rustc_index::vec::Idx;
6 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
7 use rustc_middle::mir::visit::*;
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
10 use rustc_session::config::OptLevel;
11 use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span};
12 use rustc_target::abi::VariantIdx;
13 use rustc_target::spec::abi::Abi;
15 use crate::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.unstable_opts.inline_mir {
47 match sess.mir_opt_level() {
50 (sess.opts.optimize == OptLevel::Default
51 || sess.opts.optimize == OptLevel::Aggressive)
52 && sess.opts.incremental == None
58 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
59 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
60 let _guard = span.enter();
61 if inline(tcx, body) {
62 debug!("running simplify cfg on {:?}", body.source);
63 CfgSimplifier::new(body).simplify();
64 remove_dead_blocks(tcx, body);
65 deref_finder(tcx, body);
70 fn inline<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
71 let def_id = body.source.def_id().expect_local();
73 // Only do inlining into fn bodies.
74 if !tcx.hir().body_owner_kind(def_id).is_fn_or_closure() {
77 if body.source.promoted.is_some() {
80 // Avoid inlining into generators, since their `optimized_mir` is used for layout computation,
81 // which can create a cycle, even when no attempt is made to inline the function in the other
83 if body.generator.is_some() {
87 let param_env = tcx.param_env_reveal_all_normalized(def_id);
90 Inliner { tcx, param_env, codegen_fn_attrs: tcx.codegen_fn_attrs(def_id), changed: false };
91 let blocks = BasicBlock::new(0)..body.basic_blocks.next_index();
92 this.process_blocks(body, blocks);
96 struct Inliner<'tcx> {
98 param_env: ParamEnv<'tcx>,
99 /// Caller codegen attributes.
100 codegen_fn_attrs: &'tcx CodegenFnAttrs,
101 /// Indicates that the caller body has been modified.
105 impl<'tcx> Inliner<'tcx> {
106 fn process_blocks(&mut self, caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>) {
108 let bb_data = &caller_body[bb];
109 if bb_data.is_cleanup {
113 let Some(callsite) = self.resolve_callsite(caller_body, bb, bb_data) else {
117 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
118 let _guard = span.enter();
120 match self.try_inlining(caller_body, &callsite) {
122 debug!("not-inlined {} [{}]", callsite.callee, reason);
126 debug!("inlined {}", callsite.callee);
128 // We could process the blocks returned by `try_inlining` here. However, that
129 // leads to exponential compile times due to the top-down nature of this kind
136 /// Attempts to inline a callsite into the caller body. When successful returns basic blocks
137 /// containing the inlined body. Otherwise returns an error describing why inlining didn't take
141 caller_body: &mut Body<'tcx>,
142 callsite: &CallSite<'tcx>,
143 ) -> Result<std::ops::Range<BasicBlock>, &'static str> {
144 let callee_attrs = self.tcx.codegen_fn_attrs(callsite.callee.def_id());
145 self.check_codegen_attributes(callsite, callee_attrs)?;
146 self.check_mir_is_available(caller_body, &callsite.callee)?;
147 let callee_body = self.tcx.instance_mir(callsite.callee.def);
148 self.check_mir_body(callsite, callee_body, callee_attrs)?;
150 if !self.tcx.consider_optimizing(|| {
151 format!("Inline {:?} into {:?}", callsite.callee, caller_body.source)
153 return Err("optimization fuel exhausted");
156 let Ok(callee_body) = callsite.callee.try_subst_mir_and_normalize_erasing_regions(
161 return Err("failed to normalize callee body");
164 // Check call signature compatibility.
165 // Normally, this shouldn't be required, but trait normalization failure can create a
167 let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
168 let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
169 let destination_ty = destination.ty(&caller_body.local_decls, self.tcx).ty;
170 let output_type = callee_body.return_ty();
171 if !util::is_subtype(self.tcx, self.param_env, output_type, destination_ty) {
172 trace!(?output_type, ?destination_ty);
173 return Err("failed to normalize return type");
175 if callsite.fn_sig.abi() == Abi::RustCall {
176 let (arg_tuple, skipped_args) = match &args[..] {
177 [arg_tuple] => (arg_tuple, 0),
178 [_, arg_tuple] => (arg_tuple, 1),
179 _ => bug!("Expected `rust-call` to have 1 or 2 args"),
182 let arg_tuple_ty = arg_tuple.ty(&caller_body.local_decls, self.tcx);
183 let ty::Tuple(arg_tuple_tys) = arg_tuple_ty.kind() else {
184 bug!("Closure arguments are not passed as a tuple");
187 for (arg_ty, input) in
188 arg_tuple_tys.iter().zip(callee_body.args_iter().skip(skipped_args))
190 let input_type = callee_body.local_decls[input].ty;
191 if !util::is_subtype(self.tcx, self.param_env, input_type, arg_ty) {
192 trace!(?arg_ty, ?input_type);
193 return Err("failed to normalize tuple argument type");
197 for (arg, input) in args.iter().zip(callee_body.args_iter()) {
198 let input_type = callee_body.local_decls[input].ty;
199 let arg_ty = arg.ty(&caller_body.local_decls, self.tcx);
200 if !util::is_subtype(self.tcx, self.param_env, input_type, arg_ty) {
201 trace!(?arg_ty, ?input_type);
202 return Err("failed to normalize argument type");
207 let old_blocks = caller_body.basic_blocks.next_index();
208 self.inline_call(caller_body, &callsite, callee_body);
209 let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
214 fn check_mir_is_available(
216 caller_body: &Body<'tcx>,
217 callee: &Instance<'tcx>,
218 ) -> Result<(), &'static str> {
219 let caller_def_id = caller_body.source.def_id();
220 let callee_def_id = callee.def_id();
221 if callee_def_id == caller_def_id {
222 return Err("self-recursion");
226 InstanceDef::Item(_) => {
227 // If there is no MIR available (either because it was not in metadata or
228 // because it has no MIR because it's an extern function), then the inliner
229 // won't cause cycles on this.
230 if !self.tcx.is_mir_available(callee_def_id) {
231 return Err("item MIR unavailable");
234 // These have no own callable MIR.
235 InstanceDef::Intrinsic(_) | InstanceDef::Virtual(..) => {
236 return Err("instance without MIR (intrinsic / virtual)");
238 // This cannot result in an immediate cycle since the callee MIR is a shim, which does
239 // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
240 // do not need to catch this here, we can wait until the inliner decides to continue
241 // inlining a second time.
242 InstanceDef::VTableShim(_)
243 | InstanceDef::ReifyShim(_)
244 | InstanceDef::FnPtrShim(..)
245 | InstanceDef::ClosureOnceShim { .. }
246 | InstanceDef::DropGlue(..)
247 | InstanceDef::CloneShim(..) => return Ok(()),
250 if self.tcx.is_constructor(callee_def_id) {
251 trace!("constructors always have MIR");
252 // Constructor functions cannot cause a query cycle.
256 if callee_def_id.is_local() {
257 // Avoid a cycle here by only using `instance_mir` only if we have
258 // a lower `DefPathHash` than the callee. This ensures that the callee will
259 // not inline us. This trick even works with incremental compilation,
260 // since `DefPathHash` is stable.
261 if self.tcx.def_path_hash(caller_def_id).local_hash()
262 < self.tcx.def_path_hash(callee_def_id).local_hash()
267 // If we know for sure that the function we're calling will itself try to
268 // call us, then we avoid inlining that function.
269 if self.tcx.mir_callgraph_reachable((*callee, caller_def_id.expect_local())) {
270 return Err("caller might be reachable from callee (query cycle avoidance)");
275 // This cannot result in an immediate cycle since the callee MIR is from another crate
276 // and is already optimized. Any subsequent inlining may cause cycles, but we do
277 // not need to catch this here, we can wait until the inliner decides to continue
278 // inlining a second time.
279 trace!("functions from other crates always have MIR");
286 caller_body: &Body<'tcx>,
288 bb_data: &BasicBlockData<'tcx>,
289 ) -> Option<CallSite<'tcx>> {
290 // Only consider direct calls to functions
291 let terminator = bb_data.terminator();
292 if let TerminatorKind::Call { ref func, target, .. } = terminator.kind {
293 let func_ty = func.ty(caller_body, self.tcx);
294 if let ty::FnDef(def_id, substs) = *func_ty.kind() {
295 // To resolve an instance its substs have to be fully normalized.
296 let substs = self.tcx.try_normalize_erasing_regions(self.param_env, substs).ok()?;
298 Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?;
300 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
304 let fn_sig = self.tcx.bound_fn_sig(def_id).subst(self.tcx, substs);
306 return Some(CallSite {
311 source_info: terminator.source_info,
319 /// Returns an error if inlining is not possible based on codegen attributes alone. A success
320 /// indicates that inlining decision should be based on other criteria.
321 fn check_codegen_attributes(
323 callsite: &CallSite<'tcx>,
324 callee_attrs: &CodegenFnAttrs,
325 ) -> Result<(), &'static str> {
326 match callee_attrs.inline {
327 InlineAttr::Never => return Err("never inline hint"),
328 InlineAttr::Always | InlineAttr::Hint => {}
329 InlineAttr::None => {
330 if self.tcx.sess.mir_opt_level() <= 2 {
331 return Err("at mir-opt-level=2, only #[inline] is inlined");
336 // Only inline local functions if they would be eligible for cross-crate
337 // inlining. This is to ensure that the final crate doesn't have MIR that
338 // reference unexported symbols
339 if callsite.callee.def_id().is_local() {
340 let is_generic = callsite.callee.substs.non_erasable_generics().next().is_some();
341 if !is_generic && !callee_attrs.requests_inline() {
342 return Err("not exported");
346 if callsite.fn_sig.c_variadic() {
347 return Err("C variadic");
350 if callee_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
354 if callee_attrs.no_sanitize != self.codegen_fn_attrs.no_sanitize {
355 return Err("incompatible sanitizer set");
358 // Two functions are compatible if the callee has no attribute (meaning
359 // that it's codegen agnostic), or sets an attribute that is identical
360 // to this function's attribute.
361 if callee_attrs.instruction_set.is_some()
362 && callee_attrs.instruction_set != self.codegen_fn_attrs.instruction_set
364 return Err("incompatible instruction set");
367 for feature in &callee_attrs.target_features {
368 if !self.codegen_fn_attrs.target_features.contains(feature) {
369 return Err("incompatible target feature");
376 /// Returns inlining decision that is based on the examination of callee MIR body.
377 /// Assumes that codegen attributes have been checked for compatibility already.
378 #[instrument(level = "debug", skip(self, callee_body))]
381 callsite: &CallSite<'tcx>,
382 callee_body: &Body<'tcx>,
383 callee_attrs: &CodegenFnAttrs,
384 ) -> Result<(), &'static str> {
387 let mut threshold = if callee_attrs.requests_inline() {
388 self.tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
390 self.tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
393 // Give a bonus functions with a small number of blocks,
394 // We normally have two or three blocks for even
395 // very small functions.
396 if callee_body.basic_blocks.len() <= 3 {
397 threshold += threshold / 4;
399 debug!(" final inline threshold = {}", threshold);
401 // FIXME: Give a bonus to functions with only a single caller
402 let diverges = matches!(
403 callee_body.basic_blocks[START_BLOCK].terminator().kind,
404 TerminatorKind::Unreachable | TerminatorKind::Call { target: None, .. }
406 if diverges && !matches!(callee_attrs.inline, InlineAttr::Always) {
407 return Err("callee diverges unconditionally");
410 let mut checker = CostChecker {
412 param_env: self.param_env,
413 instance: callsite.callee,
419 // Traverse the MIR manually so we can account for the effects of inlining on the CFG.
420 let mut work_list = vec![START_BLOCK];
421 let mut visited = BitSet::new_empty(callee_body.basic_blocks.len());
422 while let Some(bb) = work_list.pop() {
423 if !visited.insert(bb.index()) {
427 let blk = &callee_body.basic_blocks[bb];
428 checker.visit_basic_block_data(bb, blk);
430 let term = blk.terminator();
431 if let TerminatorKind::Drop { ref place, target, unwind }
432 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } = term.kind
434 work_list.push(target);
436 // If the place doesn't actually need dropping, treat it like a regular goto.
437 let ty = callsite.callee.subst_mir(self.tcx, &place.ty(callee_body, tcx).ty);
438 if ty.needs_drop(tcx, self.param_env) && let Some(unwind) = unwind {
439 work_list.push(unwind);
441 } else if callee_attrs.instruction_set != self.codegen_fn_attrs.instruction_set
442 && matches!(term.kind, TerminatorKind::InlineAsm { .. })
444 // During the attribute checking stage we allow a callee with no
445 // instruction_set assigned to count as compatible with a function that does
446 // assign one. However, during this stage we require an exact match when any
447 // inline-asm is detected. LLVM will still possibly do an inline later on
448 // if the no-attribute function ends up with the same instruction set anyway.
449 return Err("Cannot move inline-asm across instruction sets");
451 work_list.extend(term.successors())
455 // Count up the cost of local variables and temps, if we know the size
456 // use that, otherwise we use a moderately-large dummy cost.
457 for v in callee_body.vars_and_temps_iter() {
458 checker.visit_local_decl(v, &callee_body.local_decls[v]);
461 // Abort if type validation found anything fishy.
464 let cost = checker.cost;
465 if let InlineAttr::Always = callee_attrs.inline {
466 debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
468 } else if cost <= threshold {
469 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
472 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
473 Err("cost above threshold")
479 caller_body: &mut Body<'tcx>,
480 callsite: &CallSite<'tcx>,
481 mut callee_body: Body<'tcx>,
483 let terminator = caller_body[callsite.block].terminator.take().unwrap();
484 match terminator.kind {
485 TerminatorKind::Call { args, destination, cleanup, .. } => {
486 // If the call is something like `a[*i] = f(i)`, where
487 // `i : &mut usize`, then just duplicating the `a[*i]`
488 // Place could result in two different locations if `f`
489 // writes to `i`. To prevent this we need to create a temporary
490 // borrow of the place and pass the destination as `*temp` instead.
491 fn dest_needs_borrow(place: Place<'_>) -> bool {
492 for elem in place.projection.iter() {
494 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
502 let dest = if dest_needs_borrow(destination) {
503 trace!("creating temp for return destination");
504 let dest = Rvalue::Ref(
505 self.tcx.lifetimes.re_erased,
506 BorrowKind::Mut { allow_two_phase_borrow: false },
509 let dest_ty = dest.ty(caller_body, self.tcx);
510 let temp = Place::from(self.new_call_temp(caller_body, &callsite, dest_ty));
511 caller_body[callsite.block].statements.push(Statement {
512 source_info: callsite.source_info,
513 kind: StatementKind::Assign(Box::new((temp, dest))),
515 self.tcx.mk_place_deref(temp)
520 // Copy the arguments if needed.
521 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, &callee_body);
523 let mut expn_data = ExpnData::default(
525 callsite.source_info.span,
526 self.tcx.sess.edition(),
530 expn_data.def_site = callee_body.span;
532 self.tcx.with_stable_hashing_context(|hcx| LocalExpnId::fresh(expn_data, hcx));
533 let mut integrator = Integrator {
535 new_locals: Local::new(caller_body.local_decls.len())..,
536 new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
537 new_blocks: BasicBlock::new(caller_body.basic_blocks.len())..,
539 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
541 cleanup_block: cleanup,
542 in_cleanup_block: false,
545 always_live_locals: BitSet::new_filled(callee_body.local_decls.len()),
548 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
549 // (or existing ones, in a few special cases) in the caller.
550 integrator.visit_body(&mut callee_body);
552 // If there are any locals without storage markers, give them storage only for the
553 // duration of the call.
554 for local in callee_body.vars_and_temps_iter() {
555 if !callee_body.local_decls[local].internal
556 && integrator.always_live_locals.contains(local)
558 let new_local = integrator.map_local(local);
559 caller_body[callsite.block].statements.push(Statement {
560 source_info: callsite.source_info,
561 kind: StatementKind::StorageLive(new_local),
565 if let Some(block) = callsite.target {
566 // To avoid repeated O(n) insert, push any new statements to the end and rotate
569 for local in callee_body.vars_and_temps_iter().rev() {
570 if !callee_body.local_decls[local].internal
571 && integrator.always_live_locals.contains(local)
573 let new_local = integrator.map_local(local);
574 caller_body[block].statements.push(Statement {
575 source_info: callsite.source_info,
576 kind: StatementKind::StorageDead(new_local),
581 caller_body[block].statements.rotate_right(n);
584 // Insert all of the (mapped) parts of the callee body into the caller.
585 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
586 caller_body.source_scopes.extend(&mut callee_body.source_scopes.drain(..));
587 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
588 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
590 caller_body[callsite.block].terminator = Some(Terminator {
591 source_info: callsite.source_info,
592 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
595 // Copy only unevaluated constants from the callee_body into the caller_body.
596 // Although we are only pushing `ConstKind::Unevaluated` consts to
597 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
598 // because we are calling `subst_and_normalize_erasing_regions`.
599 caller_body.required_consts.extend(
600 callee_body.required_consts.iter().copied().filter(|&ct| match ct.literal {
601 ConstantKind::Ty(_) => {
602 bug!("should never encounter ty::UnevaluatedConst in `required_consts`")
604 ConstantKind::Val(..) | ConstantKind::Unevaluated(..) => true,
608 kind => bug!("unexpected terminator kind {:?}", kind),
614 args: Vec<Operand<'tcx>>,
615 callsite: &CallSite<'tcx>,
616 caller_body: &mut Body<'tcx>,
617 callee_body: &Body<'tcx>,
621 // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
622 // The caller provides the arguments wrapped up in a tuple:
624 // tuple_tmp = (a, b, c)
625 // Fn::call(closure_ref, tuple_tmp)
627 // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
628 // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
629 // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
632 // [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
634 // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
635 // if we "spill" that into *another* temporary, so that we can map the argument
636 // variable in the callee MIR directly to an argument variable on our side.
637 // So we introduce temporaries like:
639 // tmp0 = tuple_tmp.0
640 // tmp1 = tuple_tmp.1
641 // tmp2 = tuple_tmp.2
643 // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
644 if callsite.fn_sig.abi() == Abi::RustCall && callee_body.spread_arg.is_none() {
645 let mut args = args.into_iter();
646 let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
647 let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
648 assert!(args.next().is_none());
650 let tuple = Place::from(tuple);
651 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
652 bug!("Closure arguments are not passed as a tuple");
655 // The `closure_ref` in our example above.
656 let closure_ref_arg = iter::once(self_);
658 // The `tmp0`, `tmp1`, and `tmp2` in our example above.
659 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
660 // This is e.g., `tuple_tmp.0` in our example above.
661 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty));
663 // Spill to a local to make e.g., `tmp0`.
664 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
667 closure_ref_arg.chain(tuple_tmp_args).collect()
670 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
675 /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
676 /// temporary `T` and an instruction `T = arg`, and returns `T`.
677 fn create_temp_if_necessary(
680 callsite: &CallSite<'tcx>,
681 caller_body: &mut Body<'tcx>,
683 // Reuse the operand if it is a moved temporary.
684 if let Operand::Move(place) = &arg
685 && let Some(local) = place.as_local()
686 && caller_body.local_kind(local) == LocalKind::Temp
691 // Otherwise, create a temporary for the argument.
692 trace!("creating temp for argument {:?}", arg);
693 let arg_ty = arg.ty(caller_body, self.tcx);
694 let local = self.new_call_temp(caller_body, callsite, arg_ty);
695 caller_body[callsite.block].statements.push(Statement {
696 source_info: callsite.source_info,
697 kind: StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg)))),
702 /// Introduces a new temporary into the caller body that is live for the duration of the call.
705 caller_body: &mut Body<'tcx>,
706 callsite: &CallSite<'tcx>,
709 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
711 caller_body[callsite.block].statements.push(Statement {
712 source_info: callsite.source_info,
713 kind: StatementKind::StorageLive(local),
716 if let Some(block) = callsite.target {
717 caller_body[block].statements.insert(
720 source_info: callsite.source_info,
721 kind: StatementKind::StorageDead(local),
730 fn type_size_of<'tcx>(
732 param_env: ty::ParamEnv<'tcx>,
735 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
738 /// Verify that the callee body is compatible with the caller.
740 /// This visitor mostly computes the inlining cost,
741 /// but also needs to verify that types match because of normalization failure.
742 struct CostChecker<'b, 'tcx> {
744 param_env: ParamEnv<'tcx>,
746 callee_body: &'b Body<'tcx>,
747 instance: ty::Instance<'tcx>,
748 validation: Result<(), &'static str>,
751 impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
752 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
753 // Don't count StorageLive/StorageDead in the inlining cost.
754 match statement.kind {
755 StatementKind::StorageLive(_)
756 | StatementKind::StorageDead(_)
757 | StatementKind::Deinit(_)
758 | StatementKind::Nop => {}
759 _ => self.cost += INSTR_COST,
762 self.super_statement(statement, location);
765 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
767 match terminator.kind {
768 TerminatorKind::Drop { ref place, unwind, .. }
769 | TerminatorKind::DropAndReplace { ref place, unwind, .. } => {
770 // If the place doesn't actually need dropping, treat it like a regular goto.
771 let ty = self.instance.subst_mir(tcx, &place.ty(self.callee_body, tcx).ty);
772 if ty.needs_drop(tcx, self.param_env) {
773 self.cost += CALL_PENALTY;
774 if unwind.is_some() {
775 self.cost += LANDINGPAD_PENALTY;
778 self.cost += INSTR_COST;
781 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
782 let fn_ty = self.instance.subst_mir(tcx, &f.literal.ty());
783 self.cost += if let ty::FnDef(def_id, _) = *fn_ty.kind() && tcx.is_intrinsic(def_id) {
784 // Don't give intrinsics the extra penalty for calls
789 if cleanup.is_some() {
790 self.cost += LANDINGPAD_PENALTY;
793 TerminatorKind::Assert { cleanup, .. } => {
794 self.cost += CALL_PENALTY;
795 if cleanup.is_some() {
796 self.cost += LANDINGPAD_PENALTY;
799 TerminatorKind::Resume => self.cost += RESUME_PENALTY,
800 TerminatorKind::InlineAsm { cleanup, .. } => {
801 self.cost += INSTR_COST;
802 if cleanup.is_some() {
803 self.cost += LANDINGPAD_PENALTY;
806 _ => self.cost += INSTR_COST,
809 self.super_terminator(terminator, location);
812 /// Count up the cost of local variables and temps, if we know the size
813 /// use that, otherwise we use a moderately-large dummy cost.
814 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
816 let ptr_size = tcx.data_layout.pointer_size.bytes();
818 let ty = self.instance.subst_mir(tcx, &local_decl.ty);
819 // Cost of the var is the size in machine-words, if we know
821 if let Some(size) = type_size_of(tcx, self.param_env, ty) {
822 self.cost += ((size + ptr_size - 1) / ptr_size) as usize;
824 self.cost += UNKNOWN_SIZE_COST;
827 self.super_local_decl(local, local_decl)
830 /// This method duplicates code from MIR validation in an attempt to detect type mismatches due
831 /// to normalization failure.
832 fn visit_projection_elem(
835 proj_base: &[PlaceElem<'tcx>],
836 elem: PlaceElem<'tcx>,
837 context: PlaceContext,
840 if let ProjectionElem::Field(f, ty) = elem {
841 let parent = Place { local, projection: self.tcx.intern_place_elems(proj_base) };
842 let parent_ty = parent.ty(&self.callee_body.local_decls, self.tcx);
843 let check_equal = |this: &mut Self, f_ty| {
844 if !util::is_equal_up_to_subtyping(this.tcx, this.param_env, ty, f_ty) {
846 this.validation = Err("failed to normalize projection type");
851 let kind = match parent_ty.ty.kind() {
852 &ty::Opaque(def_id, substs) => {
853 self.tcx.bound_type_of(def_id).subst(self.tcx, substs).kind()
859 ty::Tuple(fields) => {
860 let Some(f_ty) = fields.get(f.as_usize()) else {
861 self.validation = Err("malformed MIR");
864 check_equal(self, *f_ty);
866 ty::Adt(adt_def, substs) => {
867 let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
868 let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
869 self.validation = Err("malformed MIR");
872 check_equal(self, field.ty(self.tcx, substs));
874 ty::Closure(_, substs) => {
875 let substs = substs.as_closure();
876 let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else {
877 self.validation = Err("malformed MIR");
880 check_equal(self, f_ty);
882 &ty::Generator(def_id, substs, _) => {
883 let f_ty = if let Some(var) = parent_ty.variant_index {
884 let gen_body = if def_id == self.callee_body.source.def_id() {
887 self.tcx.optimized_mir(def_id)
890 let Some(layout) = gen_body.generator_layout() else {
891 self.validation = Err("malformed MIR");
895 let Some(&local) = layout.variant_fields[var].get(f) else {
896 self.validation = Err("malformed MIR");
900 let Some(&f_ty) = layout.field_tys.get(local) else {
901 self.validation = Err("malformed MIR");
907 let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else {
908 self.validation = Err("malformed MIR");
915 check_equal(self, f_ty);
917 _ => self.validation = Err("malformed MIR"),
921 self.super_projection_elem(local, proj_base, elem, context, location);
928 * Integrates blocks from the callee function into the calling function.
929 * Updates block indices, references to locals and other control flow
932 struct Integrator<'a, 'tcx> {
934 new_locals: RangeFrom<Local>,
935 new_scopes: RangeFrom<SourceScope>,
936 new_blocks: RangeFrom<BasicBlock>,
937 destination: Place<'tcx>,
938 callsite_scope: SourceScopeData<'tcx>,
939 callsite: &'a CallSite<'tcx>,
940 cleanup_block: Option<BasicBlock>,
941 in_cleanup_block: bool,
943 expn_data: LocalExpnId,
944 always_live_locals: BitSet<Local>,
947 impl Integrator<'_, '_> {
948 fn map_local(&self, local: Local) -> Local {
949 let new = if local == RETURN_PLACE {
950 self.destination.local
952 let idx = local.index() - 1;
953 if idx < self.args.len() {
956 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
959 trace!("mapping local `{:?}` to `{:?}`", local, new);
963 fn map_scope(&self, scope: SourceScope) -> SourceScope {
964 let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
965 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
969 fn map_block(&self, block: BasicBlock) -> BasicBlock {
970 let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
971 trace!("mapping block `{:?}` to `{:?}`", block, new);
975 fn map_unwind(&self, unwind: Option<BasicBlock>) -> Option<BasicBlock> {
976 if self.in_cleanup_block {
977 if unwind.is_some() {
978 bug!("cleanup on cleanup block");
984 Some(target) => Some(self.map_block(target)),
985 // Add an unwind edge to the original call's cleanup block
986 None => self.cleanup_block,
991 impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
992 fn tcx(&self) -> TyCtxt<'tcx> {
996 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
997 *local = self.map_local(*local);
1000 fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1001 self.super_source_scope_data(scope_data);
1002 if scope_data.parent_scope.is_none() {
1003 // Attach the outermost callee scope as a child of the callsite
1004 // scope, via the `parent_scope` and `inlined_parent_scope` chains.
1005 scope_data.parent_scope = Some(self.callsite.source_info.scope);
1006 assert_eq!(scope_data.inlined_parent_scope, None);
1007 scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1008 Some(self.callsite.source_info.scope)
1010 self.callsite_scope.inlined_parent_scope
1013 // Mark the outermost callee scope as an inlined one.
1014 assert_eq!(scope_data.inlined, None);
1015 scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1016 } else if scope_data.inlined_parent_scope.is_none() {
1017 // Make it easy to find the scope with `inlined` set above.
1018 scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1022 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1023 *scope = self.map_scope(*scope);
1026 fn visit_span(&mut self, span: &mut Span) {
1027 // Make sure that all spans track the fact that they were inlined.
1028 *span = span.fresh_expansion(self.expn_data);
1031 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1032 for elem in place.projection {
1033 // FIXME: Make sure that return place is not used in an indexing projection, since it
1034 // won't be rebased as it is supposed to be.
1035 assert_ne!(ProjectionElem::Index(RETURN_PLACE), elem);
1038 // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
1039 let dest_proj_len = self.destination.projection.len();
1040 if place.local == RETURN_PLACE && dest_proj_len > 0 {
1041 let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
1042 projs.extend(self.destination.projection);
1043 projs.extend(place.projection);
1045 place.projection = self.tcx.intern_place_elems(&*projs);
1047 // Handles integrating any locals that occur in the base
1049 self.super_place(place, context, location)
1052 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1053 self.in_cleanup_block = data.is_cleanup;
1054 self.super_basic_block_data(block, data);
1055 self.in_cleanup_block = false;
1058 fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
1059 self.super_retag(kind, place, loc);
1061 // We have to patch all inlined retags to be aware that they are no longer
1062 // happening on function entry.
1063 if *kind == RetagKind::FnEntry {
1064 *kind = RetagKind::Default;
1068 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1069 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1072 self.always_live_locals.remove(local);
1074 self.super_statement(statement, location);
1077 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1078 // Don't try to modify the implicit `_0` access on return (`return` terminators are
1079 // replaced down below anyways).
1080 if !matches!(terminator.kind, TerminatorKind::Return) {
1081 self.super_terminator(terminator, loc);
1084 match terminator.kind {
1085 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
1086 TerminatorKind::Goto { ref mut target } => {
1087 *target = self.map_block(*target);
1089 TerminatorKind::SwitchInt { ref mut targets, .. } => {
1090 for tgt in targets.all_targets_mut() {
1091 *tgt = self.map_block(*tgt);
1094 TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
1095 | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
1096 *target = self.map_block(*target);
1097 *unwind = self.map_unwind(*unwind);
1099 TerminatorKind::Call { ref mut target, ref mut cleanup, .. } => {
1100 if let Some(ref mut tgt) = *target {
1101 *tgt = self.map_block(*tgt);
1103 *cleanup = self.map_unwind(*cleanup);
1105 TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
1106 *target = self.map_block(*target);
1107 *cleanup = self.map_unwind(*cleanup);
1109 TerminatorKind::Return => {
1110 terminator.kind = if let Some(tgt) = self.callsite.target {
1111 TerminatorKind::Goto { target: tgt }
1113 TerminatorKind::Unreachable
1116 TerminatorKind::Resume => {
1117 if let Some(tgt) = self.cleanup_block {
1118 terminator.kind = TerminatorKind::Goto { target: tgt }
1121 TerminatorKind::Abort => {}
1122 TerminatorKind::Unreachable => {}
1123 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1124 *real_target = self.map_block(*real_target);
1125 *imaginary_target = self.map_block(*imaginary_target);
1127 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1128 // see the ordering of passes in the optimized_mir query.
1130 bug!("False unwinds should have been removed before inlining")
1132 TerminatorKind::InlineAsm { ref mut destination, ref mut cleanup, .. } => {
1133 if let Some(ref mut tgt) = *destination {
1134 *tgt = self.map_block(*tgt);
1136 *cleanup = self.map_unwind(*cleanup);