Skip to main content

rustc_mir_transform/
inline.rs

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