Skip to main content

rustc_mir_build/
check_tail_calls.rs

1use rustc_abi::ExternAbi;
2use rustc_data_structures::stack::ensure_sufficient_stack;
3use rustc_errors::Applicability;
4use rustc_hir::LangItem;
5use rustc_hir::def::DefKind;
6use rustc_hir::def_id::CRATE_DEF_ID;
7use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8use rustc_middle::span_bug;
9use rustc_middle::thir::visit::{self, Visitor};
10use rustc_middle::thir::{BodyTy, Expr, ExprId, ExprKind, Thir};
11use rustc_middle::ty::{self, Ty, TyCtxt};
12use rustc_span::def_id::{DefId, LocalDefId};
13use rustc_span::{ErrorGuaranteed, Span};
14
15pub(crate) fn check_tail_calls(tcx: TyCtxt<'_>, def: LocalDefId) -> Result<(), ErrorGuaranteed> {
16    let (thir, expr) = tcx.thir_body(def)?;
17    let thir = &thir.borrow();
18
19    // If `thir` is empty, a type error occurred, skip this body.
20    if thir.exprs.is_empty() {
21        return Ok(());
22    }
23
24    let is_closure = #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def) {
    DefKind::Closure => true,
    _ => false,
}matches!(tcx.def_kind(def), DefKind::Closure);
25
26    let mut visitor = TailCallCkVisitor {
27        tcx,
28        thir,
29        found_errors: Ok(()),
30        // FIXME(#132279): we're clearly in a body here.
31        typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
32        is_closure,
33        caller_def_id: def,
34    };
35
36    visitor.visit_expr(&thir[expr]);
37
38    visitor.found_errors
39}
40
41struct TailCallCkVisitor<'a, 'tcx> {
42    tcx: TyCtxt<'tcx>,
43    thir: &'a Thir<'tcx>,
44    typing_env: ty::TypingEnv<'tcx>,
45    /// Whatever the currently checked body is one of a closure
46    is_closure: bool,
47    /// The result of the checks, `Err(_)` if there was a problem with some
48    /// tail call, `Ok(())` if all of them were fine.
49    found_errors: Result<(), ErrorGuaranteed>,
50    /// `LocalDefId` of the caller function.
51    caller_def_id: LocalDefId,
52}
53
54impl<'tcx> TailCallCkVisitor<'_, 'tcx> {
55    fn check_tail_call(&mut self, call: &Expr<'_>, expr: &Expr<'_>) {
56        if self.is_closure {
57            self.report_in_closure(expr);
58            return;
59        }
60
61        let BodyTy::Fn(caller_sig) = self.thir.body_type else {
62            ::rustc_middle::util::bug::span_bug_fmt(call.span,
    format_args!("`become` outside of functions should have been disallowed by hir_typeck"))span_bug!(
63                call.span,
64                "`become` outside of functions should have been disallowed by hir_typeck"
65            )
66        };
67        // While the `caller_sig` does have its free regions erased, it does not have its
68        // binders anonymized. We call `erase_and_anonymize_regions` once again to anonymize any binders
69        // within the signature, such as in function pointer or `dyn Trait` args.
70        let caller_sig = self.tcx.erase_and_anonymize_regions(caller_sig);
71
72        let ExprKind::Scope { value, .. } = call.kind else {
73            ::rustc_middle::util::bug::span_bug_fmt(call.span,
    format_args!("expected scope, found: {0:?}", call))span_bug!(call.span, "expected scope, found: {call:?}")
74        };
75        let value = &self.thir[value];
76
77        if #[allow(non_exhaustive_omitted_patterns)] match value.kind {
    ExprKind::Binary { .. } | ExprKind::Unary { .. } | ExprKind::AssignOp { ..
        } | ExprKind::Index { .. } => true,
    _ => false,
}matches!(
78            value.kind,
79            ExprKind::Binary { .. }
80                | ExprKind::Unary { .. }
81                | ExprKind::AssignOp { .. }
82                | ExprKind::Index { .. }
83        ) {
84            self.report_builtin_op(call, expr);
85            return;
86        }
87
88        let ExprKind::Call { ty, fun, ref args, from_hir_call, fn_span } = value.kind else {
89            self.report_non_call(value, expr);
90            return;
91        };
92
93        if !from_hir_call {
94            self.report_op(ty, args, fn_span, expr);
95        }
96
97        if let &ty::FnDef(did, args) = ty.kind() {
98            // Closures in thir look something akin to
99            // `for<'a> extern "rust-call" fn(&'a [closure@...], ()) -> <[closure@...] as FnOnce<()>>::Output {<[closure@...] as Fn<()>>::call}`
100            // So we have to check for them in this weird way...
101            let parent = self.tcx.parent(did);
102            if self.tcx.fn_trait_kind_from_def_id(parent).is_some()
103                && let Some(this) = args.first()
104                && let Some(this) = this.as_type()
105            {
106                if this.is_closure() {
107                    self.report_calling_closure(&self.thir[fun], args[1].as_type().unwrap(), expr);
108                } else {
109                    // This can happen when tail calling `Box` that wraps a function
110                    self.report_nonfn_callee(fn_span, self.thir[fun].span, this);
111                }
112
113                // Tail calling is likely to cause unrelated errors (ABI, argument mismatches),
114                // skip them, producing an error about calling a closure is enough.
115                return;
116            };
117
118            if self.tcx.intrinsic(did).is_some() {
119                self.report_calling_intrinsic(expr);
120            }
121        }
122
123        let (ty::FnDef(..) | ty::FnPtr(..)) = ty.kind() else {
124            self.report_nonfn_callee(fn_span, self.thir[fun].span, ty);
125
126            // `fn_sig` below panics otherwise
127            return;
128        };
129
130        // Erase regions since tail calls don't care about lifetimes
131        let callee_sig =
132            self.tcx.normalize_erasing_late_bound_regions(self.typing_env, ty.fn_sig(self.tcx));
133
134        if caller_sig.abi() != callee_sig.abi() {
135            self.report_abi_mismatch(expr.span, caller_sig.abi(), callee_sig.abi());
136        }
137
138        if !callee_sig.abi().supports_guaranteed_tail_call() {
139            self.report_unsupported_abi(expr.span, callee_sig.abi());
140        }
141
142        // FIXME(explicit_tail_calls): this currently fails for cases where opaques are used.
143        // e.g.
144        // ```
145        // fn a() -> impl Sized { become b() } // ICE
146        // fn b() -> u8 { 0 }
147        // ```
148        // we should think what is the expected behavior here.
149        // (we should probably just accept this by revealing opaques?)
150        if caller_sig.inputs_and_output != callee_sig.inputs_and_output {
151            let caller_ty = self.tcx.type_of(self.caller_def_id).skip_binder();
152
153            self.report_signature_mismatch(
154                expr.span,
155                self.tcx.liberate_late_bound_regions(
156                    CRATE_DEF_ID.to_def_id(),
157                    caller_ty.fn_sig(self.tcx),
158                ),
159                self.tcx.liberate_late_bound_regions(CRATE_DEF_ID.to_def_id(), ty.fn_sig(self.tcx)),
160            );
161        }
162
163        {
164            // `#[track_caller]` affects the ABI of a function (by adding a location argument),
165            // so a `track_caller` can only tail call other `track_caller` functions.
166            //
167            // The issue is however that we can't know if a function is `track_caller` or not at
168            // this point (THIR can be polymorphic, we may have an unresolved trait function).
169            // We could only allow functions that we *can* resolve and *are* `track_caller`,
170            // but that would turn changing `track_caller`-ness into a breaking change,
171            // which is probably undesirable.
172            //
173            // Also note that we don't check callee's `track_caller`-ness at all, mostly for the
174            // reasons above, but also because we can always tailcall the shim we'd generate for
175            // coercing the function to an `fn()` pointer. (although in that case the tailcall is
176            // basically useless -- the shim calls the actual function, so tailcalling the shim is
177            // equivalent to calling the function)
178            let caller_needs_location = self.caller_needs_location();
179
180            if caller_needs_location {
181                self.report_track_caller_caller(expr.span);
182            }
183        }
184
185        if caller_sig.c_variadic() {
186            self.report_c_variadic_caller(expr.span);
187        }
188
189        if callee_sig.c_variadic() {
190            self.report_c_variadic_callee(expr.span);
191        }
192    }
193
194    /// Returns true if the caller function needs a location argument
195    /// (i.e. if a function is marked as `#[track_caller]`)
196    fn caller_needs_location(&self) -> bool {
197        let flags = self.tcx.codegen_fn_attrs(self.caller_def_id).flags;
198        flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
199    }
200
201    fn report_in_closure(&mut self, expr: &Expr<'_>) {
202        let err = self.tcx.dcx().span_err(expr.span, "`become` is not allowed in closures");
203        self.found_errors = Err(err);
204    }
205
206    fn report_builtin_op(&mut self, value: &Expr<'_>, expr: &Expr<'_>) {
207        let err = self
208            .tcx
209            .dcx()
210            .struct_span_err(value.span, "`become` does not support operators")
211            .with_note("using `become` on a builtin operator is not useful")
212            .with_span_suggestion(
213                value.span.until(expr.span),
214                "try using `return` instead",
215                "return ",
216                Applicability::MachineApplicable,
217            )
218            .emit();
219        self.found_errors = Err(err);
220    }
221
222    fn report_op(&mut self, fun_ty: Ty<'_>, args: &[ExprId], fn_span: Span, expr: &Expr<'_>) {
223        let mut err =
224            self.tcx.dcx().struct_span_err(fn_span, "`become` does not support operators");
225
226        if let &ty::FnDef(did, _substs) = fun_ty.kind()
227            && let parent = self.tcx.parent(did)
228            && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(parent) {
    DefKind::Trait => true,
    _ => false,
}matches!(self.tcx.def_kind(parent), DefKind::Trait)
229            && let Some(method) = op_trait_as_method_name(self.tcx, parent)
230        {
231            match args {
232                &[arg] => {
233                    let arg = &self.thir[arg];
234
235                    err.multipart_suggestion(
236                        "try using the method directly",
237                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(fn_span.shrink_to_lo().until(arg.span), "(".to_owned()),
                (arg.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(").{0}()", method))
                        }))]))vec![
238                            (fn_span.shrink_to_lo().until(arg.span), "(".to_owned()),
239                            (arg.span.shrink_to_hi(), format!(").{method}()")),
240                        ],
241                        Applicability::MaybeIncorrect,
242                    );
243                }
244                &[lhs, rhs] => {
245                    let lhs = &self.thir[lhs];
246                    let rhs = &self.thir[rhs];
247
248                    err.multipart_suggestion(
249                        "try using the method directly",
250                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lhs.span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("("))
                        })),
                (lhs.span.between(rhs.span),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(").{0}(", method))
                        })),
                (rhs.span.between(expr.span.shrink_to_hi()),
                    ")".to_owned())]))vec![
251                            (lhs.span.shrink_to_lo(), format!("(")),
252                            (lhs.span.between(rhs.span), format!(").{method}(")),
253                            (rhs.span.between(expr.span.shrink_to_hi()), ")".to_owned()),
254                        ],
255                        Applicability::MaybeIncorrect,
256                    );
257                }
258                _ => ::rustc_middle::util::bug::span_bug_fmt(expr.span,
    format_args!("operator with more than 2 args? {0:?}", args))span_bug!(expr.span, "operator with more than 2 args? {args:?}"),
