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