1use rustc_hir::attrs::InlineAttr;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::LocalDefId;
4use rustc_hir::{selfas hir, find_attr};
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;
1112use crate::{inline, pass_manageras pm};
1314pub(super) fn provide(providers: &mut Providers) {
15providers.cross_crate_inlinable = cross_crate_inlinable;
16}
1718fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
19let 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.
22if codegen_fn_attrs.contains_extern_indicator() {
23return false;
24 }
2526// This just reproduces the logic from Instance::requires_inline.
27match tcx.def_kind(def_id) {
28 DefKind::Ctor(..) | DefKind::Closure | DefKind::SyntheticCoroutineBody => return true,
29 DefKind::Fn | DefKind::AssocFn => {}
30_ => return false,
31 }
3233// From this point on, it is valid to return true or false.
34if tcx.sess.opts.unstable_opts.cross_crate_inline_threshold == InliningThreshold::Always {
35return true;
36 }
3738if {
{
'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.
43return true;
44 }
4546if 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.
49return false;
50 }
5152// Obey source annotations first; this is important because it means we can use
53 // #[inline(never)] to force code generation.
54match codegen_fn_attrs.inline {
55 InlineAttr::Never => return false,
56 InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. } => return true,
57_ => {}
58 }
5960// 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.
63if tcx.sess.opts.unstable_opts.hint_mostly_unused {
64return true;
65 }
6667let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
68for ty in sig.inputs().skip_binder().iter().chain(std::iter::once(&sig.output().skip_binder()))
69 {
70// FIXME(f16_f128): in order to avoid crashes building `core`, always inline to skip
71 // codegen if the function is not used.
72if ty == &tcx.types.f16 || ty == &tcx.types.f128 {
73return true;
74 }
75 }
7677// Don't do any inference when incremental compilation is enabled; the additional inlining that
78 // inference permits also creates more work for small edits.
79if tcx.sess.opts.incremental.is_some() {
80return false;
81 }
8283// Don't do any inference if codegen optimizations are disabled and also MIR inlining is not
84 // enabled. This ensures that we do inference even if someone only passes -Zinline-mir,
85 // which is less confusing than having to also enable -Copt-level=1.
86let inliner_will_run =
87 pm::should_run_pass(&inline::Inline, &pm::PassCtx::for_body(tcx, def_id.to_def_id()))
88 || inline::ForceInline::should_run_pass_for_callee(tcx, def_id.to_def_id());
89if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.opts.optimize {
OptLevel::No => true,
_ => false,
}matches!(tcx.sess.opts.optimize, OptLevel::No) && !inliner_will_run {
90return false;
91 }
9293if !tcx.is_mir_available(def_id) {
94return false;
95 }
9697let threshold = match tcx.sess.opts.unstable_opts.cross_crate_inline_threshold {
98 InliningThreshold::Always => return true,
99 InliningThreshold::Sometimes(threshold) => threshold,
100 InliningThreshold::Never => return false,
101 };
102103let mir = tcx.optimized_mir(def_id);
104let mut checker =
105CostChecker { tcx, callee_body: mir, calls: 0, statements: 0, landing_pads: 0, resumes: 0 };
106checker.visit_body(mir);
107checker.calls == 0
108&& checker.resumes == 0
109&& checker.landing_pads == 0
110&& checker.statements <= threshold111}
112113// The threshold that CostChecker computes is balancing the desire to make more things
114// inlinable cross crates against the growth in incremental CGU size that happens when too many
115// things in the sysroot are made inlinable.
116// Permitting calls causes the size of some incremental CGUs to grow, because more functions are
117// made inlinable out of the sysroot or dependencies.
118// Assert terminators are similar to calls, but do not have the same impact on compile time, so
119// those are just treated as statements.
120// A threshold exists at all because we don't want to blindly mark a huge function as inlinable.
121122struct CostChecker<'b, 'tcx> {
123 tcx: TyCtxt<'tcx>,
124 callee_body: &'b Body<'tcx>,
125 calls: usize,
126 statements: usize,
127 landing_pads: usize,
128 resumes: usize,
129}
130131impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
132fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
133// Don't count StorageLive/StorageDead in the inlining cost.
134match statement.kind {
135 StatementKind::StorageLive(_) | StatementKind::StorageDead(_) | StatementKind::Nop => {}
136_ => self.statements += 1,
137 }
138 }
139140fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, _: Location) {
141self.statements += 1;
142let tcx = self.tcx;
143match &terminator.kind {
144 TerminatorKind::Drop { place, unwind, .. } => {
145let ty = place.ty(self.callee_body, tcx).ty;
146if !ty.is_trivially_pure_clone_copy() {
147self.calls += 1;
148if let UnwindAction::Cleanup(_) = unwind {
149self.landing_pads += 1;
150 }
151 }
152 }
153 TerminatorKind::Call { func, unwind, .. } => {
154// We track calls because they make our function not a leaf (and in theory, the
155 // number of calls indicates how likely this function is to perturb other CGUs).
156 // But there are a handful of intrinsics such as raw_eq that should not block
157 // cross-crate-inlining. Adding a broad exception for all intrinsics benchmarks well
158 // and seems more sustainable than an ever-growing list of intrinsics to ignore.
159if let Some((fn_def_id, _)) = func.const_fn_def()
160 && {
{
'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)161 {
162return;
163 }
164self.calls += 1;
165if let UnwindAction::Cleanup(_) = unwind {
166self.landing_pads += 1;
167 }
168 }
169 TerminatorKind::TailCall { .. } => {
170self.calls += 1;
171 }
172 TerminatorKind::Assert { unwind, .. } => {
173if let UnwindAction::Cleanup(_) = unwind {
174self.landing_pads += 1;
175 }
176 }
177 TerminatorKind::UnwindResume => self.resumes += 1,
178 TerminatorKind::InlineAsm { unwind, .. } => {
179if let UnwindAction::Cleanup(_) = unwind {
180self.landing_pads += 1;
181 }
182 }
183 TerminatorKind::Return184 | TerminatorKind::Goto { .. }
185 | TerminatorKind::SwitchInt { .. }
186 | TerminatorKind::Unreachable187 | TerminatorKind::UnwindTerminate(_) => {}
188 kind @ (TerminatorKind::FalseUnwind { .. }
189 | TerminatorKind::FalseEdge { .. }
190 | TerminatorKind::Yield { .. }
191 | TerminatorKind::CoroutineDrop) => {
192bug_impl(None, format_args!("{0:?} should not be in runtime MIR", kind),
Location::caller());bug!("{kind:?} should not be in runtime MIR");
193 }
194 }
195 }
196}