1use std::iter;
4use std::ops::{Range, RangeFrom};
5
6use rustc_abi::{ExternAbi, FieldIdx};
7use rustc_data_structures::debug_assert_matches;
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::{self, Instance, InstanceKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt};
18use rustc_session::config::{DebugInfo, OptLevel};
19use rustc_span::source_map::Spanned;
20use tracing::{debug, instrument, trace, trace_span};
21
22use crate::cost_checker::{CostChecker, is_call_like};
23use crate::simplify::{UsedInStmtLocals, simplify_cfg};
24use crate::validate::validate_types;
25use crate::{check_inline, util};
26
27pub(crate) mod cycle;
28
29const HISTORY_DEPTH_LIMIT: usize = 20;
30const TOP_DOWN_DEPTH_LIMIT: usize = 5;
31
32#[derive(Clone, Debug)]
33struct CallSite<'tcx> {
34 callee: Instance<'tcx>,
35 fn_sig: ty::PolyFnSig<'tcx>,
36 block: BasicBlock,
37 source_info: SourceInfo,
38}
39
40pub struct Inline;
43
44impl<'tcx> crate::MirPass<'tcx> for Inline {
45 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
46 if let Some(enabled) = sess.opts.unstable_opts.inline_mir {
47 return enabled;
48 }
49
50 match sess.mir_opt_level() {
51 0 | 1 => false,
52 2 => {
53 (sess.opts.optimize == OptLevel::More || sess.opts.optimize == OptLevel::Aggressive)
54 && sess.opts.incremental == None
55 }
56 _ => true,
57 }
58 }
59
60 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
61 let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
62 let _guard = span.enter();
63 if inline::<NormalInliner<'tcx>>(tcx, body) {
64 debug!("running simplify cfg on {:?}", body.source);
65 simplify_cfg(tcx, body);
66 }
67 }
68
69 fn is_required(&self) -> bool {
70 false
71 }
72}
73
74pub struct ForceInline;
75
76impl ForceInline {
77 pub fn should_run_pass_for_callee<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
78 matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
79 }
80}
81
82impl<'tcx> crate::MirPass<'tcx> for ForceInline {
83 fn is_enabled(&self, _: &rustc_session::Session) -> bool {
84 true
85 }
86
87 fn can_be_overridden(&self) -> bool {
88 false
89 }
90
91 fn is_required(&self) -> bool {
92 true
93 }
94
95 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
96 let span = trace_span!("force_inline", body = %tcx.def_path_str(body.source.def_id()));
97 let _guard = span.enter();
98 if inline::<ForceInliner<'tcx>>(tcx, body) {
99 debug!("running simplify cfg on {:?}", body.source);
100 simplify_cfg(tcx, body);
101 }
102 }
103}
104
105trait Inliner<'tcx> {
106 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self;
107
108 fn tcx(&self) -> TyCtxt<'tcx>;
109 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
110 fn history(&self) -> &[DefId];
111 fn caller_def_id(&self) -> DefId;
112
113 fn changed(self) -> bool;
115
116 fn should_inline_for_callee(&self, def_id: DefId) -> bool;
118
119 fn check_codegen_attributes_extra(
120 &self,
121 callee_attrs: &CodegenFnAttrs,
122 ) -> Result<(), &'static str>;
123
124 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool;
125
126 fn check_callee_mir_body(
129 &self,
130 callsite: &CallSite<'tcx>,
131 callee_body: &Body<'tcx>,
132 callee_attrs: &CodegenFnAttrs,
133 ) -> Result<(), &'static str>;
134
135 fn on_inline_success(
137 &mut self,
138 callsite: &CallSite<'tcx>,
139 caller_body: &mut Body<'tcx>,
140 new_blocks: std::ops::Range<BasicBlock>,
141 );
142
143 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str);
145}
146
147struct ForceInliner<'tcx> {
148 tcx: TyCtxt<'tcx>,
149 typing_env: ty::TypingEnv<'tcx>,
150 def_id: DefId,
152 history: Vec<DefId>,
158 changed: bool,
160}
161
162impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> {
163 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
164 Self { tcx, typing_env: body.typing_env(tcx), def_id, history: Vec::new(), changed: false }
165 }
166
167 fn tcx(&self) -> TyCtxt<'tcx> {
168 self.tcx
169 }
170
171 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
172 self.typing_env
173 }
174
175 fn history(&self) -> &[DefId] {
176 &self.history
177 }
178
179 fn caller_def_id(&self) -> DefId {
180 self.def_id
181 }
182
183 fn changed(self) -> bool {
184 self.changed
185 }
186
187 fn should_inline_for_callee(&self, def_id: DefId) -> bool {
188 ForceInline::should_run_pass_for_callee(self.tcx(), def_id)
189 }
190
191 fn check_codegen_attributes_extra(
192 &self,
193 callee_attrs: &CodegenFnAttrs,
194 ) -> Result<(), &'static str> {
195 debug_assert_matches!(callee_attrs.inline, InlineAttr::Force { .. });
196 Ok(())
197 }
198
199 fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool {
200 true
201 }
202
203 #[instrument(level = "debug", skip(self, callee_body))]
204 fn check_callee_mir_body(
205 &self,
206 _: &CallSite<'tcx>,
207 callee_body: &Body<'tcx>,
208 callee_attrs: &CodegenFnAttrs,
209 ) -> Result<(), &'static str> {
210 if callee_body.tainted_by_errors.is_some() {
211 return Err("body has errors");
212 }
213
214 let caller_attrs = self.tcx().codegen_fn_attrs(self.caller_def_id());
215 if callee_attrs.instruction_set != caller_attrs.instruction_set
216 && callee_body
217 .basic_blocks
218 .iter()
219 .any(|bb| matches!(bb.terminator().kind, TerminatorKind::InlineAsm { .. }))
220 {
221 Err("cannot move inline-asm across instruction sets")
227 } else {
228 Ok(())
229 }
230 }
231
232 fn on_inline_success(
233 &mut self,
234 callsite: &CallSite<'tcx>,
235 caller_body: &mut Body<'tcx>,
236 new_blocks: std::ops::Range<BasicBlock>,
237 ) {
238 self.changed = true;
239
240 self.history.push(callsite.callee.def_id());
241 process_blocks(self, caller_body, new_blocks);
242 self.history.pop();
243 }
244
245 fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str) {
246 let tcx = self.tcx();
247 let InlineAttr::Force { attr_span, reason: justification } =
248 tcx.codegen_instance_attrs(callsite.callee.def).inline
249 else {
250 bug!("called on item without required inlining");
251 };
252
253 let call_span = callsite.source_info.span;
254 let callee = tcx.def_path_str(callsite.callee.def_id());
255 tcx.dcx().emit_err(crate::errors::ForceInlineFailure {
256 call_span,
257 attr_span,
258 caller_span: tcx.def_span(self.def_id),
259 caller: tcx.def_path_str(self.def_id),
260 callee_span: tcx.def_span(callsite.callee.def_id()),
261 callee: callee.clone(),
262 reason,
263 justification: justification
264 .map(|sym| crate::errors::ForceInlineJustification { sym, callee }),
265 });
266 }
267}
268
269struct NormalInliner<'tcx> {
270 tcx: TyCtxt<'tcx>,
271 typing_env: ty::TypingEnv<'tcx>,
272 def_id: DefId,
274 history: Vec<DefId>,
280 top_down_counter: usize,
284 changed: bool,
286 caller_is_inline_forwarder: bool,
289}
290
291impl<'tcx> NormalInliner<'tcx> {
292 fn past_depth_limit(&self) -> bool {
293 self.history.len() > HISTORY_DEPTH_LIMIT || self.top_down_counter > TOP_DOWN_DEPTH_LIMIT
294 }
295}
296
297impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> {
298 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
299 let typing_env = body.typing_env(tcx);
300 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
301
302 Self {
303 tcx,
304 typing_env,
305 def_id,
306 history: Vec::new(),
307 top_down_counter: 0,
308 changed: false,
309 caller_is_inline_forwarder: matches!(
310 codegen_fn_attrs.inline,
311 InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. }
312 ) && body_is_forwarder(body),
313 }
314 }
315
316 fn tcx(&self) -> TyCtxt<'tcx> {
317 self.tcx
318 }
319
320 fn caller_def_id(&self) -> DefId {
321 self.def_id
322 }
323
324 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
325 self.typing_env
326 }
327
328 fn history(&self) -> &[DefId] {
329 &self.history
330 }
331
332 fn changed(self) -> bool {
333 self.changed
334 }
335
336 fn should_inline_for_callee(&self, _: DefId) -> bool {
337 true
338 }
339
340 fn check_codegen_attributes_extra(
341 &self,
342 callee_attrs: &CodegenFnAttrs,
343 ) -> Result<(), &'static str> {
344 if self.past_depth_limit() && matches!(callee_attrs.inline, InlineAttr::None) {
345 Err("Past depth limit so not inspecting unmarked callee")
346 } else {
347 Ok(())
348 }
349 }
350
351 fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool {
352 if body.coroutine.is_some() {
356 return false;
357 }
358
359 true
360 }
361
362 #[instrument(level = "debug", skip(self, callee_body))]
363 fn check_callee_mir_body(
364 &self,
365 callsite: &CallSite<'tcx>,
366 callee_body: &Body<'tcx>,
367 callee_attrs: &CodegenFnAttrs,
368 ) -> Result<(), &'static str> {
369 let tcx = self.tcx();
370
371 if let Some(_) = callee_body.tainted_by_errors {
372 return Err("body has errors");
373 }
374
375 if self.past_depth_limit() && callee_body.basic_blocks.len() > 1 {
376 return Err("Not inlining multi-block body as we're past a depth limit");
377 }
378
379 let mut threshold = if self.caller_is_inline_forwarder || self.past_depth_limit() {
380 tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30)
381 } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) {
382 tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
383 } else {
384 tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
385 };
386
387 if callee_body.basic_blocks.len() <= 3 {
391 threshold += threshold / 4;
392 }
393 debug!(" final inline threshold = {}", threshold);
394
395 let mut checker =
398 CostChecker::new(tcx, self.typing_env(), Some(callsite.callee), callee_body);
399
400 checker.add_function_level_costs();
401
402 let mut work_list = vec![START_BLOCK];
404 let mut visited = DenseBitSet::new_empty(callee_body.basic_blocks.len());
405 while let Some(bb) = work_list.pop() {
406 if !visited.insert(bb.index()) {
407 continue;
408 }
409
410 let blk = &callee_body.basic_blocks[bb];
411 checker.visit_basic_block_data(bb, blk);
412
413 let term = blk.terminator();
414 let caller_attrs = tcx.codegen_fn_attrs(self.caller_def_id());
415 if let TerminatorKind::Drop {
416 ref place,
417 target,
418 unwind,
419 replace: _,
420 drop: _,
421 async_fut: _,
422 } = term.kind
423 {
424 work_list.push(target);
425
426 let ty = callsite
428 .callee
429 .instantiate_mir(tcx, ty::EarlyBinder::bind(&place.ty(callee_body, tcx).ty));
430 if ty.needs_drop(tcx, self.typing_env())
431 && let UnwindAction::Cleanup(unwind) = unwind
432 {
433 work_list.push(unwind);
434 }
435 } else if callee_attrs.instruction_set != caller_attrs.instruction_set
436 && matches!(term.kind, TerminatorKind::InlineAsm { .. })
437 {
438 return Err("cannot move inline-asm across instruction sets");
444 } else if let TerminatorKind::TailCall { .. } = term.kind {
445 return Err("can't inline functions with tail calls");
448 } else {
449 work_list.extend(term.successors())
450 }
451 }
452
453 let cost = checker.cost();
458 if cost <= threshold {
459 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
460 Ok(())
461 } else {
462 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
463 Err("cost above threshold")
464 }
465 }
466
467 fn on_inline_success(
468 &mut self,
469 callsite: &CallSite<'tcx>,
470 caller_body: &mut Body<'tcx>,
471 new_blocks: std::ops::Range<BasicBlock>,
472 ) {
473 self.changed = true;
474
475 let new_calls_count = new_blocks
476 .clone()
477 .filter(|&bb| is_call_like(caller_body.basic_blocks[bb].terminator()))
478 .count();
479 if new_calls_count > 1 {
480 self.top_down_counter += 1;
481 }
482
483 self.history.push(callsite.callee.def_id());
484 process_blocks(self, caller_body, new_blocks);
485 self.history.pop();
486
487 if self.history.is_empty() {
488 self.top_down_counter = 0;
489 }
490 }
491
492 fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {}
493}
494
495fn inline<'tcx, T: Inliner<'tcx>>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
496 let def_id = body.source.def_id();
497
498 if !tcx.hir_body_owner_kind(def_id).is_fn_or_closure() {
500 return false;
501 }
502
503 let mut inliner = T::new(tcx, def_id, body);
504 if !inliner.check_caller_mir_body(body) {
505 return false;
506 }
507
508 let blocks = START_BLOCK..body.basic_blocks.next_index();
509 process_blocks(&mut inliner, body, blocks);
510 inliner.changed()
511}
512
513fn process_blocks<'tcx, I: Inliner<'tcx>>(
514 inliner: &mut I,
515 caller_body: &mut Body<'tcx>,
516 blocks: Range<BasicBlock>,
517) {
518 for bb in blocks {
519 let bb_data = &caller_body[bb];
520 if bb_data.is_cleanup {
521 continue;
522 }
523
524 let Some(callsite) = resolve_callsite(inliner, caller_body, bb, bb_data) else {
525 continue;
526 };
527
528 let span = trace_span!("process_blocks", %callsite.callee, ?bb);
529 let _guard = span.enter();
530
531 match try_inlining(inliner, caller_body, &callsite) {
532 Err(reason) => {
533 debug!("not-inlined {} [{}]", callsite.callee, reason);
534 inliner.on_inline_failure(&callsite, reason);
535 }
536 Ok(new_blocks) => {
537 debug!("inlined {}", callsite.callee);
538 inliner.on_inline_success(&callsite, caller_body, new_blocks);
539 }
540 }
541 }
542}
543
544fn resolve_callsite<'tcx, I: Inliner<'tcx>>(
545 inliner: &I,
546 caller_body: &Body<'tcx>,
547 bb: BasicBlock,
548 bb_data: &BasicBlockData<'tcx>,
549) -> Option<CallSite<'tcx>> {
550 let tcx = inliner.tcx();
551 let terminator = bb_data.terminator();
553
554 if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
556 let func_ty = func.ty(caller_body, tcx);
557 if let ty::FnDef(def_id, args) = *func_ty.kind() {
558 if !inliner.should_inline_for_callee(def_id) {
559 debug!("not enabled");
560 return None;
561 }
562
563 let args = tcx.try_normalize_erasing_regions(inliner.typing_env(), args).ok()?;
565 let callee =
566 Instance::try_resolve(tcx, inliner.typing_env(), def_id, args).ok().flatten()?;
567
568 if let InstanceKind::Virtual(..) | InstanceKind::Intrinsic(_) = callee.def {
569 return None;
570 }
571
572 if inliner.history().contains(&callee.def_id()) {
573 return None;
574 }
575
576 let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args);
577
578 if let InstanceKind::Item(instance_def_id) = callee.def
581 && tcx.def_kind(instance_def_id) == DefKind::AssocFn
582 && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
583 && instance_fn_sig.abi() != fn_sig.abi()
584 {
585 return None;
586 }
587
588 let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
589
590 return Some(CallSite { callee, fn_sig, block: bb, source_info });
591 }
592 }
593
594 None
595}
596
597fn try_inlining<'tcx, I: Inliner<'tcx>>(
601 inliner: &I,
602 caller_body: &mut Body<'tcx>,
603 callsite: &CallSite<'tcx>,
604) -> Result<std::ops::Range<BasicBlock>, &'static str> {
605 let tcx = inliner.tcx();
606 check_mir_is_available(inliner, caller_body, callsite.callee)?;
607
608 let callee_attrs = tcx.codegen_instance_attrs(callsite.callee.def);
609 let callee_attrs = callee_attrs.as_ref();
610 check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
611 check_codegen_attributes(inliner, callsite, callee_attrs)?;
612
613 let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
614 let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
615 let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
616 for arg in args {
617 if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
618 return Err("call has unsized argument");
621 }
622 }
623
624 let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
625 check_inline::is_inline_valid_on_body(tcx, callee_body)?;
626 inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
627
628 let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
629 tcx,
630 inliner.typing_env(),
631 ty::EarlyBinder::bind(callee_body.clone()),
632 ) else {
633 debug!("failed to normalize callee body");
634 return Err("implementation limitation -- could not normalize callee body");
635 };
636
637 if !validate_types(tcx, inliner.typing_env(), &callee_body, caller_body).is_empty() {
640 debug!("failed to validate callee body");
641 return Err("implementation limitation -- callee body failed validation");
642 }
643
644 let output_type = callee_body.return_ty();
648 if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
649 trace!(?output_type, ?destination_ty);
650 return Err("implementation limitation -- return type mismatch");
651 }
652 if callsite.fn_sig.abi() == ExternAbi::RustCall {
653 let (self_arg, arg_tuple) = match &args[..] {
654 [arg_tuple] => (None, arg_tuple),
655 [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
656 _ => bug!("Expected `rust-call` to have 1 or 2 args"),
657 };
658
659 let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
660
661 let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
662 let arg_tys = if callee_body.spread_arg.is_some() {
663 std::slice::from_ref(&arg_tuple_ty)
664 } else {
665 let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
666 bug!("Closure arguments are not passed as a tuple");
667 };
668 arg_tuple_tys.as_slice()
669 };
670
671 for (arg_ty, input) in
672 self_arg_ty.into_iter().chain(arg_tys.iter().copied()).zip(callee_body.args_iter())
673 {
674 let input_type = callee_body.local_decls[input].ty;
675 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
676 trace!(?arg_ty, ?input_type);
677 debug!("failed to normalize tuple argument type");
678 return Err("implementation limitation");
679 }
680 }
681 } else {
682 for (arg, input) in args.iter().zip(callee_body.args_iter()) {
683 let input_type = callee_body.local_decls[input].ty;
684 let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
685 if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
686 trace!(?arg_ty, ?input_type);
687 debug!("failed to normalize argument type");
688 return Err("implementation limitation -- arg mismatch");
689 }
690 }
691 }
692
693 let old_blocks = caller_body.basic_blocks.next_index();
694 inline_call(inliner, caller_body, callsite, callee_body);
695 let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
696
697 Ok(new_blocks)
698}
699
700fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
701 inliner: &I,
702 caller_body: &Body<'tcx>,
703 callee: Instance<'tcx>,
704) -> Result<(), &'static str> {
705 let caller_def_id = caller_body.source.def_id();
706 let callee_def_id = callee.def_id();
707 if callee_def_id == caller_def_id {
708 return Err("self-recursion");
709 }
710
711 match callee.def {
712 InstanceKind::Item(_) => {
713 if !inliner.tcx().is_mir_available(callee_def_id) {
717 debug!("item MIR unavailable");
718 return Err("implementation limitation -- MIR unavailable");
719 }
720 }
721 InstanceKind::Intrinsic(_) | InstanceKind::Virtual(..) => {
723 debug!("instance without MIR (intrinsic / virtual)");
724 return Err("implementation limitation -- cannot inline intrinsic");
725 }
726
727 InstanceKind::DropGlue(_, Some(ty)) if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) => {
733 debug!("still needs substitution");
734 return Err("implementation limitation -- HACK for dropping polymorphic type");
735 }
736 InstanceKind::AsyncDropGlue(_, ty) | InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
737 return if ty.still_further_specializable() {
738 Err("still needs substitution")
739 } else {
740 Ok(())
741 };
742 }
743 InstanceKind::FutureDropPollShim(_, ty, ty2) => {
744 return if ty.still_further_specializable() || ty2.still_further_specializable() {
745 Err("still needs substitution")
746 } else {
747 Ok(())
748 };
749 }
750
751 InstanceKind::VTableShim(_)
756 | InstanceKind::ReifyShim(..)
757 | InstanceKind::FnPtrShim(..)
758 | InstanceKind::ClosureOnceShim { .. }
759 | InstanceKind::ConstructCoroutineInClosureShim { .. }
760 | InstanceKind::DropGlue(..)
761 | InstanceKind::CloneShim(..)
762 | InstanceKind::ThreadLocalShim(..)
763 | InstanceKind::FnPtrAddrShim(..) => return Ok(()),
764 }
765
766 if inliner.tcx().is_constructor(callee_def_id) {
767 trace!("constructors always have MIR");
768 return Ok(());
770 }
771
772 if let Some(callee_def_id) = callee_def_id.as_local()
773 && !inliner
774 .tcx()
775 .is_lang_item(inliner.tcx().parent(caller_def_id), rustc_hir::LangItem::FnOnce)
776 {
777 let Some(cyclic_callees) = inliner.tcx().mir_callgraph_cyclic(caller_def_id.expect_local())
780 else {
781 return Err("call graph cycle detection bailed due to recursion limit");
782 };
783 if cyclic_callees.contains(&callee_def_id) {
784 debug!("query cycle avoidance");
785 return Err("caller might be reachable from callee");
786 }
787
788 Ok(())
789 } else {
790 trace!("functions from other crates always have MIR");
795 Ok(())
796 }
797}
798
799fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
802 inliner: &I,
803 callsite: &CallSite<'tcx>,
804 callee_attrs: &CodegenFnAttrs,
805) -> Result<(), &'static str> {
806 let tcx = inliner.tcx();
807 if let InlineAttr::Never = callee_attrs.inline {
808 return Err("never inline attribute");
809 }
810
811 if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
812 return Err("has DoNotOptimize attribute");
813 }
814
815 inliner.check_codegen_attributes_extra(callee_attrs)?;
816
817 let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
820 if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
821 return Err("not exported");
822 }
823
824 let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
825 if callee_attrs.sanitizers != codegen_fn_attrs.sanitizers {
826 return Err("incompatible sanitizer set");
827 }
828
829 if callee_attrs.instruction_set.is_some()
833 && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
834 {
835 return Err("incompatible instruction set");
836 }
837
838 let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
839 let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
840 if callee_feature_names.ne(this_feature_names) {
841 return Err("incompatible target features");
847 }
848
849 Ok(())
850}
851
852fn inline_call<'tcx, I: Inliner<'tcx>>(
853 inliner: &I,
854 caller_body: &mut Body<'tcx>,
855 callsite: &CallSite<'tcx>,
856 mut callee_body: Body<'tcx>,
857) {
858 let tcx = inliner.tcx();
859 let terminator = caller_body[callsite.block].terminator.take().unwrap();
860 let TerminatorKind::Call { func, args, destination, unwind, target, .. } = terminator.kind
861 else {
862 bug!("unexpected terminator kind {:?}", terminator.kind);
863 };
864
865 let return_block = if let Some(block) = target {
866 let data = BasicBlockData::new(
869 Some(Terminator {
870 source_info: terminator.source_info,
871 kind: TerminatorKind::Goto { target: block },
872 }),
873 caller_body[block].is_cleanup,
874 );
875 Some(caller_body.basic_blocks_mut().push(data))
876 } else {
877 None
878 };
879
880 fn dest_needs_borrow(place: Place<'_>) -> bool {
886 for elem in place.projection.iter() {
887 match elem {
888 ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
889 _ => {}
890 }
891 }
892
893 false
894 }
895
896 let dest = if dest_needs_borrow(destination) {
897 trace!("creating temp for return destination");
898 let dest = Rvalue::Ref(
899 tcx.lifetimes.re_erased,
900 BorrowKind::Mut { kind: MutBorrowKind::Default },
901 destination,
902 );
903 let dest_ty = dest.ty(caller_body, tcx);
904 let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
905 caller_body[callsite.block].statements.push(Statement::new(
906 callsite.source_info,
907 StatementKind::Assign(Box::new((temp, dest))),
908 ));
909 tcx.mk_place_deref(temp)
910 } else {
911 destination
912 };
913
914 let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
917 (false, d)
918 } else {
919 (
920 true,
921 new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
922 )
923 };
924
925 let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
927
928 let mut integrator = Integrator {
929 args: &args,
930 new_locals: caller_body.local_decls.next_index()..,
931 new_scopes: caller_body.source_scopes.next_index()..,
932 new_blocks: caller_body.basic_blocks.next_index()..,
933 destination: destination_local,
934 callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
935 callsite,
936 cleanup_block: unwind,
937 in_cleanup_block: false,
938 return_block,
939 tcx,
940 always_live_locals: UsedInStmtLocals::new(&callee_body).locals,
941 };
942
943 integrator.visit_body(&mut callee_body);
946
947 for local in callee_body.vars_and_temps_iter() {
950 if integrator.always_live_locals.contains(local) {
951 let new_local = integrator.map_local(local);
952 caller_body[callsite.block]
953 .statements
954 .push(Statement::new(callsite.source_info, StatementKind::StorageLive(new_local)));
955 }
956 }
957 if let Some(block) = return_block {
958 let mut n = 0;
961 if remap_destination {
962 caller_body[block].statements.push(Statement::new(
963 callsite.source_info,
964 StatementKind::Assign(Box::new((
965 dest,
966 Rvalue::Use(Operand::Move(destination_local.into())),
967 ))),
968 ));
969 n += 1;
970 }
971 for local in callee_body.vars_and_temps_iter().rev() {
972 if integrator.always_live_locals.contains(local) {
973 let new_local = integrator.map_local(local);
974 caller_body[block].statements.push(Statement::new(
975 callsite.source_info,
976 StatementKind::StorageDead(new_local),
977 ));
978 n += 1;
979 }
980 }
981 caller_body[block].statements.rotate_right(n);
982 }
983
984 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
986 caller_body.source_scopes.append(&mut callee_body.source_scopes);
987
988 if tcx
990 .sess
991 .opts
992 .unstable_opts
993 .inline_mir_preserve_debug
994 .unwrap_or(tcx.sess.opts.debuginfo == DebugInfo::Full)
995 {
996 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
1000 } else {
1001 for bb in callee_body.basic_blocks_mut() {
1002 bb.drop_debuginfo();
1003 }
1004 }
1005 caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
1006
1007 caller_body[callsite.block].terminator = Some(Terminator {
1008 source_info: callsite.source_info,
1009 kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
1010 });
1011
1012 caller_body.required_consts.as_mut().unwrap().extend(
1016 callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
1017 );
1018 let callee_item = MentionedItem::Fn(func.ty(caller_body, tcx));
1026 let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
1027 if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
1028 caller_mentioned_items.remove(idx);
1030 caller_mentioned_items.extend(callee_body.mentioned_items());
1031 } else {
1032 }
1036}
1037
1038fn make_call_args<'tcx, I: Inliner<'tcx>>(
1039 inliner: &I,
1040 args: Box<[Spanned<Operand<'tcx>>]>,
1041 callsite: &CallSite<'tcx>,
1042 caller_body: &mut Body<'tcx>,
1043 callee_body: &Body<'tcx>,
1044 return_block: Option<BasicBlock>,
1045) -> Box<[Local]> {
1046 let tcx = inliner.tcx();
1047
1048 if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1072 let mut args = <_>::into_iter(args);
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)))),
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_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
1276 self.super_retag(kind, place, loc);
1277
1278 if *kind == RetagKind::FnEntry {
1281 *kind = RetagKind::Default;
1282 }
1283 }
1284
1285 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1286 if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1287 statement.kind
1288 {
1289 self.always_live_locals.remove(local);
1290 }
1291 self.super_statement(statement, location);
1292 }
1293
1294 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1295 if !matches!(terminator.kind, TerminatorKind::Return) {
1298 self.super_terminator(terminator, loc);
1299 } else {
1300 self.visit_source_info(&mut terminator.source_info);
1301 }
1302
1303 match terminator.kind {
1304 TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1305 TerminatorKind::Goto { ref mut target } => {
1306 *target = self.map_block(*target);
1307 }
1308 TerminatorKind::SwitchInt { ref mut targets, .. } => {
1309 for tgt in targets.all_targets_mut() {
1310 *tgt = self.map_block(*tgt);
1311 }
1312 }
1313 TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1314 *target = self.map_block(*target);
1315 *unwind = self.map_unwind(*unwind);
1316 }
1317 TerminatorKind::TailCall { .. } => {
1318 unreachable!()
1320 }
1321 TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1322 if let Some(ref mut tgt) = *target {
1323 *tgt = self.map_block(*tgt);
1324 }
1325 *unwind = self.map_unwind(*unwind);
1326 }
1327 TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1328 *target = self.map_block(*target);
1329 *unwind = self.map_unwind(*unwind);
1330 }
1331 TerminatorKind::Return => {
1332 terminator.kind = if let Some(tgt) = self.return_block {
1333 TerminatorKind::Goto { target: tgt }
1334 } else {
1335 TerminatorKind::Unreachable
1336 }
1337 }
1338 TerminatorKind::UnwindResume => {
1339 terminator.kind = match self.cleanup_block {
1340 UnwindAction::Cleanup(tgt) => TerminatorKind::Goto { target: tgt },
1341 UnwindAction::Continue => TerminatorKind::UnwindResume,
1342 UnwindAction::Unreachable => TerminatorKind::Unreachable,
1343 UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1344 };
1345 }
1346 TerminatorKind::UnwindTerminate(_) => {}
1347 TerminatorKind::Unreachable => {}
1348 TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1349 *real_target = self.map_block(*real_target);
1350 *imaginary_target = self.map_block(*imaginary_target);
1351 }
1352 TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1353 {
1355 bug!("False unwinds should have been removed before inlining")
1356 }
1357 TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1358 for tgt in targets.iter_mut() {
1359 *tgt = self.map_block(*tgt);
1360 }
1361 *unwind = self.map_unwind(*unwind);
1362 }
1363 }
1364 }
1365}
1366
1367#[instrument(skip(tcx), level = "debug")]
1368fn try_instance_mir<'tcx>(
1369 tcx: TyCtxt<'tcx>,
1370 instance: InstanceKind<'tcx>,
1371) -> Result<&'tcx Body<'tcx>, &'static str> {
1372 if let ty::InstanceKind::DropGlue(_, Some(ty)) | ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) =
1373 instance
1374 && let ty::Adt(def, args) = ty.kind()
1375 {
1376 let fields = def.all_fields();
1377 for field in fields {
1378 let field_ty = field.ty(tcx, args);
1379 if field_ty.has_param() && field_ty.has_aliases() {
1380 return Err("cannot build drop shim for polymorphic type");
1381 }
1382 }
1383 }
1384 Ok(tcx.instance_mir(instance))
1385}
1386
1387fn body_is_forwarder(body: &Body<'_>) -> bool {
1388 let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1389 else {
1390 return false;
1391 };
1392 if let Some(target) = target {
1393 let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1394 return false;
1395 };
1396 }
1397
1398 let max_blocks = if !body.is_polymorphic {
1399 2
1400 } else if target.is_none() {
1401 3
1402 } else {
1403 4
1404 };
1405 if body.basic_blocks.len() > max_blocks {
1406 return false;
1407 }
1408
1409 body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1410 bb == START_BLOCK
1411 || matches!(
1412 bb_data.terminator().kind,
1413 TerminatorKind::Return
1414 | TerminatorKind::Drop { .. }
1415 | TerminatorKind::UnwindResume
1416 | TerminatorKind::UnwindTerminate(_)
1417 )
1418 })
1419}