Skip to main content

rustc_mir_transform/shim/
async_destructor_ctor.rs

1use rustc_hir::def_id::DefId;
2use rustc_hir::lang_items::LangItem;
3use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource};
4use rustc_index::{Idx, IndexVec};
5use rustc_middle::mir::{
6    BasicBlock, BasicBlockData, Body, Local, LocalDecl, MirSource, Operand, Place, Rvalue,
7    SourceInfo, Statement, StatementKind, Terminator, TerminatorKind,
8};
9use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt, TypeVisitableExt};
10
11use super::*;
12use crate::deref_separator::deref_finder;
13use crate::patch::MirPatch;
14
15const SELF_ARG: Local = Local::arg(0);
16
17pub(super) fn build_async_destructor_ctor_shim<'tcx>(
18    tcx: TyCtxt<'tcx>,
19    def_id: DefId,
20    ty: Ty<'tcx>,
21) -> Body<'tcx> {
22    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs:22",
                        "rustc_mir_transform::shim::async_destructor_ctor",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs"),
                        ::tracing_core::__macro_support::Option::Some(22u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim::async_destructor_ctor"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("build_async_destructor_ctor_shim(def_id={0:?}, ty={1:?})",
                                                    def_id, ty) as &dyn Value))])
            });
    } else { ; }
};debug!("build_async_destructor_ctor_shim(def_id={:?}, ty={:?})", def_id, ty);
23    if true {
    match (&Some(def_id), &tcx.lang_items().async_drop_in_place_fn()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(Some(def_id), tcx.lang_items().async_drop_in_place_fn());
24    let generic_body = tcx.optimized_mir(def_id);
25    let args = tcx.mk_args(&[ty.into()]);
26    let mut body = EarlyBinder::bind(generic_body.clone()).instantiate(tcx, args).skip_norm_wip();
27
28    // Minimal shim passes except MentionedItems,
29    // it causes error "mentioned_items for DefId(...async_drop_in_place...) have already been set
30    pm::run_passes(
31        tcx,
32        &mut body,
33        &[
34            &simplify::SimplifyCfg::MakeShim,
35            &abort_unwinding_calls::AbortUnwindingCalls,
36            &add_call_guards::CriticalCallEdges,
37        ],
38        None,
39        pm::Optimizations::Allowed,
40    );
41    body
42}
43
44// build_drop_shim analog for async drop glue (for generated coroutine poll function)
45x;#[tracing::instrument(level = "trace", skip(tcx), ret)]
46pub(super) fn build_async_drop_shim<'tcx>(
47    tcx: TyCtxt<'tcx>,
48    def_id: DefId,
49    ty: Ty<'tcx>,
50) -> Body<'tcx> {
51    let ty::Coroutine(_, parent_args) = ty.kind() else {
52        bug!();
53    };
54    let typing_env = ty::TypingEnv::fully_monomorphized();
55
56    let drop_ty = parent_args.first().unwrap().expect_ty();
57    let drop_ptr_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, drop_ty);
58
59    assert!(tcx.is_coroutine(def_id));
60    let coroutine_kind = tcx.coroutine_kind(def_id).unwrap();
61
62    assert!(matches!(
63        coroutine_kind,
64        CoroutineKind::Desugared(CoroutineDesugaring::Async, CoroutineSource::Fn)
65    ));
66
67    let needs_async_drop = drop_ty.needs_async_drop(tcx, typing_env);
68    let needs_sync_drop = !needs_async_drop && drop_ty.needs_drop(tcx, typing_env);
69
70    let resume_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, DUMMY_SP));
71    let resume_ty = Ty::new_adt(tcx, resume_adt, ty::List::empty());
72
73    let fn_sig = ty::Binder::dummy(tcx.mk_fn_sig_safe_rust_abi([ty, resume_ty], tcx.types.unit));
74    let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
75
76    assert!(!drop_ty.is_coroutine());
77    let span = tcx.def_span(def_id);
78    let source_info = SourceInfo::outermost(span);
79
80    // The first argument (index 0) which will be local 1 (after the return value).
81    let coroutine_layout = Place::from(SELF_ARG);
82    let coroutine_layout_dropee =
83        tcx.mk_place_field(coroutine_layout, FieldIdx::new(0), drop_ptr_ty);
84
85    let return_block = BasicBlock::new(1);
86    let mut blocks = IndexVec::with_capacity(2);
87    let block = |blocks: &mut IndexVec<_, _>, kind| {
88        blocks.push(BasicBlockData::new(Some(Terminator { source_info, kind }), false))
89    };
90    block(
91        &mut blocks,
92        if needs_sync_drop {
93            TerminatorKind::Drop {
94                place: tcx.mk_place_deref(coroutine_layout_dropee),
95                target: return_block,
96                unwind: UnwindAction::Continue,
97                replace: false,
98                drop: None,
99            }
100        } else {
101            TerminatorKind::Goto { target: return_block }
102        },
103    );
104    block(&mut blocks, TerminatorKind::Return);
105
106    let source = MirSource::from_instance(ty::InstanceKind::AsyncDropGlue(def_id, ty));
107    let mut body =
108        new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
109
110    body.coroutine = Some(Box::new(CoroutineInfo::initial(
111        coroutine_kind,
112        parent_args.as_coroutine().yield_ty(),
113        parent_args.as_coroutine().resume_ty(),
114    )));
115    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
116
117    // Returning noop body for types without `need async drop`
118    // (or sync Drop in case of !`need async drop` && `need drop`).
119    // And also for error types.
120    if needs_async_drop && !drop_ty.references_error() {
121        let dropee_ptr = Place::from(body.local_decls.push(LocalDecl::new(drop_ptr_ty, span)));
122        let st_kind = StatementKind::Assign(Box::new((
123            dropee_ptr,
124            Rvalue::Use(Operand::Move(coroutine_layout_dropee), WithRetag::Yes),
125        )));
126        body.basic_blocks_mut()[START_BLOCK].statements.push(Statement::new(source_info, st_kind));
127
128        let dropline = body.basic_blocks.last_index();
129
130        let patch = {
131            let mut elaborator = DropShimElaborator {
132                body: &body,
133                patch: MirPatch::new(&body),
134                tcx,
135                typing_env,
136                produce_async_drops: true,
137            };
138            let dropee = tcx.mk_place_deref(dropee_ptr);
139            let resume_block = elaborator.patch.resume_block();
140            elaborate_drop(
141                &mut elaborator,
142                source_info,
143                dropee,
144                (),
145                return_block,
146                Unwind::To(resume_block),
147                START_BLOCK,
148                dropline,
149            );
150            elaborator.patch
151        };
152        patch.apply(&mut body);
153    }
154
155    // We did not bother respecting deref separation, do it here.
156    deref_finder(tcx, &mut body, false);
157
158    body
159}
160
161// * For async drop a "normal" coroutine:
162// `async_drop_in_place<T>::{closure}.poll()` is converted into `T.future_drop_poll()`.
163// Every coroutine has its `poll` (calculate yourself a little further)
164// and its `future_drop_poll` (drop yourself a little further).
165//
166// * For async drop of "async drop coroutine" (`async_drop_in_place<T>::{closure}`):
167// Correct drop of such coroutine means normal execution of nested async drop.
168// async_drop(async_drop(T))::future_drop_poll() => async_drop(T)::poll().
169pub(super) fn build_future_drop_poll_shim<'tcx>(
170    tcx: TyCtxt<'tcx>,
171    def_id: DefId,
172    proxy_ty: Ty<'tcx>,
173    impl_ty: Ty<'tcx>,
174) -> Body<'tcx> {
175    let instance = ty::InstanceKind::FutureDropPollShim(def_id, proxy_ty, impl_ty);
176    let ty::Coroutine(coroutine_def_id, _) = impl_ty.kind() else {
177        ::rustc_middle::util::bug::bug_fmt(format_args!("build_future_drop_poll_shim not for coroutine impl type: ({0:?})",
        instance));bug!("build_future_drop_poll_shim not for coroutine impl type: ({:?})", instance);
178    };
179
180    let span = tcx.def_span(def_id);
181
182    if tcx.is_async_drop_in_place_coroutine(*coroutine_def_id) {
183        build_adrop_for_adrop_shim(tcx, proxy_ty, impl_ty, span, instance)
184    } else {
185        build_adrop_for_coroutine_shim(tcx, proxy_ty, impl_ty, span, instance)
186    }
187}
188
189// For async drop a "normal" coroutine:
190// `async_drop_in_place<T>::{closure}.poll()` is converted into `T.future_drop_poll()`.
191// Every coroutine has its `poll` (calculate yourself a little further)
192// and its `future_drop_poll` (drop yourself a little further).
193fn build_adrop_for_coroutine_shim<'tcx>(
194    tcx: TyCtxt<'tcx>,
195    proxy_ty: Ty<'tcx>,
196    impl_ty: Ty<'tcx>,
197    span: Span,
198    instance: ty::InstanceKind<'tcx>,
199) -> Body<'tcx> {
200    let ty::Coroutine(coroutine_def_id, impl_args) = impl_ty.kind() else {
201        ::rustc_middle::util::bug::bug_fmt(format_args!("build_adrop_for_coroutine_shim not for coroutine impl type: ({0:?})",
        instance));bug!("build_adrop_for_coroutine_shim not for coroutine impl type: ({:?})", instance);
202    };
203    let source_info = SourceInfo::outermost(span);
204    let body = tcx.optimized_mir(*coroutine_def_id).future_drop_poll().unwrap();
205    let mut body: Body<'tcx> =
206        EarlyBinder::bind(body.clone()).instantiate(tcx, impl_args).skip_norm_wip();
207    body.source.instance = instance;
208    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
209    body.var_debug_info.clear();
210
211    // converting `(_1: Pin<&mut CorLayout>, _2: &mut Context<'_>) -> Poll<()>`
212    // into `(_1: Pin<&mut ProxyLayout>, _2: &mut Context<'_>) -> Poll<()>`
213    // let mut _x: &mut CorLayout = &mut *_1.0.0;
214    // Replace old _1.0 accesses into _x accesses;
215    let proxy_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, proxy_ty);
216
217    let pin_adt_ref = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
218    let args = tcx.mk_args(&[proxy_ref.into()]);
219    let pin_proxy_ref = Ty::new_adt(tcx, pin_adt_ref, args);
220
221    let cor_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, impl_ty);
222    let cor_ref_local = body.local_decls.push(LocalDecl::new(cor_ref, span));
223
224    FixProxyFutureDropVisitor { tcx, replace_to: cor_ref_local }.visit_body(&mut body);
225
226    // Now changing first arg from Pin<&mut ImplCoroutine> to Pin<&mut ProxyCoroutine>
227    body.local_decls[SELF_ARG] = LocalDecl::new(pin_proxy_ref, span);
228
229    // Build the projection to assign `cor_ref_local = _1.<projection>`.
230    let mut pin_proxy_to_cor_projection = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [PlaceElem::Field(FieldIdx::ZERO, proxy_ref)]))vec![
231        // _1.0 : Pin<&mut ProxyLayout> ==> &mut ProxyLayout
232        PlaceElem::Field(FieldIdx::ZERO, proxy_ref),
233    ];
234
235    // _cor_ref_tmp = (*(*_proxy).0).0...
236    proxy_ty.find_async_drop_impl_coroutine(tcx, |ty| {
237        if ty != proxy_ty {
238            let ty_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
239            pin_proxy_to_cor_projection.push(PlaceElem::Deref);
240            pin_proxy_to_cor_projection.push(PlaceElem::Field(FieldIdx::ZERO, ty_ref));
241        }
242    });
243
244    // _cor_ref = cor_ref_tmp
245    let projected_pin = Place::from(SELF_ARG).project_deeper(&pin_proxy_to_cor_projection, tcx);
246    body.basic_blocks_mut()[START_BLOCK].statements.insert(
247        0,
248        Statement::new(
249            source_info,
250            StatementKind::Assign(Box::new((
251                Place::from(cor_ref_local),
252                Rvalue::Use(Operand::Move(projected_pin), WithRetag::Yes),
253            ))),
254        ),
255    );
256
257    // We did not bother respecting deref separation, do it here.
258    deref_finder(tcx, &mut body, false);
259
260    return body;
261
262    /// Replace Pin<&mut ImplCoroutine> accesses (_1.0) into Pin<&mut ProxyCoroutine> accesses
263    struct FixProxyFutureDropVisitor<'tcx> {
264        tcx: TyCtxt<'tcx>,
265        replace_to: Local,
266    }
267
268    impl<'tcx> MutVisitor<'tcx> for FixProxyFutureDropVisitor<'tcx> {
269        fn tcx(&self) -> TyCtxt<'tcx> {
270            self.tcx
271        }
272
273        fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
274            if place.local == SELF_ARG
275                && let Some((first, rest)) = place.projection.split_first()
276            {
277                if !#[allow(non_exhaustive_omitted_patterns)] match first {
            ProjectionElem::Field(FieldIdx::ZERO, _) => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(first, ProjectionElem::Field(FieldIdx::ZERO, _))")
};assert!(matches!(first, ProjectionElem::Field(FieldIdx::ZERO, _)));
278                *place = Place::from(self.replace_to).project_deeper(rest, self.tcx);
279            }
280        }
281    }
282}
283
284// When dropping async drop coroutine, we continue its execution.
285// async_drop(async_drop(T))::future_drop_poll() => async_drop(T)::poll()
286fn build_adrop_for_adrop_shim<'tcx>(
287    tcx: TyCtxt<'tcx>,
288    proxy_ty: Ty<'tcx>,
289    impl_ty: Ty<'tcx>,
290    span: Span,
291    instance: ty::InstanceKind<'tcx>,
292) -> Body<'tcx> {
293    let source_info = SourceInfo::outermost(span);
294    let proxy_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, proxy_ty);
295    // taking _1.0 (impl from Pin)
296    let proxy_ref_place =
297        Place::from(SELF_ARG).project_deeper(&[PlaceElem::Field(FieldIdx::ZERO, proxy_ref)], tcx);
298    let cor_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, impl_ty);
299
300    // ret_ty = `Poll<()>`
301    let poll_adt_ref = tcx.adt_def(tcx.require_lang_item(LangItem::Poll, span));
302    let ret_ty = Ty::new_adt(tcx, poll_adt_ref, tcx.mk_args(&[tcx.types.unit.into()]));
303    // env_ty = `Pin<&mut proxy_ty>`
304    let pin_adt_ref = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
305    let env_ty = Ty::new_adt(tcx, pin_adt_ref, tcx.mk_args(&[proxy_ref.into()]));
306    // sig = `fn (Pin<&mut proxy_ty>, &mut Context) -> Poll<()>`
307    let sig = tcx.mk_fn_sig_safe_rust_abi([env_ty, Ty::new_task_context(tcx)], ret_ty);
308    // This function will be called with pinned proxy coroutine layout.
309    // We need to extract `Arg0.0` to get proxy layout, and then get `.0`
310    // further to receive impl coroutine (may be needed)
311    let mut locals = local_decls_for_sig(&sig, span);
312    let mut blocks = IndexVec::with_capacity(3);
313
314    let proxy_ref_local = locals.push(LocalDecl::new(proxy_ref, span));
315
316    let call_bb = BasicBlock::new(1);
317    let return_bb = BasicBlock::new(2);
318
319    let mut statements = Vec::new();
320
321    statements.push(Statement::new(
322        source_info,
323        StatementKind::Assign(Box::new((
324            Place::from(proxy_ref_local),
325            Rvalue::Use(Operand::Copy(proxy_ref_place), WithRetag::Yes),
326        ))),
327    ));
328
329    let mut cor_ptr_local = proxy_ref_local;
330    proxy_ty.find_async_drop_impl_coroutine(tcx, |ty| {
331        if ty != proxy_ty {
332            let ty_ptr = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
333            let impl_ptr_place = Place::from(cor_ptr_local)
334                .project_deeper(&[PlaceElem::Deref, PlaceElem::Field(FieldIdx::ZERO, ty_ptr)], tcx);
335            cor_ptr_local = locals.push(LocalDecl::new(ty_ptr, span));
336            // _cor_ptr = _proxy.0.0 (... .0)
337            statements.push(Statement::new(
338                source_info,
339                StatementKind::Assign(Box::new((
340                    Place::from(cor_ptr_local),
341                    Rvalue::Use(Operand::Copy(impl_ptr_place), WithRetag::Yes),
342                ))),
343            ));
344        }
345    });
346
347    // convert impl coroutine ptr into ref
348    let reborrow = Rvalue::Ref(
349        tcx.lifetimes.re_erased,
350        BorrowKind::Mut { kind: MutBorrowKind::Default },
351        tcx.mk_place_deref(Place::from(cor_ptr_local)),
352    );
353    let cor_ref_place = Place::from(locals.push(LocalDecl::new(cor_ref, span)));
354    statements.push(Statement::new(
355        source_info,
356        StatementKind::Assign(Box::new((cor_ref_place, reborrow))),
357    ));
358
359    // cor_pin_ty = `Pin<&mut cor_ref>`
360    let cor_pin_ty = Ty::new_adt(tcx, pin_adt_ref, tcx.mk_args(&[cor_ref.into()]));
361    let cor_pin_place = Place::from(locals.push(LocalDecl::new(cor_pin_ty, span)));
362
363    let pin_fn = tcx.require_lang_item(LangItem::PinNewUnchecked, span);
364    // call Pin<FutTy>::new_unchecked(&mut impl_cor)
365    blocks.push(BasicBlockData::new_stmts(
366        statements,
367        Some(Terminator {
368            source_info,
369            kind: TerminatorKind::Call {
370                func: Operand::function_handle(tcx, pin_fn, [cor_ref.into()], span),
371                args: [dummy_spanned(Operand::Move(cor_ref_place))].into(),
372                destination: cor_pin_place,
373                target: Some(call_bb),
374                unwind: UnwindAction::Continue,
375                call_source: CallSource::Misc,
376                fn_span: span,
377            },
378        }),
379        false,
380    ));
381    // When dropping async drop coroutine, we continue its execution:
382    // we call impl::poll (impl_layout, ctx)
383    let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, span);
384    let resume_ctx = Place::from(Local::new(2));
385    blocks.push(BasicBlockData::new(
386        Some(Terminator {
387            source_info,
388            kind: TerminatorKind::Call {
389                func: Operand::function_handle(tcx, poll_fn, [impl_ty.into()], span),
390                args: [
391                    dummy_spanned(Operand::Move(cor_pin_place)),
392                    dummy_spanned(Operand::Move(resume_ctx)),
393                ]
394                .into(),
395                destination: Place::return_place(),
396                target: Some(return_bb),
397                unwind: UnwindAction::Continue,
398                call_source: CallSource::Misc,
399                fn_span: span,
400            },
401        }),
402        false,
403    ));
404    blocks.push(BasicBlockData::new(
405        Some(Terminator { source_info, kind: TerminatorKind::Return }),
406        false,
407    ));
408
409    let source = MirSource::from_instance(instance);
410    let mut body = new_body(source, blocks, locals, sig.inputs().len(), span);
411    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
412    return body;
413}