rustc_mir_transform/
check_inline.rs

1//! Check that a body annotated with `#[rustc_force_inline]` will not fail to inline based on its
2//! definition alone (irrespective of any specific caller).
3
4use rustc_hir::attrs::InlineAttr;
5use rustc_hir::def_id::DefId;
6use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
7use rustc_middle::mir::{Body, TerminatorKind};
8use rustc_middle::ty;
9use rustc_middle::ty::TyCtxt;
10use rustc_span::sym;
11
12use crate::pass_manager::MirLint;
13
14pub(super) struct CheckForceInline;
15
16impl<'tcx> MirLint<'tcx> for CheckForceInline {
17    fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
18        let def_id = body.source.def_id();
19        if !tcx.hir_body_owner_kind(def_id).is_fn_or_closure() || !def_id.is_local() {
20            return;
21        }
22        let InlineAttr::Force { attr_span, .. } = tcx.codegen_fn_attrs(def_id).inline else {
23            return;
24        };
25
26        if let Err(reason) =
27            is_inline_valid_on_fn(tcx, def_id).and_then(|_| is_inline_valid_on_body(tcx, body))
28        {
29            tcx.dcx().emit_err(crate::errors::InvalidForceInline {
30                attr_span,
31                callee_span: tcx.def_span(def_id),
32                callee: tcx.def_path_str(def_id),
33                reason,
34            });
35        }
36    }
37}
38
39pub(super) fn is_inline_valid_on_fn<'tcx>(
40    tcx: TyCtxt<'tcx>,
41    def_id: DefId,
42) -> Result<(), &'static str> {
43    let codegen_attrs = tcx.codegen_fn_attrs(def_id);
44    if tcx.has_attr(def_id, sym::rustc_no_mir_inline) {
45        return Err("#[rustc_no_mir_inline]");
46    }
47
48    let ty = tcx.type_of(def_id);
49    if match ty.instantiate_identity().kind() {
50        ty::FnDef(..) => tcx.fn_sig(def_id).instantiate_identity().c_variadic(),
51        ty::Closure(_, args) => args.as_closure().sig().c_variadic(),
52        _ => false,
53    } {
54        return Err("C variadic");
55    }
56
57    if codegen_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
58        return Err("cold");
59    }
60
61    // Intrinsic fallback bodies are automatically made cross-crate inlineable,
62    // but at this stage we don't know whether codegen knows the intrinsic,
63    // so just conservatively don't inline it. This also ensures that we do not
64    // accidentally inline the body of an intrinsic that *must* be overridden.
65    if tcx.has_attr(def_id, sym::rustc_intrinsic) {
66        return Err("callee is an intrinsic");
67    }
68
69    Ok(())
70}
71
72pub(super) fn is_inline_valid_on_body<'tcx>(
73    _: TyCtxt<'tcx>,
74    body: &Body<'tcx>,
75) -> Result<(), &'static str> {
76    if body
77        .basic_blocks
78        .iter()
79        .any(|bb| matches!(bb.terminator().kind, TerminatorKind::TailCall { .. }))
80    {
81        return Err("can't inline functions with tail calls");
82    }
83
84    Ok(())
85}