259            }
260        }
261
262        self.found_errors = Err(err.emit());
263    }
264
265    fn report_non_call(&mut self, value: &Expr<'_>, expr: &Expr<'_>) {
266        let err = self
267            .tcx
268            .dcx()
269            .struct_span_err(value.span, "`become` requires a function call")
270            .with_span_note(value.span, "not a function call")
271            .with_span_suggestion(
272                value.span.until(expr.span),
273                "try using `return` instead",
274                "return ",
275                Applicability::MaybeIncorrect,
276            )
277            .emit();
278        self.found_errors = Err(err);
279    }
280
281    fn report_calling_closure(&mut self, fun: &Expr<'_>, tupled_args: Ty<'_>, expr: &Expr<'_>) {
282        let underscored_args = match tupled_args.kind() {
283            ty::Tuple(tys) if tys.is_empty() => "".to_owned(),
284            ty::Tuple(tys) => std::iter::repeat_n("_, ", tys.len() - 1).chain(["_"]).collect(),
285            _ => "_".to_owned(),
286        };
287
288        let err = self
289            .tcx
290            .dcx()
291            .struct_span_err(expr.span, "tail calling closures directly is not allowed")
292            .with_multipart_suggestion(
293                "try casting the closure to a function pointer type",
294                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(fun.span.shrink_to_lo(), "(".to_owned()),
                (fun.span.shrink_to_hi(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" as fn({0}) -> _)",
                                    underscored_args))
                        }))]))vec![
295                    (fun.span.shrink_to_lo(), "(".to_owned()),
296                    (fun.span.shrink_to_hi(), format!(" as fn({underscored_args}) -> _)")),
297                ],
298                Applicability::MaybeIncorrect,
299            )
300            .emit();
301        self.found_errors = Err(err);
302    }
303
304    fn report_calling_intrinsic(&mut self, expr: &Expr<'_>) {
305        let err = self
306            .tcx
307            .dcx()
308            .struct_span_err(expr.span, "tail calling intrinsics is not allowed")
309            .emit();
310
311        self.found_errors = Err(err);
312    }
313
314    fn report_nonfn_callee(&mut self, call_sp: Span, fun_sp: Span, ty: Ty<'_>) {
315        let mut err = self
316            .tcx
317            .dcx()
318            .struct_span_err(
319                call_sp,
320                "tail calls can only be performed with function definitions or pointers",
321            )
322            .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("callee has type `{0}`", ty))
    })format!("callee has type `{ty}`"));
