rustc_mir_transform/
inline.rs

1//! Inlining pass for MIR functions.
2
3use std::iter;
4use std::ops::{Range, RangeFrom};
5
6use rustc_abi::{ExternAbi, FieldIdx};
7use rustc_attr_parsing::{InlineAttr, OptimizeAttr};
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::DefId;
10use rustc_index::Idx;
11use rustc_index::bit_set::DenseBitSet;
12use rustc_middle::bug;
13use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
14use rustc_middle::mir::visit::*;
15use rustc_middle::mir::*;
16use rustc_middle::ty::{self, Instance, InstanceKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt};
17use rustc_session::config::{DebugInfo, OptLevel};
18use rustc_span::source_map::Spanned;
19use tracing::{debug, instrument, trace, trace_span};
20
21use crate::cost_checker::CostChecker;
22use crate::deref_separator::deref_finder;
23use crate::simplify::simplify_cfg;
24use crate::validate::validate_types;
25use crate::{check_inline, util};
26
27pub(crate) mod cycle;
28
29const TOP_DOWN_DEPTH_LIMIT: usize = 5;
30
31#[derive(Clone, Debug)]
32struct CallSite<'tcx> {
33    callee: Instance<'tcx>,
34    fn_sig: ty::PolyFnSig<'tcx>,
35    block: BasicBlock,
36    source_info: SourceInfo,
37}
38
39// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
40// by custom rustc drivers, running all the steps by themselves. See #114628.
41pub struct Inline;
42
43impl<'tcx> crate::MirPass<'tcx> for Inline {
44    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
45        if let Some(enabled) = sess.opts.unstable_opts.inline_mir {
46            return enabled;
47        }
48
49        match sess.mir_opt_level() {
50            0 | 1 => false,
51            2 => {
52                (sess.opts.optimize == OptLevel::More || sess.opts.optimize == OptLevel::Aggressive)
53                    && sess.opts.incremental == None
54            }
55            _ => true,
56        }
57    }
58
59    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
60        let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
61        let _guard = span.enter();
62        if inline::<NormalInliner<'tcx>>(tcx, body) {
63            debug!("running simplify cfg on {:?}", body.source);
64            simplify_cfg(body);
65            deref_finder(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(body);
101            deref_finder(tcx, body);
102        }
103    }
104}
105
106trait Inliner<'tcx> {
107    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self;
108
109    fn tcx(&self) -> TyCtxt<'tcx>;
110    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
111    fn history(&self) -> &[DefId];
112    fn caller_def_id(&self) -> DefId;
113
114    /// Has the caller body been changed?
115    fn changed(self) -> bool;
116
117    /// Should inlining happen for a given callee?
118    fn should_inline_for_callee(&self, def_id: DefId) -> bool;
119
120    fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool;
121
122    /// Returns inlining decision that is based on the examination of callee MIR body.
123    /// Assumes that codegen attributes have been checked for compatibility already.
124    fn check_callee_mir_body(
125        &self,
126        callsite: &CallSite<'tcx>,
127        callee_body: &Body<'tcx>,
128        callee_attrs: &CodegenFnAttrs,
129    ) -> Result<(), &'static str>;
130
131    // How many callsites in a body are we allowed to inline? We need to limit this in order
132    // to prevent super-linear growth in MIR size.
133    fn inline_limit_for_block(&self) -> Option<usize>;
134
135    /// Called when inlining succeeds.
136    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    /// Called when inlining failed or was not performed.
144    fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str);
145
146    /// Called when the inline limit for a body is reached.
147    fn on_inline_limit_reached(&self) -> bool;
148}
149
150struct ForceInliner<'tcx> {
151    tcx: TyCtxt<'tcx>,
152    typing_env: ty::TypingEnv<'tcx>,
153    /// `DefId` of caller.
154    def_id: DefId,
155    /// Stack of inlined instances.
156    /// We only check the `DefId` and not the args because we want to
157    /// avoid inlining cases of polymorphic recursion.
158    /// The number of `DefId`s is finite, so checking history is enough
159    /// to ensure that we do not loop endlessly while inlining.
160    history: Vec<DefId>,
161    /// Indicates that the caller body has been modified.
162    changed: bool,
163}
164
165impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> {
166    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
167        Self { tcx, typing_env: body.typing_env(tcx), def_id, history: Vec::new(), changed: false }
168    }
169
170    fn tcx(&self) -> TyCtxt<'tcx> {
171        self.tcx
172    }
173
174    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
175        self.typing_env
176    }
177
178    fn history(&self) -> &[DefId] {
179        &self.history
180    }
181
182    fn caller_def_id(&self) -> DefId {
183        self.def_id
184    }
185
186    fn changed(self) -> bool {
187        self.changed
188    }
189
190    fn should_inline_for_callee(&self, def_id: DefId) -> bool {
191        ForceInline::should_run_pass_for_callee(self.tcx(), def_id)
192    }
193
194    fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool {
195        true
196    }
197
198    #[instrument(level = "debug", skip(self, callee_body))]
199    fn check_callee_mir_body(
200        &self,
201        _: &CallSite<'tcx>,
202        callee_body: &Body<'tcx>,
203        callee_attrs: &CodegenFnAttrs,
204    ) -> Result<(), &'static str> {
205        if callee_body.tainted_by_errors.is_some() {
206            return Err("body has errors");
207        }
208
209        let caller_attrs = self.tcx().codegen_fn_attrs(self.caller_def_id());
210        if callee_attrs.instruction_set != caller_attrs.instruction_set
211            && callee_body
212                .basic_blocks
213                .iter()
214                .any(|bb| matches!(bb.terminator().kind, TerminatorKind::InlineAsm { .. }))
215        {
216            // During the attribute checking stage we allow a callee with no
217            // instruction_set assigned to count as compatible with a function that does
218            // assign one. However, during this stage we require an exact match when any
219            // inline-asm is detected. LLVM will still possibly do an inline later on
220            // if the no-attribute function ends up with the same instruction set anyway.
221            Err("cannot move inline-asm across instruction sets")
222        } else {
223            Ok(())
224        }
225    }
226
227    fn inline_limit_for_block(&self) -> Option<usize> {
228        Some(usize::MAX)
229    }
230
231    fn on_inline_success(
232        &mut self,
233        callsite: &CallSite<'tcx>,
234        caller_body: &mut Body<'tcx>,
235        new_blocks: std::ops::Range<BasicBlock>,
236    ) {
237        self.changed = true;
238
239        self.history.push(callsite.callee.def_id());
240        process_blocks(self, caller_body, new_blocks);
241        self.history.pop();
242    }
243
244    fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str) {
245        let tcx = self.tcx();
246        let InlineAttr::Force { attr_span, reason: justification } =
247            tcx.codegen_fn_attrs(callsite.callee.def_id()).inline
248        else {
249            bug!("called on item without required inlining");
250        };
251
252        let call_span = callsite.source_info.span;
253        tcx.dcx().emit_err(crate::errors::ForceInlineFailure {
254            call_span,
255            attr_span,
256            caller_span: tcx.def_span(self.def_id),
257            caller: tcx.def_path_str(self.def_id),
258            callee_span: tcx.def_span(callsite.callee.def_id()),
259            callee: tcx.def_path_str(callsite.callee.def_id()),
260            reason,
261            justification: justification.map(|sym| crate::errors::ForceInlineJustification { sym }),
262        });
263    }
264
265    fn on_inline_limit_reached(&self) -> bool {
266        false
267    }
268}
269
270struct NormalInliner<'tcx> {
271    tcx: TyCtxt<'tcx>,
272    typing_env: ty::TypingEnv<'tcx>,
273    /// `DefId` of caller.
274    def_id: DefId,
275    /// Stack of inlined instances.
276    /// We only check the `DefId` and not the args because we want to
277    /// avoid inlining cases of polymorphic recursion.
278    /// The number of `DefId`s is finite, so checking history is enough
279    /// to ensure that we do not loop endlessly while inlining.
280    history: Vec<DefId>,
281    /// Indicates that the caller body has been modified.
282    changed: bool,
283    /// Indicates that the caller is #[inline] and just calls another function,
284    /// and thus we can inline less into it as it'll be inlined itself.
285    caller_is_inline_forwarder: bool,
286}
287
288impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> {
289    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self {
290        let typing_env = body.typing_env(tcx);
291        let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
292
293        Self {
294            tcx,
295            typing_env,
296            def_id,
297            history: Vec::new(),
298            changed: false,
299            caller_is_inline_forwarder: matches!(
300                codegen_fn_attrs.inline,
301                InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. }
302            ) && body_is_forwarder(body),
303        }
304    }
305
306    fn tcx(&self) -> TyCtxt<'tcx> {
307        self.tcx
308    }
309
310    fn caller_def_id(&self) -> DefId {
311        self.def_id
312    }
313
314    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
315        self.typing_env
316    }
317
318    fn history(&self) -> &[DefId] {
319        &self.history
320    }
321
322    fn changed(self) -> bool {
323        self.changed
324    }
325
326    fn should_inline_for_callee(&self, _: DefId) -> bool {
327        true
328    }
329
330    fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool {
331        // Avoid inlining into coroutines, since their `optimized_mir` is used for layout computation,
332        // which can create a cycle, even when no attempt is made to inline the function in the other
333        // direction.
334        if body.coroutine.is_some() {
335            return false;
336        }
337
338        true
339    }
340
341    #[instrument(level = "debug", skip(self, callee_body))]
342    fn check_callee_mir_body(
343        &self,
344        callsite: &CallSite<'tcx>,
345        callee_body: &Body<'tcx>,
346        callee_attrs: &CodegenFnAttrs,
347    ) -> Result<(), &'static str> {
348        let tcx = self.tcx();
349
350        if let Some(_) = callee_body.tainted_by_errors {
351            return Err("body has errors");
352        }
353
354        let mut threshold = if self.caller_is_inline_forwarder {
355            tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30)
356        } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) {
357            tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100)
358        } else {
359            tcx.sess.opts.unstable_opts.inline_mir_threshold.unwrap_or(50)
360        };
361
362        // Give a bonus functions with a small number of blocks,
363        // We normally have two or three blocks for even
364        // very small functions.
365        if callee_body.basic_blocks.len() <= 3 {
366            threshold += threshold / 4;
367        }
368        debug!("    final inline threshold = {}", threshold);
369
370        // FIXME: Give a bonus to functions with only a single caller
371
372        let mut checker =
373            CostChecker::new(tcx, self.typing_env(), Some(callsite.callee), callee_body);
374
375        checker.add_function_level_costs();
376
377        // Traverse the MIR manually so we can account for the effects of inlining on the CFG.
378        let mut work_list = vec![START_BLOCK];
379        let mut visited = DenseBitSet::new_empty(callee_body.basic_blocks.len());
380        while let Some(bb) = work_list.pop() {
381            if !visited.insert(bb.index()) {
382                continue;
383            }
384
385            let blk = &callee_body.basic_blocks[bb];
386            checker.visit_basic_block_data(bb, blk);
387
388            let term = blk.terminator();
389            let caller_attrs = tcx.codegen_fn_attrs(self.caller_def_id());
390            if let TerminatorKind::Drop { ref place, target, unwind, replace: _ } = term.kind {
391                work_list.push(target);
392
393                // If the place doesn't actually need dropping, treat it like a regular goto.
394                let ty = callsite
395                    .callee
396                    .instantiate_mir(tcx, ty::EarlyBinder::bind(&place.ty(callee_body, tcx).ty));
397                if ty.needs_drop(tcx, self.typing_env())
398                    && let UnwindAction::Cleanup(unwind) = unwind
399                {
400                    work_list.push(unwind);
401                }
402            } else if callee_attrs.instruction_set != caller_attrs.instruction_set
403                && matches!(term.kind, TerminatorKind::InlineAsm { .. })
404            {
405                // During the attribute checking stage we allow a callee with no
406                // instruction_set assigned to count as compatible with a function that does
407                // assign one. However, during this stage we require an exact match when any
408                // inline-asm is detected. LLVM will still possibly do an inline later on
409                // if the no-attribute function ends up with the same instruction set anyway.
410                return Err("cannot move inline-asm across instruction sets");
411            } else if let TerminatorKind::TailCall { .. } = term.kind {
412                // FIXME(explicit_tail_calls): figure out how exactly functions containing tail
413                // calls can be inlined (and if they even should)
414                return Err("can't inline functions with tail calls");
415            } else {
416                work_list.extend(term.successors())
417            }
418        }
419
420        // N.B. We still apply our cost threshold to #[inline(always)] functions.
421        // That attribute is often applied to very large functions that exceed LLVM's (very
422        // generous) inlining threshold. Such functions are very poor MIR inlining candidates.
423        // Always inlining #[inline(always)] functions in MIR, on net, slows down the compiler.
424        let cost = checker.cost();
425        if cost <= threshold {
426            debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
427            Ok(())
428        } else {
429            debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
430            Err("cost above threshold")
431        }
432    }
433
434    fn inline_limit_for_block(&self) -> Option<usize> {
435        match self.history.len() {
436            0 => Some(usize::MAX),
437            1..=TOP_DOWN_DEPTH_LIMIT => Some(1),
438            _ => None,
439        }
440    }
441
442    fn on_inline_success(
443        &mut self,
444        callsite: &CallSite<'tcx>,
445        caller_body: &mut Body<'tcx>,
446        new_blocks: std::ops::Range<BasicBlock>,
447    ) {
448        self.changed = true;
449
450        self.history.push(callsite.callee.def_id());
451        process_blocks(self, caller_body, new_blocks);
452        self.history.pop();
453    }
454
455    fn on_inline_limit_reached(&self) -> bool {
456        true
457    }
458
459    fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {}
460}
461
462fn inline<'tcx, T: Inliner<'tcx>>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
463    let def_id = body.source.def_id();
464
465    // Only do inlining into fn bodies.
466    if !tcx.hir().body_owner_kind(def_id).is_fn_or_closure() {
467        return false;
468    }
469
470    let mut inliner = T::new(tcx, def_id, body);
471    if !inliner.check_caller_mir_body(body) {
472        return false;
473    }
474
475    let blocks = START_BLOCK..body.basic_blocks.next_index();
476    process_blocks(&mut inliner, body, blocks);
477    inliner.changed()
478}
479
480fn process_blocks<'tcx, I: Inliner<'tcx>>(
481    inliner: &mut I,
482    caller_body: &mut Body<'tcx>,
483    blocks: Range<BasicBlock>,
484) {
485    let Some(inline_limit) = inliner.inline_limit_for_block() else { return };
486    let mut inlined_count = 0;
487    for bb in blocks {
488        let bb_data = &caller_body[bb];
489        if bb_data.is_cleanup {
490            continue;
491        }
492
493        let Some(callsite) = resolve_callsite(inliner, caller_body, bb, bb_data) else {
494            continue;
495        };
496
497        let span = trace_span!("process_blocks", %callsite.callee, ?bb);
498        let _guard = span.enter();
499
500        match try_inlining(inliner, caller_body, &callsite) {
501            Err(reason) => {
502                debug!("not-inlined {} [{}]", callsite.callee, reason);
503                inliner.on_inline_failure(&callsite, reason);
504            }
505            Ok(new_blocks) => {
506                debug!("inlined {}", callsite.callee);
507                inliner.on_inline_success(&callsite, caller_body, new_blocks);
508
509                inlined_count += 1;
510                if inlined_count == inline_limit {
511                    if inliner.on_inline_limit_reached() {
512                        return;
513                    }
514                }
515            }
516        }
517    }
518}
519
520fn resolve_callsite<'tcx, I: Inliner<'tcx>>(
521    inliner: &I,
522    caller_body: &Body<'tcx>,
523    bb: BasicBlock,
524    bb_data: &BasicBlockData<'tcx>,
525) -> Option<CallSite<'tcx>> {
526    let tcx = inliner.tcx();
527    // Only consider direct calls to functions
528    let terminator = bb_data.terminator();
529
530    // FIXME(explicit_tail_calls): figure out if we can inline tail calls
531    if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
532        let func_ty = func.ty(caller_body, tcx);
533        if let ty::FnDef(def_id, args) = *func_ty.kind() {
534            if !inliner.should_inline_for_callee(def_id) {
535                debug!("not enabled");
536                return None;
537            }
538
539            // To resolve an instance its args have to be fully normalized.
540            let args = tcx.try_normalize_erasing_regions(inliner.typing_env(), args).ok()?;
541            let callee =
542                Instance::try_resolve(tcx, inliner.typing_env(), def_id, args).ok().flatten()?;
543
544            if let InstanceKind::Virtual(..) | InstanceKind::Intrinsic(_) = callee.def {
545                return None;
546            }
547
548            if inliner.history().contains(&callee.def_id()) {
549                return None;
550            }
551
552            let fn_sig = tcx.fn_sig(def_id).instantiate(tcx, args);
553
554            // Additionally, check that the body that we're inlining actually agrees
555            // with the ABI of the trait that the item comes from.
556            if let InstanceKind::Item(instance_def_id) = callee.def
557                && tcx.def_kind(instance_def_id) == DefKind::AssocFn
558                && let instance_fn_sig = tcx.fn_sig(instance_def_id).skip_binder()
559                && instance_fn_sig.abi() != fn_sig.abi()
560            {
561                return None;
562            }
563
564            let source_info = SourceInfo { span: fn_span, ..terminator.source_info };
565
566            return Some(CallSite { callee, fn_sig, block: bb, source_info });
567        }
568    }
569
570    None
571}
572
573/// Attempts to inline a callsite into the caller body. When successful returns basic blocks
574/// containing the inlined body. Otherwise returns an error describing why inlining didn't take
575/// place.
576fn try_inlining<'tcx, I: Inliner<'tcx>>(
577    inliner: &I,
578    caller_body: &mut Body<'tcx>,
579    callsite: &CallSite<'tcx>,
580) -> Result<std::ops::Range<BasicBlock>, &'static str> {
581    let tcx = inliner.tcx();
582    check_mir_is_available(inliner, caller_body, callsite.callee)?;
583
584    let callee_attrs = tcx.codegen_fn_attrs(callsite.callee.def_id());
585    check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?;
586    check_codegen_attributes(inliner, callsite, callee_attrs)?;
587
588    let terminator = caller_body[callsite.block].terminator.as_ref().unwrap();
589    let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() };
590    let destination_ty = destination.ty(&caller_body.local_decls, tcx).ty;
591    for arg in args {
592        if !arg.node.ty(&caller_body.local_decls, tcx).is_sized(tcx, inliner.typing_env()) {
593            // We do not allow inlining functions with unsized params. Inlining these functions
594            // could create unsized locals, which are unsound and being phased out.
595            return Err("call has unsized argument");
596        }
597    }
598
599    let callee_body = try_instance_mir(tcx, callsite.callee.def)?;
600    check_inline::is_inline_valid_on_body(tcx, callee_body)?;
601    inliner.check_callee_mir_body(callsite, callee_body, callee_attrs)?;
602
603    let Ok(callee_body) = callsite.callee.try_instantiate_mir_and_normalize_erasing_regions(
604        tcx,
605        inliner.typing_env(),
606        ty::EarlyBinder::bind(callee_body.clone()),
607    ) else {
608        debug!("failed to normalize callee body");
609        return Err("implementation limitation");
610    };
611
612    // Normally, this shouldn't be required, but trait normalization failure can create a
613    // validation ICE.
614    if !validate_types(tcx, inliner.typing_env(), &callee_body, &caller_body).is_empty() {
615        debug!("failed to validate callee body");
616        return Err("implementation limitation");
617    }
618
619    // Check call signature compatibility.
620    // Normally, this shouldn't be required, but trait normalization failure can create a
621    // validation ICE.
622    let output_type = callee_body.return_ty();
623    if !util::sub_types(tcx, inliner.typing_env(), output_type, destination_ty) {
624        trace!(?output_type, ?destination_ty);
625        debug!("failed to normalize return type");
626        return Err("implementation limitation");
627    }
628    if callsite.fn_sig.abi() == ExternAbi::RustCall {
629        // FIXME: Don't inline user-written `extern "rust-call"` functions,
630        // since this is generally perf-negative on rustc, and we hope that
631        // LLVM will inline these functions instead.
632        if callee_body.spread_arg.is_some() {
633            return Err("user-written rust-call functions");
634        }
635
636        let (self_arg, arg_tuple) = match &args[..] {
637            [arg_tuple] => (None, arg_tuple),
638            [self_arg, arg_tuple] => (Some(self_arg), arg_tuple),
639            _ => bug!("Expected `rust-call` to have 1 or 2 args"),
640        };
641
642        let self_arg_ty = self_arg.map(|self_arg| self_arg.node.ty(&caller_body.local_decls, tcx));
643
644        let arg_tuple_ty = arg_tuple.node.ty(&caller_body.local_decls, tcx);
645        let ty::Tuple(arg_tuple_tys) = *arg_tuple_ty.kind() else {
646            bug!("Closure arguments are not passed as a tuple");
647        };
648
649        for (arg_ty, input) in
650            self_arg_ty.into_iter().chain(arg_tuple_tys).zip(callee_body.args_iter())
651        {
652            let input_type = callee_body.local_decls[input].ty;
653            if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
654                trace!(?arg_ty, ?input_type);
655                debug!("failed to normalize tuple argument type");
656                return Err("implementation limitation");
657            }
658        }
659    } else {
660        for (arg, input) in args.iter().zip(callee_body.args_iter()) {
661            let input_type = callee_body.local_decls[input].ty;
662            let arg_ty = arg.node.ty(&caller_body.local_decls, tcx);
663            if !util::sub_types(tcx, inliner.typing_env(), input_type, arg_ty) {
664                trace!(?arg_ty, ?input_type);
665                debug!("failed to normalize argument type");
666                return Err("implementation limitation");
667            }
668        }
669    }
670
671    let old_blocks = caller_body.basic_blocks.next_index();
672    inline_call(inliner, caller_body, callsite, callee_body);
673    let new_blocks = old_blocks..caller_body.basic_blocks.next_index();
674
675    Ok(new_blocks)
676}
677
678fn check_mir_is_available<'tcx, I: Inliner<'tcx>>(
679    inliner: &I,
680    caller_body: &Body<'tcx>,
681    callee: Instance<'tcx>,
682) -> Result<(), &'static str> {
683    let caller_def_id = caller_body.source.def_id();
684    let callee_def_id = callee.def_id();
685    if callee_def_id == caller_def_id {
686        return Err("self-recursion");
687    }
688
689    match callee.def {
690        InstanceKind::Item(_) => {
691            // If there is no MIR available (either because it was not in metadata or
692            // because it has no MIR because it's an extern function), then the inliner
693            // won't cause cycles on this.
694            if !inliner.tcx().is_mir_available(callee_def_id) {
695                debug!("item MIR unavailable");
696                return Err("implementation limitation");
697            }
698        }
699        // These have no own callable MIR.
700        InstanceKind::Intrinsic(_) | InstanceKind::Virtual(..) => {
701            debug!("instance without MIR (intrinsic / virtual)");
702            return Err("implementation limitation");
703        }
704
705        // FIXME(#127030): `ConstParamHasTy` has bad interactions with
706        // the drop shim builder, which does not evaluate predicates in
707        // the correct param-env for types being dropped. Stall resolving
708        // the MIR for this instance until all of its const params are
709        // substituted.
710        InstanceKind::DropGlue(_, Some(ty)) if ty.has_type_flags(TypeFlags::HAS_CT_PARAM) => {
711            debug!("still needs substitution");
712            return Err("implementation limitation");
713        }
714
715        // This cannot result in an immediate cycle since the callee MIR is a shim, which does
716        // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
717        // do not need to catch this here, we can wait until the inliner decides to continue
718        // inlining a second time.
719        InstanceKind::VTableShim(_)
720        | InstanceKind::ReifyShim(..)
721        | InstanceKind::FnPtrShim(..)
722        | InstanceKind::ClosureOnceShim { .. }
723        | InstanceKind::ConstructCoroutineInClosureShim { .. }
724        | InstanceKind::DropGlue(..)
725        | InstanceKind::CloneShim(..)
726        | InstanceKind::ThreadLocalShim(..)
727        | InstanceKind::FnPtrAddrShim(..)
728        | InstanceKind::AsyncDropGlueCtorShim(..) => return Ok(()),
729    }
730
731    if inliner.tcx().is_constructor(callee_def_id) {
732        trace!("constructors always have MIR");
733        // Constructor functions cannot cause a query cycle.
734        return Ok(());
735    }
736
737    if callee_def_id.is_local()
738        && !inliner
739            .tcx()
740            .is_lang_item(inliner.tcx().parent(caller_def_id), rustc_hir::LangItem::FnOnce)
741    {
742        // If we know for sure that the function we're calling will itself try to
743        // call us, then we avoid inlining that function.
744        if inliner.tcx().mir_callgraph_reachable((callee, caller_def_id.expect_local())) {
745            debug!("query cycle avoidance");
746            return Err("caller might be reachable from callee");
747        }
748
749        Ok(())
750    } else {
751        // This cannot result in an immediate cycle since the callee MIR is from another crate
752        // and is already optimized. Any subsequent inlining may cause cycles, but we do
753        // not need to catch this here, we can wait until the inliner decides to continue
754        // inlining a second time.
755        trace!("functions from other crates always have MIR");
756        Ok(())
757    }
758}
759
760/// Returns an error if inlining is not possible based on codegen attributes alone. A success
761/// indicates that inlining decision should be based on other criteria.
762fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>(
763    inliner: &I,
764    callsite: &CallSite<'tcx>,
765    callee_attrs: &CodegenFnAttrs,
766) -> Result<(), &'static str> {
767    let tcx = inliner.tcx();
768    if let InlineAttr::Never = callee_attrs.inline {
769        return Err("never inline attribute");
770    }
771
772    if let OptimizeAttr::DoNotOptimize = callee_attrs.optimize {
773        return Err("has DoNotOptimize attribute");
774    }
775
776    // Reachability pass defines which functions are eligible for inlining. Generally inlining
777    // other functions is incorrect because they could reference symbols that aren't exported.
778    let is_generic = callsite.callee.args.non_erasable_generics().next().is_some();
779    if !is_generic && !tcx.cross_crate_inlinable(callsite.callee.def_id()) {
780        return Err("not exported");
781    }
782
783    let codegen_fn_attrs = tcx.codegen_fn_attrs(inliner.caller_def_id());
784    if callee_attrs.no_sanitize != codegen_fn_attrs.no_sanitize {
785        return Err("incompatible sanitizer set");
786    }
787
788    // Two functions are compatible if the callee has no attribute (meaning
789    // that it's codegen agnostic), or sets an attribute that is identical
790    // to this function's attribute.
791    if callee_attrs.instruction_set.is_some()
792        && callee_attrs.instruction_set != codegen_fn_attrs.instruction_set
793    {
794        return Err("incompatible instruction set");
795    }
796
797    let callee_feature_names = callee_attrs.target_features.iter().map(|f| f.name);
798    let this_feature_names = codegen_fn_attrs.target_features.iter().map(|f| f.name);
799    if callee_feature_names.ne(this_feature_names) {
800        // In general it is not correct to inline a callee with target features that are a
801        // subset of the caller. This is because the callee might contain calls, and the ABI of
802        // those calls depends on the target features of the surrounding function. By moving a
803        // `Call` terminator from one MIR body to another with more target features, we might
804        // change the ABI of that call!
805        return Err("incompatible target features");
806    }
807
808    Ok(())
809}
810
811fn inline_call<'tcx, I: Inliner<'tcx>>(
812    inliner: &I,
813    caller_body: &mut Body<'tcx>,
814    callsite: &CallSite<'tcx>,
815    mut callee_body: Body<'tcx>,
816) {
817    let tcx = inliner.tcx();
818    let terminator = caller_body[callsite.block].terminator.take().unwrap();
819    let TerminatorKind::Call { func, args, destination, unwind, target, .. } = terminator.kind
820    else {
821        bug!("unexpected terminator kind {:?}", terminator.kind);
822    };
823
824    let return_block = if let Some(block) = target {
825        // Prepare a new block for code that should execute when call returns. We don't use
826        // target block directly since it might have other predecessors.
827        let data = BasicBlockData::new(
828            Some(Terminator {
829                source_info: terminator.source_info,
830                kind: TerminatorKind::Goto { target: block },
831            }),
832            caller_body[block].is_cleanup,
833        );
834        Some(caller_body.basic_blocks_mut().push(data))
835    } else {
836        None
837    };
838
839    // If the call is something like `a[*i] = f(i)`, where
840    // `i : &mut usize`, then just duplicating the `a[*i]`
841    // Place could result in two different locations if `f`
842    // writes to `i`. To prevent this we need to create a temporary
843    // borrow of the place and pass the destination as `*temp` instead.
844    fn dest_needs_borrow(place: Place<'_>) -> bool {
845        for elem in place.projection.iter() {
846            match elem {
847                ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
848                _ => {}
849            }
850        }
851
852        false
853    }
854
855    let dest = if dest_needs_borrow(destination) {
856        trace!("creating temp for return destination");
857        let dest = Rvalue::Ref(
858            tcx.lifetimes.re_erased,
859            BorrowKind::Mut { kind: MutBorrowKind::Default },
860            destination,
861        );
862        let dest_ty = dest.ty(caller_body, tcx);
863        let temp = Place::from(new_call_temp(caller_body, callsite, dest_ty, return_block));
864        caller_body[callsite.block].statements.push(Statement {
865            source_info: callsite.source_info,
866            kind: StatementKind::Assign(Box::new((temp, dest))),
867        });
868        tcx.mk_place_deref(temp)
869    } else {
870        destination
871    };
872
873    // Always create a local to hold the destination, as `RETURN_PLACE` may appear
874    // where a full `Place` is not allowed.
875    let (remap_destination, destination_local) = if let Some(d) = dest.as_local() {
876        (false, d)
877    } else {
878        (
879            true,
880            new_call_temp(caller_body, callsite, destination.ty(caller_body, tcx).ty, return_block),
881        )
882    };
883
884    // Copy the arguments if needed.
885    let args = make_call_args(inliner, args, callsite, caller_body, &callee_body, return_block);
886
887    let mut integrator = Integrator {
888        args: &args,
889        new_locals: Local::new(caller_body.local_decls.len())..,
890        new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
891        new_blocks: BasicBlock::new(caller_body.basic_blocks.len())..,
892        destination: destination_local,
893        callsite_scope: caller_body.source_scopes[callsite.source_info.scope].clone(),
894        callsite,
895        cleanup_block: unwind,
896        in_cleanup_block: false,
897        return_block,
898        tcx,
899        always_live_locals: DenseBitSet::new_filled(callee_body.local_decls.len()),
900    };
901
902    // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
903    // (or existing ones, in a few special cases) in the caller.
904    integrator.visit_body(&mut callee_body);
905
906    // If there are any locals without storage markers, give them storage only for the
907    // duration of the call.
908    for local in callee_body.vars_and_temps_iter() {
909        if integrator.always_live_locals.contains(local) {
910            let new_local = integrator.map_local(local);
911            caller_body[callsite.block].statements.push(Statement {
912                source_info: callsite.source_info,
913                kind: StatementKind::StorageLive(new_local),
914            });
915        }
916    }
917    if let Some(block) = return_block {
918        // To avoid repeated O(n) insert, push any new statements to the end and rotate
919        // the slice once.
920        let mut n = 0;
921        if remap_destination {
922            caller_body[block].statements.push(Statement {
923                source_info: callsite.source_info,
924                kind: StatementKind::Assign(Box::new((
925                    dest,
926                    Rvalue::Use(Operand::Move(destination_local.into())),
927                ))),
928            });
929            n += 1;
930        }
931        for local in callee_body.vars_and_temps_iter().rev() {
932            if integrator.always_live_locals.contains(local) {
933                let new_local = integrator.map_local(local);
934                caller_body[block].statements.push(Statement {
935                    source_info: callsite.source_info,
936                    kind: StatementKind::StorageDead(new_local),
937                });
938                n += 1;
939            }
940        }
941        caller_body[block].statements.rotate_right(n);
942    }
943
944    // Insert all of the (mapped) parts of the callee body into the caller.
945    caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
946    caller_body.source_scopes.append(&mut callee_body.source_scopes);
947    if tcx
948        .sess
949        .opts
950        .unstable_opts
951        .inline_mir_preserve_debug
952        .unwrap_or(tcx.sess.opts.debuginfo != DebugInfo::None)
953    {
954        // Note that we need to preserve these in the standard library so that
955        // people working on rust can build with or without debuginfo while
956        // still getting consistent results from the mir-opt tests.
957        caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
958    }
959    caller_body.basic_blocks_mut().append(callee_body.basic_blocks_mut());
960
961    caller_body[callsite.block].terminator = Some(Terminator {
962        source_info: callsite.source_info,
963        kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
964    });
965
966    // Copy required constants from the callee_body into the caller_body. Although we are only
967    // pushing unevaluated consts to `required_consts`, here they may have been evaluated
968    // because we are calling `instantiate_and_normalize_erasing_regions` -- so we filter again.
969    caller_body.required_consts.as_mut().unwrap().extend(
970        callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()),
971    );
972    // Now that we incorporated the callee's `required_consts`, we can remove the callee from
973    // `mentioned_items` -- but we have to take their `mentioned_items` in return. This does
974    // some extra work here to save the monomorphization collector work later. It helps a lot,
975    // since monomorphization can avoid a lot of work when the "mentioned items" are similar to
976    // the actually used items. By doing this we can entirely avoid visiting the callee!
977    // We need to reconstruct the `required_item` for the callee so that we can find and
978    // remove it.
979    let callee_item = MentionedItem::Fn(func.ty(caller_body, tcx));
980    let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap();
981    if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) {
982        // We found the callee, so remove it and add its items instead.
983        caller_mentioned_items.remove(idx);
984        caller_mentioned_items.extend(callee_body.mentioned_items());
985    } else {
986        // If we can't find the callee, there's no point in adding its items. Probably it
987        // already got removed by being inlined elsewhere in the same function, so we already
988        // took its items.
989    }
990}
991
992fn make_call_args<'tcx, I: Inliner<'tcx>>(
993    inliner: &I,
994    args: Box<[Spanned<Operand<'tcx>>]>,
995    callsite: &CallSite<'tcx>,
996    caller_body: &mut Body<'tcx>,
997    callee_body: &Body<'tcx>,
998    return_block: Option<BasicBlock>,
999) -> Box<[Local]> {
1000    let tcx = inliner.tcx();
1001
1002    // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
1003    // The caller provides the arguments wrapped up in a tuple:
1004    //
1005    //     tuple_tmp = (a, b, c)
1006    //     Fn::call(closure_ref, tuple_tmp)
1007    //
1008    // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
1009    // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
1010    // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
1011    // a vector like
1012    //
1013    //     [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
1014    //
1015    // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
1016    // if we "spill" that into *another* temporary, so that we can map the argument
1017    // variable in the callee MIR directly to an argument variable on our side.
1018    // So we introduce temporaries like:
1019    //
1020    //     tmp0 = tuple_tmp.0
1021    //     tmp1 = tuple_tmp.1
1022    //     tmp2 = tuple_tmp.2
1023    //
1024    // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
1025    if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
1026        // FIXME(edition_2024): switch back to a normal method call.
1027        let mut args = <_>::into_iter(args);
1028        let self_ = create_temp_if_necessary(
1029            inliner,
1030            args.next().unwrap().node,
1031            callsite,
1032            caller_body,
1033            return_block,
1034        );
1035        let tuple = create_temp_if_necessary(
1036            inliner,
1037            args.next().unwrap().node,
1038            callsite,
1039            caller_body,
1040            return_block,
1041        );
1042        assert!(args.next().is_none());
1043
1044        let tuple = Place::from(tuple);
1045        let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
1046            bug!("Closure arguments are not passed as a tuple");
1047        };
1048
1049        // The `closure_ref` in our example above.
1050        let closure_ref_arg = iter::once(self_);
1051
1052        // The `tmp0`, `tmp1`, and `tmp2` in our example above.
1053        let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
1054            // This is e.g., `tuple_tmp.0` in our example above.
1055            let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
1056
1057            // Spill to a local to make e.g., `tmp0`.
1058            create_temp_if_necessary(inliner, tuple_field, callsite, caller_body, return_block)
1059        });
1060
1061        closure_ref_arg.chain(tuple_tmp_args).collect()
1062    } else {
1063        // FIXME(edition_2024): switch back to a normal method call.
1064        <_>::into_iter(args)
1065            .map(|a| create_temp_if_necessary(inliner, a.node, callsite, caller_body, return_block))
1066            .collect()
1067    }
1068}
1069
1070/// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh temporary `T` and an
1071/// instruction `T = arg`, and returns `T`.
1072fn create_temp_if_necessary<'tcx, I: Inliner<'tcx>>(
1073    inliner: &I,
1074    arg: Operand<'tcx>,
1075    callsite: &CallSite<'tcx>,
1076    caller_body: &mut Body<'tcx>,
1077    return_block: Option<BasicBlock>,
1078) -> Local {
1079    // Reuse the operand if it is a moved temporary.
1080    if let Operand::Move(place) = &arg
1081        && let Some(local) = place.as_local()
1082        && caller_body.local_kind(local) == LocalKind::Temp
1083    {
1084        return local;
1085    }
1086
1087    // Otherwise, create a temporary for the argument.
1088    trace!("creating temp for argument {:?}", arg);
1089    let arg_ty = arg.ty(caller_body, inliner.tcx());
1090    let local = new_call_temp(caller_body, callsite, arg_ty, return_block);
1091    caller_body[callsite.block].statements.push(Statement {
1092        source_info: callsite.source_info,
1093        kind: StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg)))),
1094    });
1095    local
1096}
1097
1098/// Introduces a new temporary into the caller body that is live for the duration of the call.
1099fn new_call_temp<'tcx>(
1100    caller_body: &mut Body<'tcx>,
1101    callsite: &CallSite<'tcx>,
1102    ty: Ty<'tcx>,
1103    return_block: Option<BasicBlock>,
1104) -> Local {
1105    let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
1106
1107    caller_body[callsite.block].statements.push(Statement {
1108        source_info: callsite.source_info,
1109        kind: StatementKind::StorageLive(local),
1110    });
1111
1112    if let Some(block) = return_block {
1113        caller_body[block].statements.insert(
1114            0,
1115            Statement {
1116                source_info: callsite.source_info,
1117                kind: StatementKind::StorageDead(local),
1118            },
1119        );
1120    }
1121
1122    local
1123}
1124
1125/**
1126 * Integrator.
1127 *
1128 * Integrates blocks from the callee function into the calling function.
1129 * Updates block indices, references to locals and other control flow
1130 * stuff.
1131*/
1132struct Integrator<'a, 'tcx> {
1133    args: &'a [Local],
1134    new_locals: RangeFrom<Local>,
1135    new_scopes: RangeFrom<SourceScope>,
1136    new_blocks: RangeFrom<BasicBlock>,
1137    destination: Local,
1138    callsite_scope: SourceScopeData<'tcx>,
1139    callsite: &'a CallSite<'tcx>,
1140    cleanup_block: UnwindAction,
1141    in_cleanup_block: bool,
1142    return_block: Option<BasicBlock>,
1143    tcx: TyCtxt<'tcx>,
1144    always_live_locals: DenseBitSet<Local>,
1145}
1146
1147impl Integrator<'_, '_> {
1148    fn map_local(&self, local: Local) -> Local {
1149        let new = if local == RETURN_PLACE {
1150            self.destination
1151        } else {
1152            let idx = local.index() - 1;
1153            if idx < self.args.len() {
1154                self.args[idx]
1155            } else {
1156                Local::new(self.new_locals.start.index() + (idx - self.args.len()))
1157            }
1158        };
1159        trace!("mapping local `{:?}` to `{:?}`", local, new);
1160        new
1161    }
1162
1163    fn map_scope(&self, scope: SourceScope) -> SourceScope {
1164        let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
1165        trace!("mapping scope `{:?}` to `{:?}`", scope, new);
1166        new
1167    }
1168
1169    fn map_block(&self, block: BasicBlock) -> BasicBlock {
1170        let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
1171        trace!("mapping block `{:?}` to `{:?}`", block, new);
1172        new
1173    }
1174
1175    fn map_unwind(&self, unwind: UnwindAction) -> UnwindAction {
1176        if self.in_cleanup_block {
1177            match unwind {
1178                UnwindAction::Cleanup(_) | UnwindAction::Continue => {
1179                    bug!("cleanup on cleanup block");
1180                }
1181                UnwindAction::Unreachable | UnwindAction::Terminate(_) => return unwind,
1182            }
1183        }
1184
1185        match unwind {
1186            UnwindAction::Unreachable | UnwindAction::Terminate(_) => unwind,
1187            UnwindAction::Cleanup(target) => UnwindAction::Cleanup(self.map_block(target)),
1188            // Add an unwind edge to the original call's cleanup block
1189            UnwindAction::Continue => self.cleanup_block,
1190        }
1191    }
1192}
1193
1194impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
1195    fn tcx(&self) -> TyCtxt<'tcx> {
1196        self.tcx
1197    }
1198
1199    fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
1200        *local = self.map_local(*local);
1201    }
1202
1203    fn visit_source_scope_data(&mut self, scope_data: &mut SourceScopeData<'tcx>) {
1204        self.super_source_scope_data(scope_data);
1205        if scope_data.parent_scope.is_none() {
1206            // Attach the outermost callee scope as a child of the callsite
1207            // scope, via the `parent_scope` and `inlined_parent_scope` chains.
1208            scope_data.parent_scope = Some(self.callsite.source_info.scope);
1209            assert_eq!(scope_data.inlined_parent_scope, None);
1210            scope_data.inlined_parent_scope = if self.callsite_scope.inlined.is_some() {
1211                Some(self.callsite.source_info.scope)
1212            } else {
1213                self.callsite_scope.inlined_parent_scope
1214            };
1215
1216            // Mark the outermost callee scope as an inlined one.
1217            assert_eq!(scope_data.inlined, None);
1218            scope_data.inlined = Some((self.callsite.callee, self.callsite.source_info.span));
1219        } else if scope_data.inlined_parent_scope.is_none() {
1220            // Make it easy to find the scope with `inlined` set above.
1221            scope_data.inlined_parent_scope = Some(self.map_scope(OUTERMOST_SOURCE_SCOPE));
1222        }
1223    }
1224
1225    fn visit_source_scope(&mut self, scope: &mut SourceScope) {
1226        *scope = self.map_scope(*scope);
1227    }
1228
1229    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
1230        self.in_cleanup_block = data.is_cleanup;
1231        self.super_basic_block_data(block, data);
1232        self.in_cleanup_block = false;
1233    }
1234
1235    fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
1236        self.super_retag(kind, place, loc);
1237
1238        // We have to patch all inlined retags to be aware that they are no longer
1239        // happening on function entry.
1240        if *kind == RetagKind::FnEntry {
1241            *kind = RetagKind::Default;
1242        }
1243    }
1244
1245    fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1246        if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
1247            statement.kind
1248        {
1249            self.always_live_locals.remove(local);
1250        }
1251        self.super_statement(statement, location);
1252    }
1253
1254    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
1255        // Don't try to modify the implicit `_0` access on return (`return` terminators are
1256        // replaced down below anyways).
1257        if !matches!(terminator.kind, TerminatorKind::Return) {
1258            self.super_terminator(terminator, loc);
1259        } else {
1260            self.visit_source_info(&mut terminator.source_info);
1261        }
1262
1263        match terminator.kind {
1264            TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => bug!(),
1265            TerminatorKind::Goto { ref mut target } => {
1266                *target = self.map_block(*target);
1267            }
1268            TerminatorKind::SwitchInt { ref mut targets, .. } => {
1269                for tgt in targets.all_targets_mut() {
1270                    *tgt = self.map_block(*tgt);
1271                }
1272            }
1273            TerminatorKind::Drop { ref mut target, ref mut unwind, .. } => {
1274                *target = self.map_block(*target);
1275                *unwind = self.map_unwind(*unwind);
1276            }
1277            TerminatorKind::TailCall { .. } => {
1278                // check_mir_body forbids tail calls
1279                unreachable!()
1280            }
1281            TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
1282                if let Some(ref mut tgt) = *target {
1283                    *tgt = self.map_block(*tgt);
1284                }
1285                *unwind = self.map_unwind(*unwind);
1286            }
1287            TerminatorKind::Assert { ref mut target, ref mut unwind, .. } => {
1288                *target = self.map_block(*target);
1289                *unwind = self.map_unwind(*unwind);
1290            }
1291            TerminatorKind::Return => {
1292                terminator.kind = if let Some(tgt) = self.return_block {
1293                    TerminatorKind::Goto { target: tgt }
1294                } else {
1295                    TerminatorKind::Unreachable
1296                }
1297            }
1298            TerminatorKind::UnwindResume => {
1299                terminator.kind = match self.cleanup_block {
1300                    UnwindAction::Cleanup(tgt) => TerminatorKind::Goto { target: tgt },
1301                    UnwindAction::Continue => TerminatorKind::UnwindResume,
1302                    UnwindAction::Unreachable => TerminatorKind::Unreachable,
1303                    UnwindAction::Terminate(reason) => TerminatorKind::UnwindTerminate(reason),
1304                };
1305            }
1306            TerminatorKind::UnwindTerminate(_) => {}
1307            TerminatorKind::Unreachable => {}
1308            TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
1309                *real_target = self.map_block(*real_target);
1310                *imaginary_target = self.map_block(*imaginary_target);
1311            }
1312            TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
1313            // see the ordering of passes in the optimized_mir query.
1314            {
1315                bug!("False unwinds should have been removed before inlining")
1316            }
1317            TerminatorKind::InlineAsm { ref mut targets, ref mut unwind, .. } => {
1318                for tgt in targets.iter_mut() {
1319                    *tgt = self.map_block(*tgt);
1320                }
1321                *unwind = self.map_unwind(*unwind);
1322            }
1323        }
1324    }
1325}
1326
1327#[instrument(skip(tcx), level = "debug")]
1328fn try_instance_mir<'tcx>(
1329    tcx: TyCtxt<'tcx>,
1330    instance: InstanceKind<'tcx>,
1331) -> Result<&'tcx Body<'tcx>, &'static str> {
1332    if let ty::InstanceKind::DropGlue(_, Some(ty))
1333    | ty::InstanceKind::AsyncDropGlueCtorShim(_, Some(ty)) = instance
1334        && let ty::Adt(def, args) = ty.kind()
1335    {
1336        let fields = def.all_fields();
1337        for field in fields {
1338            let field_ty = field.ty(tcx, args);
1339            if field_ty.has_param() && field_ty.has_aliases() {
1340                return Err("cannot build drop shim for polymorphic type");
1341            }
1342        }
1343    }
1344    Ok(tcx.instance_mir(instance))
1345}
1346
1347fn body_is_forwarder(body: &Body<'_>) -> bool {
1348    let TerminatorKind::Call { target, .. } = body.basic_blocks[START_BLOCK].terminator().kind
1349    else {
1350        return false;
1351    };
1352    if let Some(target) = target {
1353        let TerminatorKind::Return = body.basic_blocks[target].terminator().kind else {
1354            return false;
1355        };
1356    }
1357
1358    let max_blocks = if !body.is_polymorphic {
1359        2
1360    } else if target.is_none() {
1361        3
1362    } else {
1363        4
1364    };
1365    if body.basic_blocks.len() > max_blocks {
1366        return false;
1367    }
1368
1369    body.basic_blocks.iter_enumerated().all(|(bb, bb_data)| {
1370        bb == START_BLOCK
1371            || matches!(
1372                bb_data.terminator().kind,
1373                TerminatorKind::Return
1374                    | TerminatorKind::Drop { .. }
1375                    | TerminatorKind::UnwindResume
1376                    | TerminatorKind::UnwindTerminate(_)
1377            )
1378    })
1379}