1use std::ops::{Range, RangeFrom};
4use std::{debug_assert_matches, iter};
5
6use rustc_abi::{ExternAbi, FieldIdx};
7use rustc_data_structures::thin_vec::ThinVec;
8use rustc_hir::attrs::lang_items::LangItem;
9use rustc_hir::attrs::{InlineAttr, OptimizeAttr};
10use rustc_hir::def::DefKind;
11use rustc_hir::def_id::DefId;
12use rustc_index::Idx;
13use rustc_index::bit_set::DenseBitSet;
14use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
15use rustc_middle::mir::visit::*;
16use rustc_middle::mir::*;
17use rustc_middle::ty::{
18 self, Instance, InstanceKind, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt, Unnormalized,
19};
20use rustc_session::config::{DebugInfo, OptLevel};
21use rustc_span::{Spanned, bug};
22use tracing::{debug, instrument, trace, trace_span};
23
24use crate::cost_checker::{CostChecker, is_call_like};
25use crate::simplify::{UsedInStmtLocals, simplify_cfg};
26use crate::validate::validate_types;
27use crate::{PassPolicy, check_inline, util};
28
29pub(crate) mod cycle;
30
31const HISTORY_DEPTH_LIMIT: usize = 20;
32const TOP_DOWN_DEPTH_LIMIT: usize = 5;
33
34#[derive(Clone, Debug)]
35struct CallSite<'tcx> {
36 callee: Instance<'tcx>,
37 fn_sig: ty::PolyFnSig<'tcx>,
38 block: BasicBlock,
39 source_info: SourceInfo,
40}
41
42pub struct Inline;
45
46impl<'tcx> crate::MirPass<'tcx> for Inline {
47 fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
48 match ctx.opts.unstable_opts.inline_mir {
49 Some(enabled) => PassPolicy::optional(enabled),
50 None => PassPolicy::optional(match ctx.mir_opt_level() {
51 0 | 1 => false,
52 2 => {
56 (ctx.opts.optimize == OptLevel::More
57 || ctx.opts.optimize == OptLevel::Aggressive)
58 && ctx.opts.incremental.is_none()
59 }
60 _ => true,
61 }),
62 }
63 }
64
65 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
66 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
67 let _guard = span.enter();
68 if inline::<NormalInliner<'tcx>>(tcx, body) {
69 debug!("running simplify cfg on {:?}", body.source);
70 simplify_cfg(tcx, body);
71 }
72 }
73}
74
75pub struct ForceInline;
76
77impl ForceInline {
78 pub fn should_run_pass_for_callee<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
79 matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
80 }
81}
82
83impl<'tcx> crate::MirPass<'tcx> for ForceInline {
84 fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
85 PassPolicy::Required
87 }
88
89 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
90 let span = trace_span!("force_inline", body = %tcx.def_path_str(body.source.def_id()));
91 let _guard = span.enter();
92 if inline::<ForceInliner<'tcx>>(tcx, body) {
93 debug!("running simplify cfg on {:?}", body.source);
94 simplify_cfg(tcx, body);
95 }
96 }
97}
98
99trait Inliner<'tcx> {
100 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self;
101
102 fn tcx(&self) -> TyCtxt<'tcx>;
103 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
104 fn history(&self) -> &[DefId];
105 fn caller_def_id(&self) -> DefId;
106
107 fn changed(self) -> bool;
109
110 fn should_inline_for_callee(&self, def_id: DefId) -> bool;
112
113 fn check_codegen_attributes_extra(
114 &self,
115 callee_attrs: &CodegenFnAttrs,
116 ) -> Result<(), &'static str>;
117
118 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool;
119
120 fn check_callee_mir_body(
123 &self,
124 callsite: &CallSite<'tcx>,
125 callee_body: &Body<'tcx>,
126 callee_attrs: &CodegenFnAttrs,
127 ) -> Result<(), &'static str>;
128
129 fn on_inline_success(
131 &mut self,
132 callsite: &CallSite<'tcx>,
133 caller_body: &mut Body<'tcx>,
134 new_blocks: std::ops::Range<BasicBlock>,
135 );
136
137 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str);
139}
140
141struct ForceInliner<'tcx> {
142 tcx: TyCtxt<'tcx>,
143 typing_env: ty::TypingEnv<'tcx>,
144 def_id: DefId,
146 history: Vec<DefId>,
152 changed: bool,
154}
155
156impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> {
157 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
158 Self { tcx, typing_env: body.typing_env(tcx), def_id, history: Vec::new(), changed: false }
159 }
160
161 fn tcx(&self) -> TyCtxt<'tcx> {
162 self.tcx
163 }
164
165 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
166 self.typing_env
167 }
168
169 fn history(&self) -> &[DefId] {
170 &self.history
171 }
172
173 fn caller_def_id(&self) -> DefId {
174 self.def_id
175 }
176
177 fn changed(self) -> bool {
178 self.changed
179 }
180
181 fn should_inline_for_callee(&self, def_id: DefId) -> bool {
182 ForceInline::should_run_pass_for_callee(self.tcx(), def_id)
183 }
184
185 fn check_codegen_attributes_extra(
186 &self,
187 callee_attrs: &CodegenFnAttrs,
188 ) -> Result<(), &'static str> {
189 debug_assert_matches!(callee_attrs.inline, InlineAttr::Force { .. });
190 Ok(())
191 }
192
193 fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool {
194 true
195 }
196
197 #[instrument(level = "debug", skip(self, callee_body))]
198 fn check_callee_mir_body(
199 &self,
200 _: &CallSite<'tcx>,
201 callee_body: &Body<'tcx>,
202 callee_attrs: &CodegenFnAttrs,
203 ) -> Result<(), &'static str> {
204 if callee_body.tainted_by_errors.is_some() {
205 return Err("body has errors");
206 }
207
208 let caller_attrs = self.tcx().codegen_fn_attrs(self.caller_def_id());
209 if callee_attrs.instruction_set != caller_attrs.instruction_set
210 && callee_body
211 .basic_blocks
212 .iter()
213 .any(|bb| matches!(bb.terminator().kind, TerminatorKind::InlineAsm { .. }))
214 {
215 Err("cannot move inline-asm across instruction sets")
221 } else {
222 Ok(())
223 }
224 }
225
226 fn on_inline_success(
227 &mut self,
228 callsite: &CallSite<'tcx>,
229 caller_body: &mut Body<'tcx>,
230 new_blocks: std::ops::Range<BasicBlock>,
231 ) {
232 self.changed = true;
233
234 self.history.push(callsite.callee.def_id());
235 process_blocks(self, caller_body, new_blocks);
236 self.history.pop();
237 }
238
239 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str) {
240 let tcx = self.tcx();
241 let InlineAttr::Force { attr_span, reason: justification } =
242 tcx.codegen_instance_attrs(callsite.callee.def).inline
243 else {
244 bug!("called on item without required inlining");
245 };
246
247 let call_span = callsite.source_info.span;
248 let callee = tcx.def_path_str(callsite.callee.def_id());
249 tcx.dcx().emit_err(crate::diagnostics::ForceInlineFailure {
250 call_span,
251 attr_span,
252 caller_span: tcx.def_span(self.def_id),
253 caller: tcx.def_path_str(self.def_id),
254 callee_span: tcx.def_span(callsite.callee.def_id()),
255 callee: callee.clone(),
256 reason,
257 justification: justification
258 .map(|sym| crate::diagnostics::ForceInlineJustification { sym, callee }),
259 });
260 }
261}
262
263struct NormalInliner<'tcx> {
264 tcx: TyCtxt<'tcx>,
265 typing_env: ty::TypingEnv<'tcx>,
266 def_id: DefId,
268 history: Vec<DefId>,
274 top_down_counter: usize,
278 changed: bool,
280 caller_is_inline_forwarder: bool,
283}
284
285impl<'tcx> NormalInliner<'tcx> {
286 fn past_depth_limit(&self) -> bool {
287 self.history.len() > HISTORY_DEPTH_LIMIT || self.top_down_counter > TOP_DOWN_DEPTH_LIMIT
288 }
289}
290
291impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> {
292 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
293 let typing_env = body.typing_env(tcx);
294 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
295
296 Self {
297 tcx,
298 typing_env,
299 def_id,
300 history: Vec::new(),
301 top_down_counter: 0,
302 changed: false,
303 caller_is_inline_forwarder: matches!(
304 codegen_fn_attrs.inline,
305 InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. }
306 ) && body_is_forwarder(body),
307 }
308 }
309
310 fn tcx(&self) -> TyCtxt<'tcx> {
311 self.tcx
312 }
313
314 fn caller_def_id(&self) -> DefId {
315 self.def_id
316 }
317
318 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
319 self.typing_env
320 }
321
322 fn history(&self) -> &[DefId] {
323 &self.history
324 }
325
326 fn changed(self) -> bool {
327 self.changed
328 }
329
330 fn should_inline_for_callee(&self, _: DefId) -> bool {
331 true
332 }
333
334 fn check_codegen_attributes_extra(
335 &self,
336 callee_attrs: &CodegenFnAttrs,
337 ) -> Result<(), &'static str> {
338 if self.past_depth_limit() && matches!(callee_attrs.inline, InlineAttr::None) {
339 Err("Past depth limit so not inspecting unmarked callee")
340 } else {
341 Ok(())
342 }
343 }
344
345 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool {
346 body.coroutine.is_none()
350 }
351
352 #[instrument(level = "debug", skip(self, callee_body))]
353 fn check_callee_mir_body(
354 &self,
355 callsite: &CallSite<'tcx>,
356 callee_body: &Body<'tcx>,
357 callee_attrs: &CodegenFnAttrs,
358 ) -> Result<(), &'static str> {
359 let tcx = self.tcx();
360
361 if let Some(_) = callee_body.tainted_by_errors {
362 return Err("body has errors");
363 }
364
365 if self.past_depth_limit() && callee_body.basic_blocks.len() > 1 {
366 return Err("Not inlining multi-block body as we're past a depth limit");
367 }
368
369 let mut threshold = if self.caller_is_inline_forwarder || self.past_depth_limit() {
370 tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30)
371 } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) {
372 tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
373 } else {
374 tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
375 };
376
377 if callee_body.basic_blocks.len() <= 3 {
381 threshold += threshold / 4;
382 }
383 debug!(" final inline threshold = {}", threshold);
384
385 let mut checker =
388 CostChecker::new(tcx, self.typing_env(), Some(callsite.callee), callee_body);
389
390 checker.add_function_level_costs();
391
392 let mut work_list = vec![START_BLOCK];
394 let mut visited = DenseBitSet::new_empty(callee_body.basic_blocks.len());
395 while let Some(bb) = work_list.pop() {
396 if !visited.insert(bb.index()) {
397 continue;
398 }
399
400 let blk = &callee_body.basic_blocks[bb];
401 checker.visit_basic_block_data(bb, blk);
402
403 let term = blk.terminator();
404 let caller_attrs = tcx.codegen_fn_attrs(self.caller_def_id());
405 if let TerminatorKind::Drop { ref place, target, unwind, replace: _, drop: _ } =
406 term.kind
407 {
408 work_list.push(target);
409
410 let ty = callsite.callee.instantiate_mir(
412 tcx,
413 ty::EarlyBinder::bind(tcx, place.ty(callee_body, tcx).ty),
414 );
415 if ty.needs_drop(tcx, self.typing_env())
416 && let UnwindAction::Cleanup(unwind) = unwind
417 {
418 work_list.push(unwind);
419 }
420 } else if callee_attrs.instruction_set != caller_attrs.instruction_set
421 && matches!(term.kind, TerminatorKind::InlineAsm { .. })
422 {
423 return Err("cannot move inline-asm across instruction sets");
429 } else if let TerminatorKind::TailCall { .. } = term.kind {
430 return Err("can't inline functions with tail calls");
433 } else {
434 work_list.extend(term.successors())
435 }
436 }
437
438 let cost = checker.cost();
443 if cost <= threshold {
444 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
445 Ok(())
446 } else {
447 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
448 Err("cost above threshold")
449 }
450 }
451
452 fn on_inline_success(
453 &mut self,
454 callsite: &CallSite<'tcx>,
455 caller_body: &mut Body<'tcx>,
456 new_blocks: std::ops::Range<BasicBlock>,
457 ) {
458 self.changed = true;
459
460 let new_calls_count = new_blocks
461 .clone()
462 .filter(|&bb| is_call_like(caller_body.basic_blocks[bb].terminator()))
463 .count();
464 if new_calls_count > 1 {
465 self.top_down_counter += 1;
466 }
467
468 self.history.push(callsite.callee.def_id());
469 process_blocks(self, caller_body, new_blocks);
470 self.history.pop();
471
472 if self.history.is_empty() {
473 self.top_down_counter = 0;
474 }
475 }
476
477 fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {}
478}
479
480fn inline<'tcx, T: Inliner<'tcx>>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
481 let def_id = body.source.def_id();
482
483 if !tcx.hir_body_owner_kind(def_id).is_fn_or_closure() {
485 return false;
486 }
487
488 let mut inliner = T::new(tcx, def_id, body);
489 if !inliner.check_caller_mir_body(body) {
490 return false;
491 }
492
493 let blocks = START_BLOCK..body.basic_blocks.next_index();
494 process_blocks(&mut inliner, body, blocks);
495 inliner.changed()
496}
497
498fn process_blocks<'tcx, I: Inliner<'tcx>>(
499 inliner: &mut I,
500 caller_body: &mut Body<'tcx>,
501 blocks: Range<BasicBlock>,
502) {
503 for bb in blocks {
504 let bb_data = &caller_body[bb];
505 if bb_data.is_cleanup {
506 continue;
507 }
508
509 let Some(callsite) = resolve_callsite(inliner, caller_body, bb, bb_data) else {
510 continue;
511 };
512
513 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
514 let _guard = span.enter();
515
516 match try_inlining(inliner, caller_body, &callsite) {
517 Err(reason) => {
518 debug!("not-inlined {} [{}]", callsite.callee, reason);
519 inliner.on_inline_failure(&callsite, reason);
520 }
521 Ok(new_blocks) => {
522 debug!("inlined {}", callsite.callee);
523 inliner.on_inline_success(&callsite, caller_body, new_blocks);
524 }
525 }
526 }
527}
528
529fn resolve_callsite<'tcx, I: Inliner<'tcx>>(
530 inliner: &I,
531 caller_body: &Body<'tcx>,
532 bb: BasicBlock,
533 bb_data: &BasicBlockData<'tcx>,
534) -> Option<CallSite<'tcx>> {
535 let tcx = inliner.tcx();
536 let terminator = bb_data.terminator();
538
539 if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
541 let func_ty = func.ty(caller_body, tcx);
542 if let ty::FnDef(def_id, args) = *func_ty.kind() {
543 if !inliner.should_inline_for_callee(def_id) {
544 debug!("not enabled");
545 return None;
546 }
547
548 let args = tcx
550 .try_normalize_erasing_regions(inliner.typing_env(), Unnormalized::new_wip(args))
551 .ok()?
552 .no_bound_vars()
553 .unwrap();
554 let mut callee =
555 Instance::try_resolve(tcx, inliner.typing_env(), def_id, args).ok().flatten()?;
556
557 if let InstanceKind::Virtual(..) = callee.def {
558 return None;
559 }
560 if let InstanceKind::Intrinsic(..) = callee.def {
561 let intrinsic = tcx.intrinsic(def_id).unwrap();
562 if intrinsic.must_be_overridden {
563 return None; }
565 if !tcx.sess.fallback_intrinsics.contains(&intrinsic.name) {
566 return None; }
568 debug!("callsite is fallback body: {def_id:?}");
570 callee = ty::Instance { def: ty::InstanceKind::Item(def_id), args: callee.args };
571 }
572
573 if inliner.history().contains(&callee.def_id()) {
574 return None;
575 }
576
577 let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip();
578
579 if let InstanceKind::Item(instance_def_id) = callee.def
582 && tcx.def_kind(instance_def_id) == DefKind::AssocFn
583 && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
584 && instance_fn_sig.abi() != fn_sig.abi()
585 {
586 return None;
587 }
588
589 let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
590
591 return Some(CallSite { callee, fn_sig, block: bb, source_info });
592 }
593 }
594
595 None
596}
597
598fn try_inlining<'tcx, I: Inliner<'tcx>>(
602 inliner: &I,
603 caller_body: &mut Body<'tcx>,
604 callsite: &CallSite<'tcx>,
605) -> Result<std::ops::Range<BasicBlock>, &'static str> {
606 let tcx = inliner.tcx();
607 check_mir_is_available(inliner, caller_body, callsite.callee)?;
608
609 let callee_attrs = tcx.codegen_instance_attrs(callsite.callee.def);
610 let callee_attrs = callee_attrs.as_ref();
611 check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
612 check_codegen_attributes(inliner, callsite, callee_attrs)?;
613
614 let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
615 let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
616 let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
617 for arg in args {
618 if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
619 return Err("call has unsized argument");
622 }
623 }
624
625 let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
626 check_inline::is_inline_valid_on_body(tcx, callee_body)?;
627 inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
628
629 let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
630 tcx,
631 inliner.typing_env(),
632 ty::EarlyBinder::bind(tcx, callee_body.clone()),
633 ) else {
634 debug!("failed to normalize callee body");
635 return Err("implementation limitation -- could not normalize callee body");
636 };
637
638 if !validate_types(tcx, inliner.typing_env(), &callee_body, caller_body).is_empty() {
641 debug!("failed to validate callee body");
642 return Err("implementation limitation -- callee body failed validation");
643 }
644
645 let output_type = callee_body.return_ty();
649 if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
650 trace!(?output_type, ?destination_ty);
651 return Err("implementation limitation -- return type mismatch");
652 }
653 if callsite.fn_sig.abi() == ExternAbi::RustCall {
654 let (self_arg, arg_tuple) = match &args[..] {
655 [arg_tuple] => (None, arg_tuple),
656 [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
657 _ => bug!("Expected `rust-call` to have 1 or 2 args"),
658 };
659
660 let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
661
662 let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
663 let arg_tys = if callee_body.spread_arg.is_some() {
664 std::slice::from_ref(&arg_tuple_ty)
665 } else {
666 let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
667 bug!("Closure arguments are not passed as a tuple");
668 };
669 arg_tuple_tys.as_slice()
670 };
671
672 for (arg_ty, input) in
673 self_arg_ty.into_iter().chain(arg_tys.iter().copied()).zip(callee_body.args_iter())
674 {
675 let input_type = callee_body.local_decls[input].ty;
676 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
677 trace!(?arg_ty, ?input_type);
678 debug!("failed to normalize tuple argument type");
679 return Err("implementation limitation");
680 }
681 }
682 } else {
683 for (arg, input) in args.iter().zip(callee_body.args_iter()) {
684 let input_type = callee_body.local_decls[input].ty;
685 let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
686 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
687 trace!(?arg_ty, ?input_type);
688 debug!("failed to normalize argument type");
689 return Err("implementation limitation -- arg mismatch");
690 }
691 }
692 }
693
694 let old_blocks = caller_body.basic_blocks.next_index();
695 inline_call(inliner, caller_body, callsite, callee_body);
696 let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
697
698 Ok(new_blocks)
699}
700
701fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
702 inliner: &I,
703 caller_body: &Body<'tcx>,
704 callee: Instance<'tcx>,
705) -> Result<(), &'static str> {
706 let caller_def_id = caller_body.source.def_id();
707 let callee_def_id = callee.def_id();
708 if callee_def_id == caller_def_id {
709 return Err("self-recursion");
710 }
711
712 match callee.def {
713 InstanceKind::Item(_) => {
714 if !inliner.tcx().is_mir_available(callee_def_id) {
718 debug!("item MIR unavailable");
719 return Err("implementation limitation -- MIR unavailable");
720 }
721 }
722 InstanceKind::Intrinsic(_) | InstanceKind::LlvmIntrinsic(_) | InstanceKind::Virtual(..) => {
724 debug!("instance without MIR (intrinsic / virtual)");
725 return Err("implementation limitation -- cannot inline intrinsic");
726 }
727
728 InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty)))
734 if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) =>
735 {
736 debug!("still needs substitution");
737 return Err("implementation limitation -- HACK for dropping polymorphic type");
738 }
739 InstanceKind::Shim(ShimKind::AsyncDropGlue(_, ty))
740 | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)) => {
741 return if ty.still_further_specializable() {
742 Err("still needs substitution")
743 } else {
744 Ok(())
745 };
746 }
747 InstanceKind::Shim(ShimKind::FutureDropPoll(_, ty, ty2)) => {
748 return if ty.still_further_specializable() || ty2.still_further_specializable() {
749 Err("still needs substitution")
750 } else {
751 Ok(())
752 };
753 }
754
755 InstanceKind::Shim(ShimKind::VTable(_))
760 | InstanceKind::Shim(ShimKind::Reify(..))
761 | InstanceKind::Shim(ShimKind::FnPtr(..))
762 | InstanceKind::Shim(ShimKind::ClosureOnce { .. })
763 | InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure { .. })
764 | InstanceKind::Shim(ShimKind::DropGlue(..))
765 | InstanceKind::Shim(ShimKind::Clone(..))
766 | InstanceKind::Shim(ShimKind::ThreadLocal(..))
767 | InstanceKind::Shim(ShimKind::FnPtrAsPtr(..))
768 | InstanceKind::Shim(ShimKind::FnPtrFromPtr(..)) => return Ok(()),
769 }
770
771 if inliner.tcx().is_constructor(callee_def_id) {
772 trace!("constructors always have MIR");
773 return Ok(());
775 }
776
777 if let Some(callee_def_id) = callee_def_id.as_local()
778 && !inliner.tcx().is_lang_item(inliner.tcx().parent(caller_def_id), LangItem::FnOnce)
779 {
780 let Some(cyclic_callees) = inliner.tcx().mir_callgraph_cyclic(caller_def_id.expect_local())
783 else {
784 return Err("call graph cycle detection bailed due to recursion limit");
785 };
786 if cyclic_callees.contains(&callee_def_id) {
787 debug!("query cycle avoidance");
788 return Err("caller might be reachable from callee");
789 }
790
791 Ok(())
792 } else {
793 trace!("functions from other crates always have MIR");
798 Ok(())
799 }
800}
801
802fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
805 inliner: &I,
806 callsite: &CallSite<'tcx>,
807 callee_attrs: &CodegenFnAttrs,
808) -> Result<(), &'static str> {
809 let tcx = inliner.tcx();
810 if let InlineAttr::Never = callee_attrs.inline {
811 return Err("never inline attribute");
812 }
813
814 if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
815 return Err("has DoNotOptimize attribute");
816 }
817
818 inliner.check_codegen_attributes_extra(callee_attrs)?;
819
820 let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
823 if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
824 return Err("not exported");
825 }
826
827 let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
828 if callee_attrs.sanitizers != codegen_fn_attrs.sanitizers {
829 return Err("incompatible sanitizer set");
830 }
831
832 if callee_attrs.instruction_set.is_some()
836 && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
837 {
838 return Err("incompatible instruction set");
839 }
840
841 let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
842 let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
843 if callee_feature_names.ne(this_feature_names) {
844 return Err("incompatible target features");
850 }
851
852 Ok(())
853}
854
855fn inline_call<'tcx, I: Inliner<'tcx>>(
856 inliner: &I,
857 caller_body: &mut Body<'tcx>,
858 callsite: &CallSite<'tcx>,
859 mut callee_body: Body<'tcx>,
860) {
861 let tcx = inliner.tcx();
862 let terminator = caller_body[callsite.block].terminator.take().unwrap();
863 let TerminatorKind::Call { func, args, destination, unwind, target, .. } = terminator.kind
864 else {
865 bug!("unexpected terminator kind {:?}", terminator.kind);
866 };
867
868 let return_block = if let Some(block) = target {
869 let data = BasicBlockData::new(
872 Some(Terminator {
873 source_info: terminator.source_info,
874 kind: TerminatorKind::Goto { target: block },
875 attributes: ThinVec::new(),
876 }),
877 caller_body[block].is_cleanup,
878 );
879 Some(caller_body.basic_blocks_mut().push(data))
880 } else {
881 None
882 };
883
884 let dest = if !destination.is_stable_offset() {
894 trace!("creating temp for return destination");
895 let dest = Rvalue::RawPtr(RawPtrKind::Mut, destination);
896 let dest_ty = dest.ty(caller_body, tcx);
897 let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
898 caller_body[callsite.block].statements.push(Statement::new(
899 callsite.source_info,
900 StatementKind::Assign(Box::new((temp, dest))),
901 ));
902 tcx.mk_place_deref(temp)
903 } else {
904 destination
905 };
906
907 let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
910 (false, d)
911 } else {
912 (
913 true,
914 new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
915 )
916 };
917
918 let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
920
921 let mut integrator = Integrator {
922 args: &args,
923 new_locals: caller_body.local_decls.next_index()..,
924 new_scopes: caller_body.source_scopes.next_index()..,
925 new_blocks: caller_body.basic_blocks.next_index()..,
926 destination: destination_local,
927 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
928 callsite,
929 cleanup_block: unwind,
930 in_cleanup_block: false,
931 return_block,
932 tcx,
933 always_live_locals: UsedInStmtLocals::new(&callee_body).locals,
934 };
935
936 integrator.visit_body(&mut callee_body);
939
940 for local in callee_body.vars_and_temps_iter() {
943 if integrator.always_live_locals.contains(local) {
944 let new_local = integrator.map_local(local);
945 caller_body[callsite.block]
946 .statements
947 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(new_local)));
948 }
949 }
950 if let Some(block) = return_block {
951 let mut n = 0;
954 if remap_destination {
955 caller_body[block].statements.push(Statement::new(
956 callsite.source_info,
957 StatementKind::Assign(Box::new((
958 dest,
959 Rvalue::Use(Operand::Move(destination_local.into()), WithRetag::Yes),
960 ))),
961 ));
962 n += 1;
963 }
964 for local in callee_body.vars_and_temps_iter().rev() {
965 if integrator.always_live_locals.contains(local) {
966 let new_local = integrator.map_local(local);
967 caller_body[block].statements.push(Statement::new(
968 callsite.source_info,
969 StatementKind::StorageDead(new_local),
970 ));
971 n += 1;
972 }
973 }
974 caller_body[block].statements.rotate_right(n);
975 }
976
977 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
979 caller_body.source_scopes.append(&mut callee_body.source_scopes);
980
981 if tcx
983 .sess
984 .opts
985 .unstable_opts
986 .inline_mir_preserve_debug
987 .unwrap_or(tcx.sess.opts.debuginfo == DebugInfo::Full)
988 {
989 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
993 } else {
994 for bb in callee_body.basic_blocks_mut() {
995 bb.drop_debuginfo();
996 }
997 }
998 caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
999
1000 caller_body[callsite.block].terminator = Some(Terminator {
1001 source_info: callsite.source_info,
1002 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
1003 attributes: ThinVec::new(),
1004 });
1005
1006 caller_body.required_consts.as_mut().unwrap().extend(
1010 callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
1011 );
1012 let callee_item = MentionedItem::Fn(func.ty(caller_body, tcx));
1020 let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
1021 if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
1022 caller_mentioned_items.remove(idx);
1024 caller_mentioned_items.extend(callee_body.mentioned_items());
1025 } else {
1026 }
1030}
1031
1032fn make_call_args<'tcx, I: Inliner<'tcx>>(
1033 inliner: &I,
1034 args: Box<[Spanned<Operand<'tcx>>]>,
1035 callsite: &CallSite<'tcx>,
1036 caller_body: &mut Body<'tcx>,
1037 callee_body: &Body<'tcx>,
1038 return_block: Option<BasicBlock>,
1039) -> Box<[Local]> {
1040 let tcx = inliner.tcx();
1041
1042 if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1066 let mut args = args.into_iter();
1067 let self_ = create_temp_if_necessary(
1068 inliner,
1069 args.next().unwrap().node,
1070 callsite,
1071 caller_body,
1072 return_block,
1073 );
1074 let tuple = create_temp_if_necessary(
1075 inliner,
1076 args.next().unwrap().node,
1077 callsite,
1078 caller_body,
1079 return_block,
1080 );
1081 assert!(args.next().is_none());
1082
1083 let tuple = Place::from(tuple);
1084 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
1085 bug!("Closure arguments are not passed as a tuple");
1086 };
1087
1088 let closure_ref_arg = iter::once(self_);
1090
1091 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
1093 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
1095
1096 create_temp_if_necessary(inliner, tuple_field, callsite, caller_body, return_block)
1098 });
1099
1100 closure_ref_arg.chain(tuple_tmp_args).collect()
1101 } else {
1102 args.into_iter()
1103 .map(|a| create_temp_if_necessary(inliner, a.node, callsite, caller_body, return_block))
1104 .collect()
1105 }
1106}
1107
1108fn create_temp_if_necessary<'tcx, I: Inliner<'tcx>>(
1111 inliner: &I,
1112 arg: Operand<'tcx>,
1113 callsite: &CallSite<'tcx>,
1114 caller_body: &mut Body<'tcx>,
1115 return_block: Option<BasicBlock>,
1116) -> Local {
1117 if let Operand::Move(place) = &arg
1119 && let Some(local) = place.as_local()
1120 && caller_body.local_kind(local) == LocalKind::Temp
1121 {
1122 return local;
1123 }
1124
1125 trace!("creating temp for argument {:?}", arg);
1127 let arg_ty = arg.ty(caller_body, inliner.tcx());
1128 let local = new_call_temp(caller_body, callsite, arg_ty, return_block);
1129 caller_body[callsite.block].statements.push(Statement::new(
1130 callsite.source_info,
1131 StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg, WithRetag::Yes)))),
1132 ));
1133 local
1134}
1135
1136fn new_call_temp<'tcx>(
1138 caller_body: &mut Body<'tcx>,
1139 callsite: &CallSite<'tcx>,
1140 ty: Ty<'tcx>,
1141 return_block: Option<BasicBlock>,
1142) -> Local {
1143 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
1144
1145 caller_body[callsite.block]
1146 .statements
1147 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(local)));
1148
1149 if let Some(block) = return_block {
1150 caller_body[block]
1151 .statements
1152 .insert(0, Statement::new(callsite.source_info, StatementKind::StorageDead(local)));
1153 }
1154
1155 local
1156}
1157
1158struct Integrator<'a, 'tcx> {
1166 args: &'a [Local],
1167 new_locals: RangeFrom<Local>,
1168 new_scopes: RangeFrom<SourceScope>,
1169 new_blocks: RangeFrom<BasicBlock>,
1170 destination: Local,
1171 callsite_scope: SourceScopeData<'tcx>,
1172 callsite: &'a CallSite<'tcx>,
1173 cleanup_block: UnwindAction,
1174 in_cleanup_block: bool,
1175 return_block: Option<BasicBlock>,
1176 tcx: TyCtxt<'tcx>,
1177 always_live_locals: DenseBitSet<Local>,
1178}
1179
1180impl Integrator<'_, '_> {
1181 fn map_local(&self, local: Local) -> Local {
1182 let new = if local == RETURN_PLACE {
1183 self.destination
1184 } else {
1185 let idx = local.index() - 1;
1186 if idx < self.args.len() {
1187 self.args[idx]
1188 } else {
1189 self.new_locals.start + (idx - self.args.len())
1190 }
1191 };
1192 trace!("mapping local `{:?}` to `{:?}`", local, new);
1193 new
1194 }
1195
1196 fn map_scope(&self, scope: SourceScope) -> SourceScope {
1197 let new = self.new_scopes.start + scope.index();
1198 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
1199 new
1200 }
1201
1202 fn map_block(&self, block: BasicBlock) -> BasicBlock {
1203 let new = self.new_blocks.start + block.index();
1204 trace!("mapping block `{:?}` to `{:?}`", block, new);
1205 new
1206 }
1207
1208 fn map_unwind(&self, unwind: UnwindAction) -> UnwindAction {
1209 if self.in_cleanup_block {
1210 match unwind {
1211 UnwindAction::Cleanup(_) | UnwindAction::Continue => {
1212 bug!("cleanup on cleanup block");
1213 }
1214 UnwindAction::Unreachable | UnwindAction::Terminate(_) => return unwind,
1215 }
1216 }
1217
1218 match unwind {
1219 UnwindAction::Unreachable | UnwindAction::Terminate(_) => unwind,
1220 UnwindAction::Cleanup(target) => UnwindAction::Cleanup(self.map_block(target)),
1221 UnwindAction::Continue => self.cleanup_block,
1223 }
1224 }
1225}
1226
1227impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
1228 fn tcx(&self) -> TyCtxt<'tcx> {
1229 self.tcx
1230 }
1231
1232 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
1233 *local = self.map_local(*local);
1234 }
1235
1236 fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1237 self.super_source_scope_data(scope_data);
1238 if scope_data.parent_scope.is_none() {
1239 scope_data.parent_scope = Some(self.callsite.source_info.scope);
1242 assert_eq!(scope_data.inlined_parent_scope, None);
1243 scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1244 Some(self.callsite.source_info.scope)
1245 } else {
1246 self.callsite_scope.inlined_parent_scope
1247 };
1248
1249 assert_eq!(scope_data.inlined, None);
1251 scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1252 } else if scope_data.inlined_parent_scope.is_none() {
1253 scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1255 }
1256 }
1257
1258 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1259 *scope = self.map_scope(*scope);
1260 }
1261
1262 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1263 self.in_cleanup_block = data.is_cleanup;
1264 self.super_basic_block_data(block, data);
1265 self.in_cleanup_block = false;
1266 }
1267
1268 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1269 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1270 statement.kind
1271 {
1272 self.always_live_locals.remove(local);
1273 }
1274 self.super_statement(statement, location);
1275 }
1276
1277 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1278 if !matches!(terminator.kind, TerminatorKind::Return) {
1281 self.super_terminator(terminator, loc);
1282 } else {
1283 self.visit_source_info(&mut terminator.source_info);
1284 }
1285
1286 match terminator.kind {
1287 TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1288 TerminatorKind::Goto { ref mut target } => {
1289 *target = self.map_block(*target);
1290 }
1291 TerminatorKind::SwitchInt { ref mut targets, .. } => {
1292 for tgt in targets.all_targets_mut() {
1293 *tgt = self.map_block(*tgt);
1294 }
1295 }
1296 TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1297 *target = self.map_block(*target);
1298 *unwind = self.map_unwind(*unwind);
1299 }
1300 TerminatorKind::TailCall { .. } => {
1301 unreachable!()
1303 }
1304 TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1305 if let Some(ref mut tgt) = *target {
1306 *tgt = self.map_block(*tgt);
1307 }
1308 *unwind = self.map_unwind(*unwind);
1309 }
1310 TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1311 *target = self.map_block(*target);
1312 *unwind = self.map_unwind(*unwind);
1313 }
1314 TerminatorKind::Return => {
1315 terminator.kind = if let Some(tgt) = self.return_block {
1316 TerminatorKind::Goto { target: tgt }
1317 } else {
1318 TerminatorKind::Unreachable
1319 }
1320 }
1321 TerminatorKind::UnwindResume => {
1322 terminator.kind = match self.cleanup_block {
1323 UnwindAction::Cleanup(tgt) => TerminatorKind::Goto { target: tgt },
1324 UnwindAction::Continue => TerminatorKind::UnwindResume,
1325 UnwindAction::Unreachable => TerminatorKind::Unreachable,
1326 UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1327 };
1328 }
1329 TerminatorKind::UnwindTerminate(_) => {}
1330 TerminatorKind::Unreachable => {}
1331 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1332 *real_target = self.map_block(*real_target);
1333 *imaginary_target = self.map_block(*imaginary_target);
1334 }
1335 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1336 {
1338 bug!("False unwinds should have been removed before inlining")
1339 }
1340 TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1341 for tgt in targets.iter_mut() {
1342 *tgt = self.map_block(*tgt);
1343 }
1344 *unwind = self.map_unwind(*unwind);
1345 }
1346 }
1347 }
1348}
1349
1350#[instrument(skip(tcx), level = "debug")]
1351fn try_instance_mir<'tcx>(
1352 tcx: TyCtxt<'tcx>,
1353 instance: InstanceKind<'tcx>,
1354) -> Result<&'tcx Body<'tcx>, &'static str> {
1355 if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, Some(ty)))
1356 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, ty)) = instance
1357 && let ty::Adt(def, args) = ty.kind()
1358 {
1359 let fields = def.all_fields();
1360 for field in fields {
1361 let field_ty = field.ty(tcx, args);
1362 if field_ty.has_param() && field_ty.has_aliases() {
1363 return Err("cannot build drop shim for polymorphic type");
1364 }
1365 }
1366 }
1367 Ok(tcx.instance_mir(instance))
1368}
1369
1370fn body_is_forwarder(body: &Body<'_>) -> bool {
1371 let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1372 else {
1373 return false;
1374 };
1375 if let Some(target) = target {
1376 let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1377 return false;
1378 };
1379 }
1380
1381 let max_blocks = if !body.is_polymorphic {
1382 2
1383 } else if target.is_none() {
1384 3
1385 } else {
1386 4
1387 };
1388 if body.basic_blocks.len() > max_blocks {
1389 return false;
1390 }
1391
1392 body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1393 bb == START_BLOCK
1394 || matches!(
1395 bb_data.terminator().kind,
1396 TerminatorKind::Return
1397 | TerminatorKind::Drop { .. }
1398 | TerminatorKind::UnwindResume
1399 | TerminatorKind::UnwindTerminate(_)
1400 )
1401 })
1402}