323
324        let mut ty = ty;
325        let mut refs = 0;
326        while ty.is_box() || ty.is_ref() {
327            ty = ty.builtin_deref(false).unwrap();
328            refs += 1;
329        }
330
331        if refs > 0 && ty.is_fn() {
332            let thing = if ty.is_fn_ptr() { "pointer" } else { "definition" };
333
334            let derefs =
335                std::iter::once('(').chain(std::iter::repeat_n('*', refs)).collect::<String>();
336
337            err.multipart_suggestion(
338                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider dereferencing the expression to get a function {0}",
                thing))
    })format!("consider dereferencing the expression to get a function {thing}"),
339                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(fun_sp.shrink_to_lo(), derefs),
                (fun_sp.shrink_to_hi(), ")".to_owned())]))vec![(fun_sp.shrink_to_lo(), derefs), (fun_sp.shrink_to_hi(), ")".to_owned())],
340                Applicability::MachineApplicable,
341            );
342        }
343
344        let err = err.emit();
345        self.found_errors = Err(err);
346    }
347
348    fn report_abi_mismatch(&mut self, sp: Span, caller_abi: ExternAbi, callee_abi: ExternAbi) {
349        let err = self
350            .tcx
351            .dcx()
352            .struct_span_err(sp, "mismatched function ABIs")
353            .with_note("`become` requires caller and callee to have the same ABI")
354            .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("caller ABI is `{0}`, while callee ABI is `{1}`",
                caller_abi, callee_abi))
    })format!("caller ABI is `{caller_abi}`, while callee ABI is `{callee_abi}`"))
