1use std::ops::{Range, RangeFrom};
4use std::{debug_assert_matches, iter};
5
6use rustc_abi::{ExternAbi, FieldIdx};
7use rustc_attr_ir::lang_items::LangItem;
8use rustc_attr_ir::{InlineAttr, OptimizeAttr};
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::DefId;
11use rustc_index::Idx;
12use rustc_index::bit_set::DenseBitSet;
13use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
14use rustc_middle::mir::visit::*;
15use rustc_middle::mir::*;
16use rustc_middle::ty::{
17 self, Instance, InstanceKind, Intrinsic, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt,
18 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 match intrinsic.name {
566 Intrinsic::Rustc(name)
568 if !tcx.sess.fallback_rustc_intrinsics.contains(&name) =>
569 {
570 return None;
571 }
572 Intrinsic::Backend { .. } => {
573 return None;
574 }
575 _ => {}
576 }
577 debug!("callsite is fallback body: {def_id:?}");
579 callee = ty::Instance { def: ty::InstanceKind::Item(def_id), args: callee.args };
580 }
581
582 if inliner.history().contains(&callee.def_id()) {
583 return None;
584 }
585
586 let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip();
587
588 if let InstanceKind::Item(instance_def_id) = callee.def
591 && tcx.def_kind(instance_def_id) == DefKind::AssocFn
592 && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
593 && instance_fn_sig.abi() != fn_sig.abi()
594 {
595 return None;
596 }
597
598 let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
599
600 return Some(CallSite { callee, fn_sig, block: bb, source_info });
601 }
602 }
603
604 None
605}
606
607fn try_inlining<'tcx, I: Inliner<'tcx>>(
611 inliner: &I,
612 caller_body: &mut Body<'tcx>,
613 callsite: &CallSite<'tcx>,
614) -> Result<std::ops::Range<BasicBlock>, &'static str> {
615 let tcx = inliner.tcx();
616 check_mir_is_available(inliner, caller_body, callsite.callee)?;
617
618 let callee_attrs = tcx.codegen_instance_attrs(callsite.callee.def);
619 let callee_attrs = callee_attrs.as_ref();
620 check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
621 check_codegen_attributes(inliner, callsite, callee_attrs)?;
622
623 let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
624 let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
625 let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
626 for arg in args {
627 if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
628 return Err("call has unsized argument");
631 }
632 }
633
634 let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
635 check_inline::is_inline_valid_on_body(tcx, callee_body)?;
636 inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
637
638 let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
639 tcx,
640 inliner.typing_env(),
641 ty::EarlyBinder::bind(tcx, callee_body.clone()),
642 ) else {
643 debug!("failed to normalize callee body");
644 return Err("implementation limitation -- could not normalize callee body");
645 };
646
647 if !validate_types(tcx, inliner.typing_env(), &callee_body, caller_body).is_empty() {
650 debug!("failed to validate callee body");
651 return Err("implementation limitation -- callee body failed validation");
652 }
653
654 let output_type = callee_body.return_ty();
658 if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
659 trace!(?output_type, ?destination_ty);
660 return Err("implementation limitation -- return type mismatch");
661 }
662 if callsite.fn_sig.abi() == ExternAbi::RustCall {
663 let (self_arg, arg_tuple) = match &args[..] {
664 [arg_tuple] => (None, arg_tuple),
665 [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
666 _ => bug!("Expected `rust-call` to have 1 or 2 args"),
667 };
668
669 let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
670
671 let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
672 let arg_tys = if callee_body.spread_arg.is_some() {
673 std::slice::from_ref(&arg_tuple_ty)
674 } else {
675 let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
676 bug!("Closure arguments are not passed as a tuple");
677 };
678 arg_tuple_tys.as_slice()
679 };
680
681 for (arg_ty, input) in
682 self_arg_ty.into_iter().chain(arg_tys.iter().copied()).zip(callee_body.args_iter())
683 {
684 let input_type = callee_body.local_decls[input].ty;
685 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
686 trace!(?arg_ty, ?input_type);
687 debug!("failed to normalize tuple argument type");
688 return Err("implementation limitation");
689 }
690 }
691 } else {
692 for (arg, input) in args.iter().zip(callee_body.args_iter()) {
693 let input_type = callee_body.local_decls[input].ty;
694 let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
695 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
696 trace!(?arg_ty, ?input_type);
697 debug!("failed to normalize argument type");
698 return Err("implementation limitation -- arg mismatch");
699 }
700 }
701 }
702
703 let old_blocks = caller_body.basic_blocks.next_index();
704 inline_call(inliner, caller_body, callsite, callee_body);
705 let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
706
707 Ok(new_blocks)
708}
709
710fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
711 inliner: &I,
712 caller_body: &Body<'tcx>,
713 callee: Instance<'tcx>,
714) -> Result<(), &'static str> {
715 let caller_def_id = caller_body.source.def_id();
716 let callee_def_id = callee.def_id();
717 if callee_def_id == caller_def_id {
718 return Err("self-recursion");
719 }
720
721 match callee.def {
722 InstanceKind::Item(_) => {
723 if !inliner.tcx().is_mir_available(callee_def_id) {
727 debug!("item MIR unavailable");
728 return Err("implementation limitation -- MIR unavailable");
729 }
730 }
731 InstanceKind::Intrinsic(_) | InstanceKind::LlvmIntrinsic(_) | InstanceKind::Virtual(..) => {
733 debug!("instance without MIR (intrinsic / virtual)");
734 return Err("implementation limitation -- cannot inline intrinsic");
735 }
736
737 InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty)))
743 if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) =>
744 {
745 debug!("still needs substitution");
746 return Err("implementation limitation -- HACK for dropping polymorphic type");
747 }
748 InstanceKind::Shim(ShimKind::AsyncDropGlue(_, ty))
749 | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)) => {
750 return if ty.still_further_specializable() {
751 Err("still needs substitution")
752 } else {
753 Ok(())
754 };
755 }
756 InstanceKind::Shim(ShimKind::FutureDropPoll(_, ty, ty2)) => {
757 return if ty.still_further_specializable() || ty2.still_further_specializable() {
758 Err("still needs substitution")
759 } else {
760 Ok(())
761 };
762 }
763
764 InstanceKind::Shim(ShimKind::VTable(_))
769 | InstanceKind::Shim(ShimKind::Reify(..))
770 | InstanceKind::Shim(ShimKind::FnPtr(..))
771 | InstanceKind::Shim(ShimKind::ClosureOnce { .. })
772 | InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure { .. })
773 | InstanceKind::Shim(ShimKind::DropGlue(..))
774 | InstanceKind::Shim(ShimKind::Clone(..))
775 | InstanceKind::Shim(ShimKind::ThreadLocal(..))
776 | InstanceKind::Shim(ShimKind::FnAddrAsPtr(..))
777 | InstanceKind::Shim(ShimKind::FnPtrFromPtr(..)) => return Ok(()),
778 }
779
780 if inliner.tcx().is_constructor(callee_def_id) {
781 trace!("constructors always have MIR");
782 return Ok(());
784 }
785
786 if let Some(callee_def_id) = callee_def_id.as_local()
787 && !inliner.tcx().is_lang_item(inliner.tcx().parent(caller_def_id), LangItem::FnOnce)
788 {
789 let Some(cyclic_callees) = inliner.tcx().mir_callgraph_cyclic(caller_def_id.expect_local())
792 else {
793 return Err("call graph cycle detection bailed due to recursion limit");
794 };
795 if cyclic_callees.contains(&callee_def_id) {
796 debug!("query cycle avoidance");
797 return Err("caller might be reachable from callee");
798 }
799
800 Ok(())
801 } else {
802 trace!("functions from other crates always have MIR");
807 Ok(())
808 }
809}
810
811fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
814 inliner: &I,
815 callsite: &CallSite<'tcx>,
816 callee_attrs: &CodegenFnAttrs,
817) -> Result<(), &'static str> {
818 let tcx = inliner.tcx();
819 if let InlineAttr::Never = callee_attrs.inline {
820 return Err("never inline attribute");
821 }
822
823 if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
824 return Err("has DoNotOptimize attribute");
825 }
826
827 inliner.check_codegen_attributes_extra(callee_attrs)?;
828
829 let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
832 if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
833 return Err("not exported");
834 }
835
836 let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
837 if callee_attrs.sanitizers != codegen_fn_attrs.sanitizers {
838 return Err("incompatible sanitizer set");
839 }
840
841 if callee_attrs.instruction_set.is_some()
845 && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
846 {
847 return Err("incompatible instruction set");
848 }
849
850 let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
851 let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
852 if callee_feature_names.ne(this_feature_names) {
853 return Err("incompatible target features");
859 }
860
861 Ok(())
862}
863
864fn inline_call<'tcx, I: Inliner<'tcx>>(
865 inliner: &I,
866 caller_body: &mut Body<'tcx>,
867 callsite: &CallSite<'tcx>,
868 mut callee_body: Body<'tcx>,
869) {
870 let tcx = inliner.tcx();
871 let terminator = caller_body.basic_blocks.as_mut()[callsite.block].terminator.as_mut().unwrap();
872 let TerminatorKind::Call { ref func, ref mut args, destination, unwind, target, .. } =
873 terminator.kind
874 else {
875 bug!("unexpected terminator kind {:?}", terminator.kind);
876 };
877 let args = std::mem::take(args);
878 let func_ty = func.ty(&caller_body.local_decls, tcx);
879
880 let return_block = if let Some(block) = target {
881 let data = BasicBlockData::new(
884 Terminator { source_info: terminator.source_info, kind: TerminatorKind::goto(block) },
885 caller_body[block].is_cleanup,
886 );
887 Some(caller_body.basic_blocks_mut().push(data))
888 } else {
889 None
890 };
891
892 let dest = if !destination.is_stable_offset() {
902 trace!("creating temp for return destination");
903 let dest = Rvalue::RawPtr(RawPtrKind::Mut, destination);
904 let dest_ty = dest.ty(caller_body, tcx);
905 let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
906 caller_body[callsite.block].statements.push(Statement::new(
907 callsite.source_info,
908 StatementKind::Assign(Box::new((temp, dest))),
909 ));
910 tcx.mk_place_deref(temp)
911 } else {
912 destination
913 };
914
915 let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
918 (false, d)
919 } else {
920 (
921 true,
922 new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
923 )
924 };
925
926 let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
928
929 let mut integrator = Integrator {
930 args: &args,
931 new_locals: caller_body.local_decls.next_index()..,
932 new_scopes: caller_body.source_scopes.next_index()..,
933 new_blocks: caller_body.basic_blocks.next_index()..,
934 destination: destination_local,
935 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
936 callsite,
937 cleanup_block: unwind,
938 in_cleanup_block: false,
939 return_block,
940 tcx,
941 always_live_locals: UsedInStmtLocals::new(&callee_body).locals,
942 };
943
944 integrator.visit_body(&mut callee_body);
947
948 for local in callee_body.vars_and_temps_iter() {
951 if integrator.always_live_locals.contains(local) {
952 let new_local = integrator.map_local(local);
953 caller_body[callsite.block]
954 .statements
955 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(new_local)));
956 }
957 }
958 if let Some(block) = return_block {
959 let mut n = 0;
962 if remap_destination {
963 caller_body[block].statements.push(Statement::new(
964 callsite.source_info,
965 StatementKind::Assign(Box::new((
966 dest,
967 Rvalue::Use(Operand::Move(destination_local.into()), WithRetag::Yes),
968 ))),
969 ));
970 n += 1;
971 }
972 for local in callee_body.vars_and_temps_iter().rev() {
973 if integrator.always_live_locals.contains(local) {
974 let new_local = integrator.map_local(local);
975 caller_body[block].statements.push(Statement::new(
976 callsite.source_info,
977 StatementKind::StorageDead(new_local),
978 ));
979 n += 1;
980 }
981 }
982 caller_body[block].statements.rotate_right(n);
983 }
984
985 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
987 caller_body.source_scopes.append(&mut callee_body.source_scopes);
988
989 if tcx
991 .sess
992 .opts
993 .unstable_opts
994 .inline_mir_preserve_debug
995 .unwrap_or(tcx.sess.opts.debuginfo == DebugInfo::Full)
996 {
997 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
1001 } else {
1002 for bb in callee_body.basic_blocks_mut() {
1003 bb.drop_debuginfo();
1004 }
1005 }
1006 caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
1007
1008 caller_body[callsite.block].terminator = Some(Terminator {
1009 source_info: callsite.source_info,
1010 kind: TerminatorKind::goto(integrator.map_block(START_BLOCK)),
1011 });
1012
1013 caller_body.required_consts.as_mut().unwrap().extend(
1017 callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
1018 );
1019 let callee_item = MentionedItem::Fn(func_ty);
1027 let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
1028 if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
1029 caller_mentioned_items.remove(idx);
1031 caller_mentioned_items.extend(callee_body.mentioned_items());
1032 } else {
1033 }
1037}
1038
1039fn make_call_args<'tcx, I: Inliner<'tcx>>(
1040 inliner: &I,
1041 args: Box<[Spanned<Operand<'tcx>>]>,
1042 callsite: &CallSite<'tcx>,
1043 caller_body: &mut Body<'tcx>,
1044 callee_body: &Body<'tcx>,
1045 return_block: Option<BasicBlock>,
1046) -> Box<[Local]> {
1047 let tcx = inliner.tcx();
1048
1049 if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1073 let mut args = args.into_iter();
1074 let self_ = create_temp_if_necessary(
1075 inliner,
1076 args.next().unwrap().node,
1077 callsite,
1078 caller_body,
1079 return_block,
1080 );
1081 let tuple = create_temp_if_necessary(
1082 inliner,
1083 args.next().unwrap().node,
1084 callsite,
1085 caller_body,
1086 return_block,
1087 );
1088 assert!(args.next().is_none());
1089
1090 let tuple = Place::from(tuple);
1091 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
1092 bug!("Closure arguments are not passed as a tuple");
1093 };
1094
1095 let closure_ref_arg = iter::once(self_);
1097
1098 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
1100 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
1102
1103 create_temp_if_necessary(inliner, tuple_field, callsite, caller_body, return_block)
1105 });
1106
1107 closure_ref_arg.chain(tuple_tmp_args).collect()
1108 } else {
1109 args.into_iter()
1110 .map(|a| create_temp_if_necessary(inliner, a.node, callsite, caller_body, return_block))
1111 .collect()
1112 }
1113}
1114
1115fn create_temp_if_necessary<'tcx, I: Inliner<'tcx>>(
1118 inliner: &I,
1119 arg: Operand<'tcx>,
1120 callsite: &CallSite<'tcx>,
1121 caller_body: &mut Body<'tcx>,
1122 return_block: Option<BasicBlock>,
1123) -> Local {
1124 if let Operand::Move(place) = &arg
1126 && let Some(local) = place.as_local()
1127 && caller_body.local_kind(local) == LocalKind::Temp
1128 {
1129 return local;
1130 }
1131
1132 trace!("creating temp for argument {:?}", arg);
1134 let arg_ty = arg.ty(caller_body, inliner.tcx());
1135 let local = new_call_temp(caller_body, callsite, arg_ty, return_block);
1136 caller_body[callsite.block].statements.push(Statement::new(
1137 callsite.source_info,
1138 StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg, WithRetag::Yes)))),
1139 ));
1140 local
1141}
1142
1143fn new_call_temp<'tcx>(
1145 caller_body: &mut Body<'tcx>,
1146 callsite: &CallSite<'tcx>,
1147 ty: Ty<'tcx>,
1148 return_block: Option<BasicBlock>,
1149) -> Local {
1150 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
1151
1152 caller_body[callsite.block]
1153 .statements
1154 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(local)));
1155
1156 if let Some(block) = return_block {
1157 caller_body[block]
1158 .statements
1159 .insert(0, Statement::new(callsite.source_info, StatementKind::StorageDead(local)));
1160 }
1161
1162 local
1163}
1164
1165struct Integrator<'a, 'tcx> {
1173 args: &'a [Local],
1174 new_locals: RangeFrom<Local>,
1175 new_scopes: RangeFrom<SourceScope>,
1176 new_blocks: RangeFrom<BasicBlock>,
1177 destination: Local,
1178 callsite_scope: SourceScopeData<'tcx>,
1179 callsite: &'a CallSite<'tcx>,
1180 cleanup_block: UnwindAction,
1181 in_cleanup_block: bool,
1182 return_block: Option<BasicBlock>,
1183 tcx: TyCtxt<'tcx>,
1184 always_live_locals: DenseBitSet<Local>,
1185}
1186
1187impl Integrator<'_, '_> {
1188 fn map_local(&self, local: Local) -> Local {
1189 let new = if local == RETURN_PLACE {
1190 self.destination
1191 } else {
1192 let idx = local.index() - 1;
1193 if idx < self.args.len() {
1194 self.args[idx]
1195 } else {
1196 self.new_locals.start + (idx - self.args.len())
1197 }
1198 };
1199 trace!("mapping local `{:?}` to `{:?}`", local, new);
1200 new
1201 }
1202
1203 fn map_scope(&self, scope: SourceScope) -> SourceScope {
1204 let new = self.new_scopes.start + scope.index();
1205 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
1206 new
1207 }
1208
1209 fn map_block(&self, block: BasicBlock) -> BasicBlock {
1210 let new = self.new_blocks.start + block.index();
1211 trace!("mapping block `{:?}` to `{:?}`", block, new);
1212 new
1213 }
1214
1215 fn map_unwind(&self, unwind: UnwindAction) -> UnwindAction {
1216 if self.in_cleanup_block {
1217 match unwind {
1218 UnwindAction::Cleanup(_) | UnwindAction::Continue => {
1219 bug!("cleanup on cleanup block");
1220 }
1221 UnwindAction::Unreachable | UnwindAction::Terminate(_) => return unwind,
1222 }
1223 }
1224
1225 match unwind {
1226 UnwindAction::Unreachable | UnwindAction::Terminate(_) => unwind,
1227 UnwindAction::Cleanup(target) => UnwindAction::Cleanup(self.map_block(target)),
1228 UnwindAction::Continue => self.cleanup_block,
1230 }
1231 }
1232}
1233
1234impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
1235 fn tcx(&self) -> TyCtxt<'tcx> {
1236 self.tcx
1237 }
1238
1239 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
1240 *local = self.map_local(*local);
1241 }
1242
1243 fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1244 self.super_source_scope_data(scope_data);
1245 if scope_data.parent_scope.is_none() {
1246 scope_data.parent_scope = Some(self.callsite.source_info.scope);
1249 assert_eq!(scope_data.inlined_parent_scope, None);
1250 scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1251 Some(self.callsite.source_info.scope)
1252 } else {
1253 self.callsite_scope.inlined_parent_scope
1254 };
1255
1256 assert_eq!(scope_data.inlined, None);
1258 scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1259 } else if scope_data.inlined_parent_scope.is_none() {
1260 scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1262 }
1263 }
1264
1265 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1266 *scope = self.map_scope(*scope);
1267 }
1268
1269 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1270 self.in_cleanup_block = data.is_cleanup;
1271 self.super_basic_block_data(block, data);
1272 self.in_cleanup_block = false;
1273 }
1274
1275 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1276 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1277 statement.kind
1278 {
1279 self.always_live_locals.remove(local);
1280 }
1281 self.super_statement(statement, location);
1282 }
1283
1284 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1285 if !matches!(terminator.kind, TerminatorKind::Return) {
1288 self.super_terminator(terminator, loc);
1289 } else {
1290 self.visit_source_info(&mut terminator.source_info);
1291 }
1292
1293 match terminator.kind {
1294 TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1295 TerminatorKind::Goto { ref mut target, .. } => {
1296 *target = self.map_block(*target);
1297 }
1298 TerminatorKind::SwitchInt { ref mut targets, .. } => {
1299 for tgt in targets.all_targets_mut() {
1300 *tgt = self.map_block(*tgt);
1301 }
1302 }
1303 TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1304 *target = self.map_block(*target);
1305 *unwind = self.map_unwind(*unwind);
1306 }
1307 TerminatorKind::TailCall { .. } => {
1308 unreachable!()
1310 }
1311 TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1312 if let Some(ref mut tgt) = *target {
1313 *tgt = self.map_block(*tgt);
1314 }
1315 *unwind = self.map_unwind(*unwind);
1316 }
1317 TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1318 *target = self.map_block(*target);
1319 *unwind = self.map_unwind(*unwind);
1320 }
1321 TerminatorKind::Return => {
1322 terminator.kind = if let Some(tgt) = self.return_block {
1323 TerminatorKind::goto(tgt)
1324 } else {
1325 TerminatorKind::Unreachable
1326 }
1327 }
1328 TerminatorKind::UnwindResume => {
1329 terminator.kind = match self.cleanup_block {
1330 UnwindAction::Cleanup(tgt) => TerminatorKind::goto(tgt),
1331 UnwindAction::Continue => TerminatorKind::UnwindResume,
1332 UnwindAction::Unreachable => TerminatorKind::Unreachable,
1333 UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1334 };
1335 }
1336 TerminatorKind::UnwindTerminate(_) => {}
1337 TerminatorKind::Unreachable => {}
1338 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1339 *real_target = self.map_block(*real_target);
1340 *imaginary_target = self.map_block(*imaginary_target);
1341 }
1342 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1343 {
1345 bug!("False unwinds should have been removed before inlining")
1346 }
1347 TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1348 for tgt in targets.iter_mut() {
1349 *tgt = self.map_block(*tgt);
1350 }
1351 *unwind = self.map_unwind(*unwind);
1352 }
1353 }
1354 }
1355}
1356
1357#[instrument(skip(tcx), level = "debug")]
1358fn try_instance_mir<'tcx>(
1359 tcx: TyCtxt<'tcx>,
1360 instance: InstanceKind<'tcx>,
1361) -> Result<&'tcx Body<'tcx>, &'static str> {
1362 if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, Some(ty)))
1363 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, ty)) = instance
1364 && let ty::Adt(def, args) = ty.kind()
1365 {
1366 let fields = def.all_fields();
1367 for field in fields {
1368 let field_ty = field.ty(tcx, *args);
1369 if field_ty.has_param() && field_ty.has_aliases() {
1370 return Err("cannot build drop shim for polymorphic type");
1371 }
1372 }
1373 }
1374 Ok(tcx.instance_mir(instance))
1375}
1376
1377fn body_is_forwarder(body: &Body<'_>) -> bool {
1378 let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1379 else {
1380 return false;
1381 };
1382 if let Some(target) = target {
1383 let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1384 return false;
1385 };
1386 }
1387
1388 let max_blocks = if !body.is_polymorphic {
1389 2
1390 } else if target.is_none() {
1391 3
1392 } else {
1393 4
1394 };
1395 if body.basic_blocks.len() > max_blocks {
1396 return false;
1397 }
1398
1399 body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1400 bb == START_BLOCK
1401 || matches!(
1402 bb_data.terminator().kind,
1403 TerminatorKind::Return
1404 | TerminatorKind::Drop { .. }
1405 | TerminatorKind::UnwindResume
1406 | TerminatorKind::UnwindTerminate(_)
1407 )
1408 })
1409}