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::{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::bug;
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;
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::{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 is_enabled(&self, sess: &rustc_session::Session) -> bool {
48 if let Some(enabled) = sess.opts.unstable_opts.inline_mir {
49 return enabled;
50 }
51
52 match sess.mir_opt_level() {
53 0 | 1 => false,
54 2 => {
55 (sess.opts.optimize == OptLevel::More || sess.opts.optimize == OptLevel::Aggressive)
56 && sess.opts.incremental == None
57 }
58 _ => true,
59 }
60 }
61
62 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
63 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
64 let _guard = span.enter();
65 if inline::<NormalInliner<'tcx>>(tcx, body) {
66 debug!("running simplify cfg on {:?}", body.source);
67 simplify_cfg(tcx, body);
68 }
69 }
70
71 fn is_required(&self) -> bool {
72 false
73 }
74}
75
76pub struct ForceInline;
77
78impl ForceInline {
79 pub fn should_run_pass_for_callee<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
80 matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
81 }
82}
83
84impl<'tcx> crate::MirPass<'tcx> for ForceInline {
85 fn is_enabled(&self, _: &rustc_session::Session) -> bool {
86 true
87 }
88
89 fn can_be_overridden(&self) -> bool {
90 false
91 }
92
93 fn is_required(&self) -> bool {
94 true
95 }
96
97 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
98 let span = trace_span!("force_inline", body = %tcx.def_path_str(body.source.def_id()));
99 let _guard = span.enter();
100 if inline::<ForceInliner<'tcx>>(tcx, body) {
101 debug!("running simplify cfg on {:?}", body.source);
102 simplify_cfg(tcx, body);
103 }
104 }
105}
106
107trait Inliner<'tcx> {
108 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self;
109
110 fn tcx(&self) -> TyCtxt<'tcx>;
111 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
112 fn history(&self) -> &[DefId];
113 fn caller_def_id(&self) -> DefId;
114
115 fn changed(self) -> bool;
117
118 fn should_inline_for_callee(&self, def_id: DefId) -> bool;
120
121 fn check_codegen_attributes_extra(
122 &self,
123 callee_attrs: &CodegenFnAttrs,
124 ) -> Result<(), &'static str>;
125
126 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool;
127
128 fn check_callee_mir_body(
131 &self,
132 callsite: &CallSite<'tcx>,
133 callee_body: &Body<'tcx>,
134 callee_attrs: &CodegenFnAttrs,
135 ) -> Result<(), &'static str>;
136
137 fn on_inline_success(
139 &mut self,
140 callsite: &CallSite<'tcx>,
141 caller_body: &mut Body<'tcx>,
142 new_blocks: std::ops::Range<BasicBlock>,
143 );
144
145 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str);
147}
148
149struct ForceInliner<'tcx> {
150 tcx: TyCtxt<'tcx>,
151 typing_env: ty::TypingEnv<'tcx>,
152 def_id: DefId,
154 history: Vec<DefId>,
160 changed: bool,
162}
163
164impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> {
165 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
166 Self { tcx, typing_env: body.typing_env(tcx), def_id, history: Vec::new(), changed: false }
167 }
168
169 fn tcx(&self) -> TyCtxt<'tcx> {
170 self.tcx
171 }
172
173 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
174 self.typing_env
175 }
176
177 fn history(&self) -> &[DefId] {
178 &self.history
179 }
180
181 fn caller_def_id(&self) -> DefId {
182 self.def_id
183 }
184
185 fn changed(self) -> bool {
186 self.changed
187 }
188
189 fn should_inline_for_callee(&self, def_id: DefId) -> bool {
190 ForceInline::should_run_pass_for_callee(self.tcx(), def_id)
191 }
192
193 fn check_codegen_attributes_extra(
194 &self,
195 callee_attrs: &CodegenFnAttrs,
196 ) -> Result<(), &'static str> {
197 debug_assert_matches!(callee_attrs.inline, InlineAttr::Force { .. });
198 Ok(())
199 }
200
201 fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool {
202 true
203 }
204
205 #[instrument(level = "debug", skip(self, callee_body))]
206 fn check_callee_mir_body(
207 &self,
208 _: &CallSite<'tcx>,
209 callee_body: &Body<'tcx>,
210 callee_attrs: &CodegenFnAttrs,
211 ) -> Result<(), &'static str> {
212 if callee_body.tainted_by_errors.is_some() {
213 return Err("body has errors");
214 }
215
216 let caller_attrs = self.tcx().codegen_fn_attrs(self.caller_def_id());
217 if callee_attrs.instruction_set != caller_attrs.instruction_set
218 && callee_body
219 .basic_blocks
220 .iter()
221 .any(|bb| matches!(bb.terminator().kind, TerminatorKind::InlineAsm { .. }))
222 {
223 Err("cannot move inline-asm across instruction sets")
229 } else {
230 Ok(())
231 }
232 }
233
234 fn on_inline_success(
235 &mut self,
236 callsite: &CallSite<'tcx>,
237 caller_body: &mut Body<'tcx>,
238 new_blocks: std::ops::Range<BasicBlock>,
239 ) {
240 self.changed = true;
241
242 self.history.push(callsite.callee.def_id());
243 process_blocks(self, caller_body, new_blocks);
244 self.history.pop();
245 }
246
247 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str) {
248 let tcx = self.tcx();
249 let InlineAttr::Force { attr_span, reason: justification } =
250 tcx.codegen_instance_attrs(callsite.callee.def).inline
251 else {
252 bug!("called on item without required inlining");
253 };
254
255 let call_span = callsite.source_info.span;
256 let callee = tcx.def_path_str(callsite.callee.def_id());
257 tcx.dcx().emit_err(crate::diagnostics::ForceInlineFailure {
258 call_span,
259 attr_span,
260 caller_span: tcx.def_span(self.def_id),
261 caller: tcx.def_path_str(self.def_id),
262 callee_span: tcx.def_span(callsite.callee.def_id()),
263 callee: callee.clone(),
264 reason,
265 justification: justification
266 .map(|sym| crate::diagnostics::ForceInlineJustification { sym, callee }),
267 });
268 }
269}
270
271struct NormalInliner<'tcx> {
272 tcx: TyCtxt<'tcx>,
273 typing_env: ty::TypingEnv<'tcx>,
274 def_id: DefId,
276 history: Vec<DefId>,
282 top_down_counter: usize,
286 changed: bool,
288 caller_is_inline_forwarder: bool,
291}
292
293impl<'tcx> NormalInliner<'tcx> {
294 fn past_depth_limit(&self) -> bool {
295 self.history.len() > HISTORY_DEPTH_LIMIT || self.top_down_counter > TOP_DOWN_DEPTH_LIMIT
296 }
297}
298
299impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> {
300 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
301 let typing_env = body.typing_env(tcx);
302 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
303
304 Self {
305 tcx,
306 typing_env,
307 def_id,
308 history: Vec::new(),
309 top_down_counter: 0,
310 changed: false,
311 caller_is_inline_forwarder: matches!(
312 codegen_fn_attrs.inline,
313 InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. }
314 ) && body_is_forwarder(body),
315 }
316 }
317
318 fn tcx(&self) -> TyCtxt<'tcx> {
319 self.tcx
320 }
321
322 fn caller_def_id(&self) -> DefId {
323 self.def_id
324 }
325
326 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
327 self.typing_env
328 }
329
330 fn history(&self) -> &[DefId] {
331 &self.history
332 }
333
334 fn changed(self) -> bool {
335 self.changed
336 }
337
338 fn should_inline_for_callee(&self, _: DefId) -> bool {
339 true
340 }
341
342 fn check_codegen_attributes_extra(
343 &self,
344 callee_attrs: &CodegenFnAttrs,
345 ) -> Result<(), &'static str> {
346 if self.past_depth_limit() && matches!(callee_attrs.inline, InlineAttr::None) {
347 Err("Past depth limit so not inspecting unmarked callee")
348 } else {
349 Ok(())
350 }
351 }
352
353 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool {
354 if body.coroutine.is_some() {
358 return false;
359 }
360
361 true
362 }
363
364 #[instrument(level = "debug", skip(self, callee_body))]
365 fn check_callee_mir_body(
366 &self,
367 callsite: &CallSite<'tcx>,
368 callee_body: &Body<'tcx>,
369 callee_attrs: &CodegenFnAttrs,
370 ) -> Result<(), &'static str> {
371 let tcx = self.tcx();
372
373 if let Some(_) = callee_body.tainted_by_errors {
374 return Err("body has errors");
375 }
376
377 if self.past_depth_limit() && callee_body.basic_blocks.len() > 1 {
378 return Err("Not inlining multi-block body as we're past a depth limit");
379 }
380
381 let mut threshold = if self.caller_is_inline_forwarder || self.past_depth_limit() {
382 tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30)
383 } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) {
384 tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
385 } else {
386 tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
387 };
388
389 if callee_body.basic_blocks.len() <= 3 {
393 threshold += threshold / 4;
394 }
395 debug!(" final inline threshold = {}", threshold);
396
397 let mut checker =
400 CostChecker::new(tcx, self.typing_env(), Some(callsite.callee), callee_body);
401
402 checker.add_function_level_costs();
403
404 let mut work_list = vec![START_BLOCK];
406 let mut visited = DenseBitSet::new_empty(callee_body.basic_blocks.len());
407 while let Some(bb) = work_list.pop() {
408 if !visited.insert(bb.index()) {
409 continue;
410 }
411
412 let blk = &callee_body.basic_blocks[bb];
413 checker.visit_basic_block_data(bb, blk);
414
415 let term = blk.terminator();
416 let caller_attrs = tcx.codegen_fn_attrs(self.caller_def_id());
417 if let TerminatorKind::Drop { ref place, target, unwind, replace: _, drop: _ } =
418 term.kind
419 {
420 work_list.push(target);
421
422 let ty = callsite.callee.instantiate_mir(
424 tcx,
425 ty::EarlyBinder::bind(tcx, place.ty(callee_body, tcx).ty),
426 );
427 if ty.needs_drop(tcx, self.typing_env())
428 && let UnwindAction::Cleanup(unwind) = unwind
429 {
430 work_list.push(unwind);
431 }
432 } else if callee_attrs.instruction_set != caller_attrs.instruction_set
433 && matches!(term.kind, TerminatorKind::InlineAsm { .. })
434 {
435 return Err("cannot move inline-asm across instruction sets");
441 } else if let TerminatorKind::TailCall { .. } = term.kind {
442 return Err("can't inline functions with tail calls");
445 } else {
446 work_list.extend(term.successors())
447 }
448 }
449
450 let cost = checker.cost();
455 if cost <= threshold {
456 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
457 Ok(())
458 } else {
459 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
460 Err("cost above threshold")
461 }
462 }
463
464 fn on_inline_success(
465 &mut self,
466 callsite: &CallSite<'tcx>,
467 caller_body: &mut Body<'tcx>,
468 new_blocks: std::ops::Range<BasicBlock>,
469 ) {
470 self.changed = true;
471
472 let new_calls_count = new_blocks
473 .clone()
474 .filter(|&bb| is_call_like(caller_body.basic_blocks[bb].terminator()))
475 .count();
476 if new_calls_count > 1 {
477 self.top_down_counter += 1;
478 }
479
480 self.history.push(callsite.callee.def_id());
481 process_blocks(self, caller_body, new_blocks);
482 self.history.pop();
483
484 if self.history.is_empty() {
485 self.top_down_counter = 0;
486 }
487 }
488
489 fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {}
490}
491
492fn inline<'tcx, T: Inliner<'tcx>>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
493 let def_id = body.source.def_id();
494
495 if !tcx.hir_body_owner_kind(def_id).is_fn_or_closure() {
497 return false;
498 }
499
500 let mut inliner = T::new(tcx, def_id, body);
501 if !inliner.check_caller_mir_body(body) {
502 return false;
503 }
504
505 let blocks = START_BLOCK..body.basic_blocks.next_index();
506 process_blocks(&mut inliner, body, blocks);
507 inliner.changed()
508}
509
510fn process_blocks<'tcx, I: Inliner<'tcx>>(
511 inliner: &mut I,
512 caller_body: &mut Body<'tcx>,
513 blocks: Range<BasicBlock>,
514) {
515 for bb in blocks {
516 let bb_data = &caller_body[bb];
517 if bb_data.is_cleanup {
518 continue;
519 }
520
521 let Some(callsite) = resolve_callsite(inliner, caller_body, bb, bb_data) else {
522 continue;
523 };
524
525 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
526 let _guard = span.enter();
527
528 match try_inlining(inliner, caller_body, &callsite) {
529 Err(reason) => {
530 debug!("not-inlined {} [{}]", callsite.callee, reason);
531 inliner.on_inline_failure(&callsite, reason);
532 }
533 Ok(new_blocks) => {
534 debug!("inlined {}", callsite.callee);
535 inliner.on_inline_success(&callsite, caller_body, new_blocks);
536 }
537 }
538 }
539}
540
541fn resolve_callsite<'tcx, I: Inliner<'tcx>>(
542 inliner: &I,
543 caller_body: &Body<'tcx>,
544 bb: BasicBlock,
545 bb_data: &BasicBlockData<'tcx>,
546) -> Option<CallSite<'tcx>> {
547 let tcx = inliner.tcx();
548 let terminator = bb_data.terminator();
550
551 if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
553 let func_ty = func.ty(caller_body, tcx);
554 if let ty::FnDef(def_id, args) = *func_ty.kind() {
555 if !inliner.should_inline_for_callee(def_id) {
556 debug!("not enabled");
557 return None;
558 }
559
560 let args = tcx
562 .try_normalize_erasing_regions(inliner.typing_env(), Unnormalized::new_wip(args))
563 .ok()?
564 .no_bound_vars()
565 .unwrap();
566 let mut callee =
567 Instance::try_resolve(tcx, inliner.typing_env(), def_id, args).ok().flatten()?;
568
569 if let InstanceKind::Virtual(..) = callee.def {
570 return None;
571 }
572 if let InstanceKind::Intrinsic(..) = callee.def {
573 let intrinsic = tcx.intrinsic(def_id).unwrap();
574 if intrinsic.must_be_overridden {
575 return None; }
577 if !tcx.sess.fallback_intrinsics.contains(&intrinsic.name) {
578 return None; }
580 debug!("callsite is fallback body: {def_id:?}");
582 callee = ty::Instance { def: ty::InstanceKind::Item(def_id), args: callee.args };
583 }
584
585 if inliner.history().contains(&callee.def_id()) {
586 return None;
587 }
588
589 let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip();
590
591 if let InstanceKind::Item(instance_def_id) = callee.def
594 && tcx.def_kind(instance_def_id) == DefKind::AssocFn
595 && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
596 && instance_fn_sig.abi() != fn_sig.abi()
597 {
598 return None;
599 }
600
601 let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
602
603 return Some(CallSite { callee, fn_sig, block: bb, source_info });
604 }
605 }
606
607 None
608}
609
610fn try_inlining<'tcx, I: Inliner<'tcx>>(
614 inliner: &I,
615 caller_body: &mut Body<'tcx>,
616 callsite: &CallSite<'tcx>,
617) -> Result<std::ops::Range<BasicBlock>, &'static str> {
618 let tcx = inliner.tcx();
619 check_mir_is_available(inliner, caller_body, callsite.callee)?;
620
621 let callee_attrs = tcx.codegen_instance_attrs(callsite.callee.def);
622 let callee_attrs = callee_attrs.as_ref();
623 check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
624 check_codegen_attributes(inliner, callsite, callee_attrs)?;
625
626 let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
627 let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
628 let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
629 for arg in args {
630 if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
631 return Err("call has unsized argument");
634 }
635 }
636
637 let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
638 check_inline::is_inline_valid_on_body(tcx, callee_body)?;
639 inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
640
641 let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
642 tcx,
643 inliner.typing_env(),
644 ty::EarlyBinder::bind(tcx, callee_body.clone()),
645 ) else {
646 debug!("failed to normalize callee body");
647 return Err("implementation limitation -- could not normalize callee body");
648 };
649
650 if !validate_types(tcx, inliner.typing_env(), &callee_body, caller_body).is_empty() {
653 debug!("failed to validate callee body");
654 return Err("implementation limitation -- callee body failed validation");
655 }
656
657 let output_type = callee_body.return_ty();
661 if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
662 trace!(?output_type, ?destination_ty);
663 return Err("implementation limitation -- return type mismatch");
664 }
665 if callsite.fn_sig.abi() == ExternAbi::RustCall {
666 let (self_arg, arg_tuple) = match &args[..] {
667 [arg_tuple] => (None, arg_tuple),
668 [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
669 _ => bug!("Expected `rust-call` to have 1 or 2 args"),
670 };
671
672 let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
673
674 let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
675 let arg_tys = if callee_body.spread_arg.is_some() {
676 std::slice::from_ref(&arg_tuple_ty)
677 } else {
678 let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
679 bug!("Closure arguments are not passed as a tuple");
680 };
681 arg_tuple_tys.as_slice()
682 };
683
684 for (arg_ty, input) in
685 self_arg_ty.into_iter().chain(arg_tys.iter().copied()).zip(callee_body.args_iter())
686 {
687 let input_type = callee_body.local_decls[input].ty;
688 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
689 trace!(?arg_ty, ?input_type);
690 debug!("failed to normalize tuple argument type");
691 return Err("implementation limitation");
692 }
693 }
694 } else {
695 for (arg, input) in args.iter().zip(callee_body.args_iter()) {
696 let input_type = callee_body.local_decls[input].ty;
697 let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
698 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
699 trace!(?arg_ty, ?input_type);
700 debug!("failed to normalize argument type");
701 return Err("implementation limitation -- arg mismatch");
702 }
703 }
704 }
705
706 let old_blocks = caller_body.basic_blocks.next_index();
707 inline_call(inliner, caller_body, callsite, callee_body);
708 let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
709
710 Ok(new_blocks)
711}
712
713fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
714 inliner: &I,
715 caller_body: &Body<'tcx>,
716 callee: Instance<'tcx>,
717) -> Result<(), &'static str> {
718 let caller_def_id = caller_body.source.def_id();
719 let callee_def_id = callee.def_id();
720 if callee_def_id == caller_def_id {
721 return Err("self-recursion");
722 }
723
724 match callee.def {
725 InstanceKind::Item(_) => {
726 if !inliner.tcx().is_mir_available(callee_def_id) {
730 debug!("item MIR unavailable");
731 return Err("implementation limitation -- MIR unavailable");
732 }
733 }
734 InstanceKind::Intrinsic(_) | InstanceKind::LlvmIntrinsic(_) | InstanceKind::Virtual(..) => {
736 debug!("instance without MIR (intrinsic / virtual)");
737 return Err("implementation limitation -- cannot inline intrinsic");
738 }
739
740 InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty)))
746 if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) =>
747 {
748 debug!("still needs substitution");
749 return Err("implementation limitation -- HACK for dropping polymorphic type");
750 }
751 InstanceKind::Shim(ShimKind::AsyncDropGlue(_, ty))
752 | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)) => {
753 return if ty.still_further_specializable() {
754 Err("still needs substitution")
755 } else {
756 Ok(())
757 };
758 }
759 InstanceKind::Shim(ShimKind::FutureDropPoll(_, ty, ty2)) => {
760 return if ty.still_further_specializable() || ty2.still_further_specializable() {
761 Err("still needs substitution")
762 } else {
763 Ok(())
764 };
765 }
766
767 InstanceKind::Shim(ShimKind::VTable(_))
772 | InstanceKind::Shim(ShimKind::Reify(..))
773 | InstanceKind::Shim(ShimKind::FnPtr(..))
774 | InstanceKind::Shim(ShimKind::ClosureOnce { .. })
775 | InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure { .. })
776 | InstanceKind::Shim(ShimKind::DropGlue(..))
777 | InstanceKind::Shim(ShimKind::Clone(..))
778 | InstanceKind::Shim(ShimKind::ThreadLocal(..))
779 | InstanceKind::Shim(ShimKind::FnPtrAddr(..)) => return Ok(()),
780 }
781
782 if inliner.tcx().is_constructor(callee_def_id) {
783 trace!("constructors always have MIR");
784 return Ok(());
786 }
787
788 if let Some(callee_def_id) = callee_def_id.as_local()
789 && !inliner
790 .tcx()
791 .is_lang_item(inliner.tcx().parent(caller_def_id), rustc_hir::LangItem::FnOnce)
792 {
793 let Some(cyclic_callees) = inliner.tcx().mir_callgraph_cyclic(caller_def_id.expect_local())
796 else {
797 return Err("call graph cycle detection bailed due to recursion limit");
798 };
799 if cyclic_callees.contains(&callee_def_id) {
800 debug!("query cycle avoidance");
801 return Err("caller might be reachable from callee");
802 }
803
804 Ok(())
805 } else {
806 trace!("functions from other crates always have MIR");
811 Ok(())
812 }
813}
814
815fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
818 inliner: &I,
819 callsite: &CallSite<'tcx>,
820 callee_attrs: &CodegenFnAttrs,
821) -> Result<(), &'static str> {
822 let tcx = inliner.tcx();
823 if let InlineAttr::Never = callee_attrs.inline {
824 return Err("never inline attribute");
825 }
826
827 if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
828 return Err("has DoNotOptimize attribute");
829 }
830
831 inliner.check_codegen_attributes_extra(callee_attrs)?;
832
833 let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
836 if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
837 return Err("not exported");
838 }
839
840 let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
841 if callee_attrs.sanitizers != codegen_fn_attrs.sanitizers {
842 return Err("incompatible sanitizer set");
843 }
844
845 if callee_attrs.instruction_set.is_some()
849 && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
850 {
851 return Err("incompatible instruction set");
852 }
853
854 let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
855 let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
856 if callee_feature_names.ne(this_feature_names) {
857 return Err("incompatible target features");
863 }
864
865 Ok(())
866}
867
868fn inline_call<'tcx, I: Inliner<'tcx>>(
869 inliner: &I,
870 caller_body: &mut Body<'tcx>,
871 callsite: &CallSite<'tcx>,
872 mut callee_body: Body<'tcx>,
873) {
874 let tcx = inliner.tcx();
875 let terminator = caller_body[callsite.block].terminator.take().unwrap();
876 let TerminatorKind::Call { func, args, destination, unwind, target, .. } = terminator.kind
877 else {
878 bug!("unexpected terminator kind {:?}", terminator.kind);
879 };
880
881 let return_block = if let Some(block) = target {
882 let data = BasicBlockData::new(
885 Some(Terminator {
886 source_info: terminator.source_info,
887 kind: TerminatorKind::Goto { target: block },
888 attributes: ThinVec::new(),
889 }),
890 caller_body[block].is_cleanup,
891 );
892 Some(caller_body.basic_blocks_mut().push(data))
893 } else {
894 None
895 };
896
897 fn dest_needs_borrow(place: Place<'_>) -> bool {
903 for elem in place.projection.iter() {
904 match elem {
905 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
906 _ => {}
907 }
908 }
909
910 false
911 }
912
913 let dest = if dest_needs_borrow(destination) {
914 trace!("creating temp for return destination");
915 let dest = Rvalue::Ref(
916 tcx.lifetimes.re_erased,
917 BorrowKind::Mut { kind: MutBorrowKind::Default },
918 destination,
919 );
920 let dest_ty = dest.ty(caller_body, tcx);
921 let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
922 caller_body[callsite.block].statements.push(Statement::new(
923 callsite.source_info,
924 StatementKind::Assign(Box::new((temp, dest))),
925 ));
926 tcx.mk_place_deref(temp)
927 } else {
928 destination
929 };
930
931 let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
934 (false, d)
935 } else {
936 (
937 true,
938 new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
939 )
940 };
941
942 let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
944
945 let mut integrator = Integrator {
946 args: &args,
947 new_locals: caller_body.local_decls.next_index()..,
948 new_scopes: caller_body.source_scopes.next_index()..,
949 new_blocks: caller_body.basic_blocks.next_index()..,
950 destination: destination_local,
951 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
952 callsite,
953 cleanup_block: unwind,
954 in_cleanup_block: false,
955 return_block,
956 tcx,
957 always_live_locals: UsedInStmtLocals::new(&callee_body).locals,
958 };
959
960 integrator.visit_body(&mut callee_body);
963
964 for local in callee_body.vars_and_temps_iter() {
967 if integrator.always_live_locals.contains(local) {
968 let new_local = integrator.map_local(local);
969 caller_body[callsite.block]
970 .statements
971 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(new_local)));
972 }
973 }
974 if let Some(block) = return_block {
975 let mut n = 0;
978 if remap_destination {
979 caller_body[block].statements.push(Statement::new(
980 callsite.source_info,
981 StatementKind::Assign(Box::new((
982 dest,
983 Rvalue::Use(Operand::Move(destination_local.into()), WithRetag::Yes),
984 ))),
985 ));
986 n += 1;
987 }
988 for local in callee_body.vars_and_temps_iter().rev() {
989 if integrator.always_live_locals.contains(local) {
990 let new_local = integrator.map_local(local);
991 caller_body[block].statements.push(Statement::new(
992 callsite.source_info,
993 StatementKind::StorageDead(new_local),
994 ));
995 n += 1;
996 }
997 }
998 caller_body[block].statements.rotate_right(n);
999 }
1000
1001 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
1003 caller_body.source_scopes.append(&mut callee_body.source_scopes);
1004
1005 if tcx
1007 .sess
1008 .opts
1009 .unstable_opts
1010 .inline_mir_preserve_debug
1011 .unwrap_or(tcx.sess.opts.debuginfo == DebugInfo::Full)
1012 {
1013 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
1017 } else {
1018 for bb in callee_body.basic_blocks_mut() {
1019 bb.drop_debuginfo();
1020 }
1021 }
1022 caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
1023
1024 caller_body[callsite.block].terminator = Some(Terminator {
1025 source_info: callsite.source_info,
1026 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
1027 attributes: ThinVec::new(),
1028 });
1029
1030 caller_body.required_consts.as_mut().unwrap().extend(
1034 callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
1035 );
1036 let callee_item = MentionedItem::Fn(func.ty(caller_body, tcx));
1044 let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
1045 if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
1046 caller_mentioned_items.remove(idx);
1048 caller_mentioned_items.extend(callee_body.mentioned_items());
1049 } else {
1050 }
1054}
1055
1056fn make_call_args<'tcx, I: Inliner<'tcx>>(
1057 inliner: &I,
1058 args: Box<[Spanned<Operand<'tcx>>]>,
1059 callsite: &CallSite<'tcx>,
1060 caller_body: &mut Body<'tcx>,
1061 callee_body: &Body<'tcx>,
1062 return_block: Option<BasicBlock>,
1063) -> Box<[Local]> {
1064 let tcx = inliner.tcx();
1065
1066 if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1090 let mut args = args.into_iter();
1091 let self_ = create_temp_if_necessary(
1092 inliner,
1093 args.next().unwrap().node,
1094 callsite,
1095 caller_body,
1096 return_block,
1097 );
1098 let tuple = create_temp_if_necessary(
1099 inliner,
1100 args.next().unwrap().node,
1101 callsite,
1102 caller_body,
1103 return_block,
1104 );
1105 assert!(args.next().is_none());
1106
1107 let tuple = Place::from(tuple);
1108 let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
1109 bug!("Closure arguments are not passed as a tuple");
1110 };
1111
1112 let closure_ref_arg = iter::once(self_);
1114
1115 let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
1117 let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
1119
1120 create_temp_if_necessary(inliner, tuple_field, callsite, caller_body, return_block)
1122 });
1123
1124 closure_ref_arg.chain(tuple_tmp_args).collect()
1125 } else {
1126 args.into_iter()
1127 .map(|a| create_temp_if_necessary(inliner, a.node, callsite, caller_body, return_block))
1128 .collect()
1129 }
1130}
1131
1132fn create_temp_if_necessary<'tcx, I: Inliner<'tcx>>(
1135 inliner: &I,
1136 arg: Operand<'tcx>,
1137 callsite: &CallSite<'tcx>,
1138 caller_body: &mut Body<'tcx>,
1139 return_block: Option<BasicBlock>,
1140) -> Local {
1141 if let Operand::Move(place) = &arg
1143 && let Some(local) = place.as_local()
1144 && caller_body.local_kind(local) == LocalKind::Temp
1145 {
1146 return local;
1147 }
1148
1149 trace!("creating temp for argument {:?}", arg);
1151 let arg_ty = arg.ty(caller_body, inliner.tcx());
1152 let local = new_call_temp(caller_body, callsite, arg_ty, return_block);
1153 caller_body[callsite.block].statements.push(Statement::new(
1154 callsite.source_info,
1155 StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg, WithRetag::Yes)))),
1156 ));
1157 local
1158}
1159
1160fn new_call_temp<'tcx>(
1162 caller_body: &mut Body<'tcx>,
1163 callsite: &CallSite<'tcx>,
1164 ty: Ty<'tcx>,
1165 return_block: Option<BasicBlock>,
1166) -> Local {
1167 let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
1168
1169 caller_body[callsite.block]
1170 .statements
1171 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(local)));
1172
1173 if let Some(block) = return_block {
1174 caller_body[block]
1175 .statements
1176 .insert(0, Statement::new(callsite.source_info, StatementKind::StorageDead(local)));
1177 }
1178
1179 local
1180}
1181
1182struct Integrator<'a, 'tcx> {
1190 args: &'a [Local],
1191 new_locals: RangeFrom<Local>,
1192 new_scopes: RangeFrom<SourceScope>,
1193 new_blocks: RangeFrom<BasicBlock>,
1194 destination: Local,
1195 callsite_scope: SourceScopeData<'tcx>,
1196 callsite: &'a CallSite<'tcx>,
1197 cleanup_block: UnwindAction,
1198 in_cleanup_block: bool,
1199 return_block: Option<BasicBlock>,
1200 tcx: TyCtxt<'tcx>,
1201 always_live_locals: DenseBitSet<Local>,
1202}
1203
1204impl Integrator<'_, '_> {
1205 fn map_local(&self, local: Local) -> Local {
1206 let new = if local == RETURN_PLACE {
1207 self.destination
1208 } else {
1209 let idx = local.index() - 1;
1210 if idx < self.args.len() {
1211 self.args[idx]
1212 } else {
1213 self.new_locals.start + (idx - self.args.len())
1214 }
1215 };
1216 trace!("mapping local `{:?}` to `{:?}`", local, new);
1217 new
1218 }
1219
1220 fn map_scope(&self, scope: SourceScope) -> SourceScope {
1221 let new = self.new_scopes.start + scope.index();
1222 trace!("mapping scope `{:?}` to `{:?}`", scope, new);
1223 new
1224 }
1225
1226 fn map_block(&self, block: BasicBlock) -> BasicBlock {
1227 let new = self.new_blocks.start + block.index();
1228 trace!("mapping block `{:?}` to `{:?}`", block, new);
1229 new
1230 }
1231
1232 fn map_unwind(&self, unwind: UnwindAction) -> UnwindAction {
1233 if self.in_cleanup_block {
1234 match unwind {
1235 UnwindAction::Cleanup(_) | UnwindAction::Continue => {
1236 bug!("cleanup on cleanup block");
1237 }
1238 UnwindAction::Unreachable | UnwindAction::Terminate(_) => return unwind,
1239 }
1240 }
1241
1242 match unwind {
1243 UnwindAction::Unreachable | UnwindAction::Terminate(_) => unwind,
1244 UnwindAction::Cleanup(target) => UnwindAction::Cleanup(self.map_block(target)),
1245 UnwindAction::Continue => self.cleanup_block,
1247 }
1248 }
1249}
1250
1251impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
1252 fn tcx(&self) -> TyCtxt<'tcx> {
1253 self.tcx
1254 }
1255
1256 fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
1257 *local = self.map_local(*local);
1258 }
1259
1260 fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1261 self.super_source_scope_data(scope_data);
1262 if scope_data.parent_scope.is_none() {
1263 scope_data.parent_scope = Some(self.callsite.source_info.scope);
1266 assert_eq!(scope_data.inlined_parent_scope, None);
1267 scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1268 Some(self.callsite.source_info.scope)
1269 } else {
1270 self.callsite_scope.inlined_parent_scope
1271 };
1272
1273 assert_eq!(scope_data.inlined, None);
1275 scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1276 } else if scope_data.inlined_parent_scope.is_none() {
1277 scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1279 }
1280 }
1281
1282 fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1283 *scope = self.map_scope(*scope);
1284 }
1285
1286 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1287 self.in_cleanup_block = data.is_cleanup;
1288 self.super_basic_block_data(block, data);
1289 self.in_cleanup_block = false;
1290 }
1291
1292 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1293 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1294 statement.kind
1295 {
1296 self.always_live_locals.remove(local);
1297 }
1298 self.super_statement(statement, location);
1299 }
1300
1301 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1302 if !matches!(terminator.kind, TerminatorKind::Return) {
1305 self.super_terminator(terminator, loc);
1306 } else {
1307 self.visit_source_info(&mut terminator.source_info);
1308 }
1309
1310 match terminator.kind {
1311 TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1312 TerminatorKind::Goto { ref mut target } => {
1313 *target = self.map_block(*target);
1314 }
1315 TerminatorKind::SwitchInt { ref mut targets, .. } => {
1316 for tgt in targets.all_targets_mut() {
1317 *tgt = self.map_block(*tgt);
1318 }
1319 }
1320 TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1321 *target = self.map_block(*target);
1322 *unwind = self.map_unwind(*unwind);
1323 }
1324 TerminatorKind::TailCall { .. } => {
1325 unreachable!()
1327 }
1328 TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1329 if let Some(ref mut tgt) = *target {
1330 *tgt = self.map_block(*tgt);
1331 }
1332 *unwind = self.map_unwind(*unwind);
1333 }
1334 TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1335 *target = self.map_block(*target);
1336 *unwind = self.map_unwind(*unwind);
1337 }
1338 TerminatorKind::Return => {
1339 terminator.kind = if let Some(tgt) = self.return_block {
1340 TerminatorKind::Goto { target: tgt }
1341 } else {
1342 TerminatorKind::Unreachable
1343 }
1344 }
1345 TerminatorKind::UnwindResume => {
1346 terminator.kind = match self.cleanup_block {
1347 UnwindAction::Cleanup(tgt) => TerminatorKind::Goto { target: tgt },
1348 UnwindAction::Continue => TerminatorKind::UnwindResume,
1349 UnwindAction::Unreachable => TerminatorKind::Unreachable,
1350 UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1351 };
1352 }
1353 TerminatorKind::UnwindTerminate(_) => {}
1354 TerminatorKind::Unreachable => {}
1355 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1356 *real_target = self.map_block(*real_target);
1357 *imaginary_target = self.map_block(*imaginary_target);
1358 }
1359 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1360 {
1362 bug!("False unwinds should have been removed before inlining")
1363 }
1364 TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1365 for tgt in targets.iter_mut() {
1366 *tgt = self.map_block(*tgt);
1367 }
1368 *unwind = self.map_unwind(*unwind);
1369 }
1370 }
1371 }
1372}
1373
1374#[instrument(skip(tcx), level = "debug")]
1375fn try_instance_mir<'tcx>(
1376 tcx: TyCtxt<'tcx>,
1377 instance: InstanceKind<'tcx>,
1378) -> Result<&'tcx Body<'tcx>, &'static str> {
1379 if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, Some(ty)))
1380 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, ty)) = instance
1381 && let ty::Adt(def, args) = ty.kind()
1382 {
1383 let fields = def.all_fields();
1384 for field in fields {
1385 let field_ty = field.ty(tcx, args);
1386 if field_ty.has_param() && field_ty.has_aliases() {
1387 return Err("cannot build drop shim for polymorphic type");
1388 }
1389 }
1390 }
1391 Ok(tcx.instance_mir(instance))
1392}
1393
1394fn body_is_forwarder(body: &Body<'_>) -> bool {
1395 let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1396 else {
1397 return false;
1398 };
1399 if let Some(target) = target {
1400 let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1401 return false;
1402 };
1403 }
1404
1405 let max_blocks = if !body.is_polymorphic {
1406 2
1407 } else if target.is_none() {
1408 3
1409 } else {
1410 4
1411 };
1412 if body.basic_blocks.len() > max_blocks {
1413 return false;
1414 }
1415
1416 body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1417 bb == START_BLOCK
1418 || matches!(
1419 bb_data.terminator().kind,
1420 TerminatorKind::Return
1421 | TerminatorKind::Drop { .. }
1422 | TerminatorKind::UnwindResume
1423 | TerminatorKind::UnwindTerminate(_)
1424 )
1425 })
1426}