355            .emit();
356        self.found_errors = Err(err);
357    }
358
359    fn report_unsupported_abi(&mut self, sp: Span, callee_abi: ExternAbi) {
360        let err = self
361            .tcx
362            .dcx()
363            .struct_span_err(sp, "ABI does not support guaranteed tail calls")
364            .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`become` is not supported for `extern {0}` functions",
                callee_abi))
    })format!("`become` is not supported for `extern {callee_abi}` functions"))
365            .emit();
366        self.found_errors = Err(err);
367    }
368
369    fn report_signature_mismatch(
370        &mut self,
371        sp: Span,
372        caller_sig: ty::FnSig<'_>,
373        callee_sig: ty::FnSig<'_>,
374    ) {
375        let err = self
376            .tcx
377            .dcx()
378            .struct_span_err(sp, "mismatched signatures")
379            .with_note("`become` requires caller and callee to have matching signatures")
380            .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("caller signature: `{0}`",
                caller_sig))
    })format!("caller signature: `{caller_sig}`"))
381            .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("callee signature: `{0}`",
                callee_sig))
    })format!("callee signature: `{callee_sig}`"))
382            .emit();
383        self.found_errors = Err(err);
384    }
385
386    fn report_track_caller_caller(&mut self, sp: Span) {
387        let err = self
388            .tcx
389            .dcx()
390            .struct_span_err(
391                sp,
392                "a function marked with `#[track_caller]` cannot perform a tail-call",
393            )
394            .emit();
395
396        self.found_errors = Err(err);
397    }
398
399    fn report_c_variadic_caller(&mut self, sp: Span) {
400        let err = self
401            .tcx
402            .dcx()
403            // FIXME(explicit_tail_calls): highlight the `...`
404            .struct_span_err(sp, "tail-calls are not allowed in c-variadic functions")
405            .emit();
406
407        self.found_errors = Err(err);
408    }
409
410    fn report_c_variadic_callee(&mut self, sp: Span) {
411        let err = self
412            .tcx
413            .dcx()
414            // FIXME(explicit_tail_calls): highlight the function or something...
415            .struct_span_err(sp, "c-variadic functions can't be tail-called")
416            .emit();
417
418        self.found_errors = Err(err);
419    }
420}
421
422impl<'a, 'tcx> Visitor<'a, 'tcx> for TailCallCkVisitor<'a, 'tcx> {
423    fn thir(&self) -> &'a Thir<'tcx> {
424        &self.thir
425    }
426
427    fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
428        ensure_sufficient_stack(|| {
429            if let ExprKind::Become { value } = expr.kind {
430                let call = &self.thir[value];
431                self.check_tail_call(call, expr);
432            }
433
434            visit::walk_expr(self, expr);
435        });
436    }
437}
438
439fn op_trait_as_method_name(tcx: TyCtxt<'_>, trait_did: DefId) -> Option<&'static str> {
440    let m = match tcx.as_lang_item(trait_did)? {
441        LangItem::Add => "add",
442        LangItem::Sub => "sub",
443        LangItem::Mul => "mul",
444        LangItem::Div => "div",
445        LangItem::Rem => "rem",
446        LangItem::Neg => "neg",
447        LangItem::Not => "not",
448        LangItem::BitXor => "bitxor",
449        LangItem::BitAnd => "bitand",
450        LangItem::BitOr => "bitor",
451        LangItem::Shl => "shl",
452        LangItem::Shr => "shr",
453        LangItem::AddAssign => "add_assign",
454        LangItem::SubAssign => "sub_assign",
455        LangItem::MulAssign => "mul_assign",
456        LangItem::DivAssign => "div_assign",
457        LangItem::RemAssign => "rem_assign",
458        LangItem::BitXorAssign => "bitxor_assign",
459        LangItem::BitAndAssign => "bitand_assign",
460        LangItem::BitOrAssign => "bitor_assign",
461        LangItem::ShlAssign => "shl_assign",
462        LangItem::ShrAssign => "shr_assign",
463        LangItem::Index => "index",
464        LangItem::IndexMut => "index_mut",
465        _ => return None,
466    };
467
468    Some(m)
469}