Skip to main content

rustc_mir_transform/
cross_crate_inline.rs

1use rustc_attr_ir::{InlineAttr, find_attr};
2use rustc_hir as hir;
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::LocalDefId;
5use rustc_middle::mir::visit::Visitor;
6use rustc_middle::mir::*;
7use rustc_middle::query::Providers;
8use rustc_middle::ty::TyCtxt;
9use rustc_session::config::{InliningThreshold, OptLevel};
10use rustc_span::{bug, sym};
11
12use crate::{inline, pass_manager as pm};
13
14pub(super) fn provide(providers: &mut Providers) {
15    providers.cross_crate_inlinable = cross_crate_inlinable;
16}
17
18fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
19    let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
20    // If this has an extern indicator, then this function is globally shared and thus will not
21    // generate cgu-internal copies which would make it cross-crate inlinable.
22    if codegen_fn_attrs.contains_extern_indicator() {
23        return false;
24    }
25
26    // This just reproduces the logic from Instance::requires_inline.
27    match tcx.def_kind(def_id) {
28        DefKind::Ctor(..) | DefKind::Closure | DefKind::SyntheticCoroutineBody => return true,
29        DefKind::Fn | DefKind::AssocFn => {}
30        _ => return false,
31    }
32
33    // From this point on, it is valid to return true or false.
34    if tcx.sess.opts.unstable_opts.cross_crate_inline_threshold == InliningThreshold::Always {
35        return true;
36    }
37
38    if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcIntrinsic) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcIntrinsic) {
39        // Intrinsic fallback bodies are always cross-crate inlineable.
40        // To ensure that the MIR inliner doesn't cluelessly try to inline fallback
41        // bodies even when the backend would implement something better, we stop
42        // the MIR inliner from ever inlining an intrinsic.
43        return true;
44    }
45
46    if let hir::Constness::Const { always: true } = tcx.constness(def_id) {
47        // Comptime functions only exist during const eval and can never be passed
48        // to codegen. The const eval MIR pipeline also doesn't inline anything at all.
49        return false;
50    }
51
52    // Obey source annotations first; this is important because it means we can use
53    // #[inline(never)] to force code generation.
54    match codegen_fn_attrs.inline {
55        InlineAttr::Never => return false,
56        InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. } => return true,
57        _ => {}
58    }
59
60    // If the crate is likely to be mostly unused, use cross-crate inlining to defer codegen until
61    // the function is referenced, in order to skip codegen for unused functions. This is
62    // intentionally after the check for `inline(never)`, so that `inline(never)` wins.
63    if tcx.sess.opts.unstable_opts.hint_mostly_unused {
64        return true;
65    }
66
67    let reliable_f16 = tcx.sess.config.contains(&(sym::target_has_reliable_f16, None));
68    let reliable_f128 = tcx.sess.config.contains(&(sym::target_has_reliable_f128, None));
69    if !reliable_f16 || !reliable_f128 {
70        let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
71        for ty in
72            sig.inputs().skip_binder().iter().chain(std::iter::once(&sig.output().skip_binder()))
73        {
74            // FIXME(f16,f128): in order to avoid crashes building `core`, inline on targets that
75            // have issues to skip codegen if the function is not used.
76            if (!reliable_f16 && ty == &tcx.types.f16) || (!reliable_f128 && ty == &tcx.types.f128)
77            {
78                return true;
79            }
80        }
81    }
82
83    // Don't do any inference when incremental compilation is enabled; the additional inlining that
84    // inference permits also creates more work for small edits.
85    if tcx.sess.opts.incremental.is_some() {
86        return false;
87    }
88
89    // Don't do any inference if codegen optimizations are disabled and also MIR inlining is not
90    // enabled. This ensures that we do inference even if someone only passes -Zinline-mir,
91    // which is less confusing than having to also enable -Copt-level=1.
92    let inliner_will_run =
93        pm::should_run_pass(&inline::Inline, &pm::PassCtx::for_body(tcx, def_id.to_def_id()))
94            || inline::ForceInline::should_run_pass_for_callee(tcx, def_id.to_def_id());
95    if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.opts.optimize {
    OptLevel::No => true,
    _ => false,
}matches!(tcx.sess.opts.optimize, OptLevel::No) && !inliner_will_run {
96        return false;
97    }
98
99    if !tcx.is_mir_available(def_id) {
100        return false;
101    }
102
103    let threshold = match tcx.sess.opts.unstable_opts.cross_crate_inline_threshold {
104        InliningThreshold::Always => return true,
105        InliningThreshold::Sometimes(threshold) => threshold,
106        InliningThreshold::Never => return false,
107    };
108
109    let mir = tcx.optimized_mir(def_id);
110    let mut checker =
111        CostChecker { tcx, callee_body: mir, calls: 0, statements: 0, landing_pads: 0, resumes: 0 };
112    checker.visit_body(mir);
113    checker.calls == 0
114        && checker.resumes == 0
115        && checker.landing_pads == 0
116        && checker.statements <= threshold
117}
118
119// The threshold that CostChecker computes is balancing the desire to make more things
120// inlinable cross crates against the growth in incremental CGU size that happens when too many
121// things in the sysroot are made inlinable.
122// Permitting calls causes the size of some incremental CGUs to grow, because more functions are
123// made inlinable out of the sysroot or dependencies.
124// Assert terminators are similar to calls, but do not have the same impact on compile time, so
125// those are just treated as statements.
126// A threshold exists at all because we don't want to blindly mark a huge function as inlinable.
127
128struct CostChecker<'b, 'tcx> {
129    tcx: TyCtxt<'tcx>,
130    callee_body: &'b Body<'tcx>,
131    calls: usize,
132    statements: usize,
133    landing_pads: usize,
134    resumes: usize,
135}
136
137impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
138    fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
139        // Don't count StorageLive/StorageDead in the inlining cost.
140        match statement.kind {
141            StatementKind::StorageLive(_) | StatementKind::StorageDead(_) | StatementKind::Nop => {}
142            _ => self.statements += 1,
143        }
144    }
145
146    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, _: Location) {
147        self.statements += 1;
148        let tcx = self.tcx;
149        match &terminator.kind {
150            TerminatorKind::Drop { place, unwind, .. } => {
151                let ty = place.ty(self.callee_body, tcx).ty;
152                if !ty.is_trivially_pure_clone_copy() {
153                    self.calls += 1;
154                    if let UnwindAction::Cleanup(_) = unwind {
155                        self.landing_pads += 1;
156                    }
157                }
158            }
159            TerminatorKind::Call { func, unwind, .. } => {
160                // We track calls because they make our function not a leaf (and in theory, the
161                // number of calls indicates how likely this function is to perturb other CGUs).
162                // But there are a handful of intrinsics such as raw_eq that should not block
163                // cross-crate-inlining. Adding a broad exception for all intrinsics benchmarks well
164                // and seems more sustainable than an ever-growing list of intrinsics to ignore.
165                if let Some((fn_def_id, _)) = func.const_fn_def()
166                    && {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(fn_def_id, &tcx)
                    {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcIntrinsic) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, fn_def_id, RustcIntrinsic)
167                {
168                    return;
169                }
170                self.calls += 1;
171                if let UnwindAction::Cleanup(_) = unwind {
172                    self.landing_pads += 1;
173                }
174            }
175            TerminatorKind::TailCall { .. } => {
176                self.calls += 1;
177            }
178            TerminatorKind::Assert { unwind, .. } => {
179                if let UnwindAction::Cleanup(_) = unwind {
180                    self.landing_pads += 1;
181                }
182            }
183            TerminatorKind::UnwindResume => self.resumes += 1,
184            TerminatorKind::InlineAsm { unwind, .. } => {
185                if let UnwindAction::Cleanup(_) = unwind {
186                    self.landing_pads += 1;
187                }
188            }
189            TerminatorKind::Return
190            | TerminatorKind::Goto { .. }
191            | TerminatorKind::SwitchInt { .. }
192            | TerminatorKind::Unreachable
193            | TerminatorKind::UnwindTerminate(_) => {}
194            kind @ (TerminatorKind::FalseUnwind { .. }
195            | TerminatorKind::FalseEdge { .. }
196            | TerminatorKind::Yield { .. }
197            | TerminatorKind::CoroutineDrop) => {
198                ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} should not be in runtime MIR", kind),
    Location::caller());bug!("{kind:?} should not be in runtime MIR");
199            }
200        }
201    }
202}