1use rustc_hir::attrs::InlineAttr;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::LocalDefId;
4use rustc_hir::find_attr;
5use rustc_middle::bug;
6use rustc_middle::mir::visit::Visitor;
7use rustc_middle::mir::*;
8use rustc_middle::query::Providers;
9use rustc_middle::ty::TyCtxt;
10use rustc_session::config::{InliningThreshold, OptLevel};
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 }
3738// FIXME(autodiff): replace this as per discussion in https://github.com/rust-lang/rust/pull/149033#discussion_r2535465880
39if {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcAutodiff(..)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(tcx, def_id, RustcAutodiff(..)) {
40return true;
41 }
4243if {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcIntrinsic) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(tcx, def_id, RustcIntrinsic) {
44// Intrinsic fallback bodies are always cross-crate inlineable.
45 // To ensure that the MIR inliner doesn't cluelessly try to inline fallback
46 // bodies even when the backend would implement something better, we stop
47 // the MIR inliner from ever inlining an intrinsic.
48return true;
49 }
5051// Obey source annotations first; this is important because it means we can use
52 // #[inline(never)] to force code generation.
53match codegen_fn_attrs.inline {
54 InlineAttr::Never => return false,
55 InlineAttr::Hint | InlineAttr::Always | InlineAttr::Force { .. } => return true,
56_ => {}
57 }
5859// If the crate is likely to be mostly unused, use cross-crate inlining to defer codegen until
60 // the function is referenced, in order to skip codegen for unused functions. This is
61 // intentionally after the check for `inline(never)`, so that `inline(never)` wins.
62if tcx.sess.opts.unstable_opts.hint_mostly_unused {
63return true;
64 }
6566let sig = tcx.fn_sig(def_id).instantiate_identity();
67for ty in sig.inputs().skip_binder().iter().chain(std::iter::once(&sig.output().skip_binder()))
68 {
69// FIXME(f16_f128): in order to avoid crashes building `core`, always inline to skip
70 // codegen if the function is not used.
71if ty == &tcx.types.f16 || ty == &tcx.types.f128 {
72return true;
73 }
74 }
7576// Don't do any inference when incremental compilation is enabled; the additional inlining that
77 // inference permits also creates more work for small edits.
78if tcx.sess.opts.incremental.is_some() {
79return false;
80 }
8182// Don't do any inference if codegen optimizations are disabled and also MIR inlining is not
83 // enabled. This ensures that we do inference even if someone only passes -Zinline-mir,
84 // which is less confusing than having to also enable -Copt-level=1.
85let inliner_will_run = pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
86 || inline::ForceInline::should_run_pass_for_callee(tcx, def_id.to_def_id());
87if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.opts.optimize {
OptLevel::No => true,
_ => false,
}matches!(tcx.sess.opts.optimize, OptLevel::No) && !inliner_will_run {
88return false;
89 }
9091if !tcx.is_mir_available(def_id) {
92return false;
93 }
9495let threshold = match tcx.sess.opts.unstable_opts.cross_crate_inline_threshold {
96 InliningThreshold::Always => return true,
97 InliningThreshold::Sometimes(threshold) => threshold,
98 InliningThreshold::Never => return false,
99 };
100101let mir = tcx.optimized_mir(def_id);
102let mut checker =
103CostChecker { tcx, callee_body: mir, calls: 0, statements: 0, landing_pads: 0, resumes: 0 };
104checker.visit_body(mir);
105checker.calls == 0
106&& checker.resumes == 0
107&& checker.landing_pads == 0
108&& checker.statements <= threshold109}
110111// The threshold that CostChecker computes is balancing the desire to make more things
112// inlinable cross crates against the growth in incremental CGU size that happens when too many
113// things in the sysroot are made inlinable.
114// Permitting calls causes the size of some incremental CGUs to grow, because more functions are
115// made inlinable out of the sysroot or dependencies.
116// Assert terminators are similar to calls, but do not have the same impact on compile time, so
117// those are just treated as statements.
118// A threshold exists at all because we don't want to blindly mark a huge function as inlinable.
119120struct CostChecker<'b, 'tcx> {
121 tcx: TyCtxt<'tcx>,
122 callee_body: &'b Body<'tcx>,
123 calls: usize,
124 statements: usize,
125 landing_pads: usize,
126 resumes: usize,
127}
128129impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
130fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
131// Don't count StorageLive/StorageDead in the inlining cost.
132match statement.kind {
133 StatementKind::StorageLive(_) | StatementKind::StorageDead(_) | StatementKind::Nop => {}
134_ => self.statements += 1,
135 }
136 }
137138fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, _: Location) {
139self.statements += 1;
140let tcx = self.tcx;
141match &terminator.kind {
142 TerminatorKind::Drop { place, unwind, .. } => {
143let ty = place.ty(self.callee_body, tcx).ty;
144if !ty.is_trivially_pure_clone_copy() {
145self.calls += 1;
146if let UnwindAction::Cleanup(_) = unwind {
147self.landing_pads += 1;
148 }
149 }
150 }
151 TerminatorKind::Call { func, unwind, .. } => {
152// We track calls because they make our function not a leaf (and in theory, the
153 // number of calls indicates how likely this function is to perturb other CGUs).
154 // But intrinsics don't have a body that gets assigned to a CGU, so they are
155 // ignored.
156if let Some((fn_def_id, _)) = func.const_fn_def()
157 && {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(fn_def_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcIntrinsic) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(tcx, fn_def_id, RustcIntrinsic)158 {
159return;
160 }
161self.calls += 1;
162if let UnwindAction::Cleanup(_) = unwind {
163self.landing_pads += 1;
164 }
165 }
166 TerminatorKind::TailCall { .. } => {
167self.calls += 1;
168 }
169 TerminatorKind::Assert { unwind, .. } => {
170if let UnwindAction::Cleanup(_) = unwind {
171self.landing_pads += 1;
172 }
173 }
174 TerminatorKind::UnwindResume => self.resumes += 1,
175 TerminatorKind::InlineAsm { unwind, .. } => {
176if let UnwindAction::Cleanup(_) = unwind {
177self.landing_pads += 1;
178 }
179 }
180 TerminatorKind::Return181 | TerminatorKind::Goto { .. }
182 | TerminatorKind::SwitchInt { .. }
183 | TerminatorKind::Unreachable184 | TerminatorKind::UnwindTerminate(_) => {}
185 kind @ (TerminatorKind::FalseUnwind { .. }
186 | TerminatorKind::FalseEdge { .. }
187 | TerminatorKind::Yield { .. }
188 | TerminatorKind::CoroutineDrop) => {
189::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} should not be in runtime MIR",
kind));bug!("{kind:?} should not be in runtime MIR");
190 }
191 }
192 }
193}