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(
89            Some(Terminator { source_info, kind, attributes: ThinVec::new() }),
90            false,
91        ))
92    };
93    block(
94        &mut blocks,
95        if needs_sync_drop {
96            TerminatorKind::Drop {
97                place: tcx.mk_place_deref(coroutine_layout_dropee),
98                target: return_block,
99                unwind: UnwindAction::Continue,
100                replace: false,
101                drop: None,
102            }
103        } else {
104            TerminatorKind::Goto { target: return_block }
105        },
106    );
107    block(&mut blocks, TerminatorKind::Return);
108
109    let source = MirSource::from_instance(ty::InstanceKind::AsyncDropGlue(def_id, ty));
110    let mut body =
111        new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
112
113    body.coroutine = Some(Box::new(CoroutineInfo::initial(
114        coroutine_kind,
115        parent_args.as_coroutine().yield_ty(),
116        parent_args.as_coroutine().resume_ty(),
117    )));
118    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
119
120    // Returning noop body for types without `need async drop`
121    // (or sync Drop in case of !`need async drop` && `need drop`).
122    // And also for error types.
123    if needs_async_drop && !drop_ty.references_error() {
124        let dropee_ptr = Place::from(body.local_decls.push(LocalDecl::new(drop_ptr_ty, span)));
125        let st_kind = StatementKind::Assign(Box::new((
126            dropee_ptr,
127            Rvalue::Use(Operand::Move(coroutine_layout_dropee), WithRetag::Yes),
128        )));
129        body.basic_blocks_mut()[START_BLOCK].statements.push(Statement::new(source_info, st_kind));
130
131        let dropline = body.basic_blocks.last_index();
132
133        let patch = {
134            let mut elaborator = DropShimElaborator {
135                body: &body,
136                patch: MirPatch::new(&body),
137                tcx,
138                typing_env,
139                produce_async_drops: true,
140            };
141            let dropee = tcx.mk_place_deref(dropee_ptr);
142            let resume_block = elaborator.patch.resume_block();
143            elaborate_drop(
144                &mut elaborator,
145                source_info,
146                dropee,
147                (),
148                return_block,
149                Unwind::To(resume_block),
150                START_BLOCK,
151                dropline,
152            );
153            elaborator.patch
154        };
155        patch.apply(&mut body);
156    }
157
158    // We did not bother respecting deref separation, do it here.
159    deref_finder(tcx, &mut body, false);
160
161    body
162}
163
164// * For async drop a "normal" coroutine:
165// `async_drop_in_place<T>::{closure}.poll()` is converted into `T.future_drop_poll()`.
166// Every coroutine has its `poll` (calculate yourself a little further)
167// and its `future_drop_poll` (drop yourself a little further).
168//
169// * For async drop of "async drop coroutine" (`async_drop_in_place<T>::{closure}`):
170// Correct drop of such coroutine means normal execution of nested async drop.
171// async_drop(async_drop(T))::future_drop_poll() => async_drop(T)::poll().
172pub(super) fn build_future_drop_poll_shim<'tcx>(
173    tcx: TyCtxt<'tcx>,
174    def_id: DefId,
175    proxy_ty: Ty<'tcx>,
176    impl_ty: Ty<'tcx>,
177) -> Body<'tcx> {
178    let instance = ty::InstanceKind::FutureDropPollShim(def_id, proxy_ty, impl_ty);
179    let ty::Coroutine(coroutine_def_id, _) = impl_ty.kind() else {
180        ::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);
181    };
182
183    let span = tcx.def_span(def_id);
184
185    if tcx.is_async_drop_in_place_coroutine(*coroutine_def_id) {
186        build_adrop_for_adrop_shim(tcx, proxy_ty, impl_ty, span, instance)
187    } else {
188        build_adrop_for_coroutine_shim(tcx, proxy_ty, impl_ty, span, instance)
189    }
190}
191
192// For async drop a "normal" coroutine:
193// `async_drop_in_place<T>::{closure}.poll()` is converted into `T.future_drop_poll()`.
194// Every coroutine has its `poll` (calculate yourself a little further)
195// and its `future_drop_poll` (drop yourself a little further).
196fn build_adrop_for_coroutine_shim<'tcx>(
197    tcx: TyCtxt<'tcx>,
198    proxy_ty: Ty<'tcx>,
199    impl_ty: Ty<'tcx>,
200    span: Span,
201    instance: ty::InstanceKind<'tcx>,
202) -> Body<'tcx> {
203    let ty::Coroutine(coroutine_def_id, impl_args) = impl_ty.kind() else {
204        ::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);
205    };
206    let source_info = SourceInfo::outermost(span);
207    let body = tcx.optimized_mir(*coroutine_def_id).future_drop_poll().unwrap();
208    let mut body: Body<'tcx> =
209        EarlyBinder::bind(body.clone()).instantiate(tcx, impl_args).skip_norm_wip();
210    body.source.instance = instance;
211    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
212    body.var_debug_info.clear();
213
214    // converting `(_1: Pin<&mut CorLayout>, _2: &mut Context<'_>) -> Poll<()>`
215    // into `(_1: Pin<&mut ProxyLayout>, _2: &mut Context<'_>) -> Poll<()>`
216    // let mut _x: &mut CorLayout = &mut *_1.0.0;
217    // Replace old _1.0 accesses into _x accesses;
218    let proxy_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, proxy_ty);
219
220    let pin_adt_ref = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
221    let args = tcx.mk_args(&[proxy_ref.into()]);
222    let pin_proxy_ref = Ty::new_adt(tcx, pin_adt_ref, args);
223
224    let cor_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, impl_ty);
225    let cor_ref_local = body.local_decls.push(LocalDecl::new(cor_ref, span));
226
227    FixProxyFutureDropVisitor { tcx, replace_to: cor_ref_local }.visit_body(&mut body);
228
229    // Now changing first arg from Pin<&mut ImplCoroutine> to Pin<&mut ProxyCoroutine>
230    body.local_decls[SELF_ARG] = LocalDecl::new(pin_proxy_ref, span);
231
232    // Build the projection to assign `cor_ref_local = _1.<projection>`.
233    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![
234        // _1.0 : Pin<&mut ProxyLayout> ==> &mut ProxyLayout
235        PlaceElem::Field(FieldIdx::ZERO, proxy_ref),
236    ];
237
238    // _cor_ref_tmp = (*(*_proxy).0).0...
239    proxy_ty.find_async_drop_impl_coroutine(tcx, |ty| {
240        if ty != proxy_ty {
241            let ty_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
242            pin_proxy_to_cor_projection.push(PlaceElem::Deref);
243            pin_proxy_to_cor_projection.push(PlaceElem::Field(FieldIdx::ZERO, ty_ref));
244        }
245    });
246
247    // _cor_ref = cor_ref_tmp
248    let projected_pin = Place::from(SELF_ARG).project_deeper(&pin_proxy_to_cor_projection, tcx);
249    body.basic_blocks_mut()[START_BLOCK].statements.insert(
250        0,
251        Statement::new(
252            source_info,
253            StatementKind::Assign(Box::new((
254                Place::from(cor_ref_local),
255                Rvalue::Use(Operand::Move(projected_pin), WithRetag::Yes),
256            ))),
257        ),
258    );
259
260    // We did not bother respecting deref separation, do it here.
261    deref_finder(tcx, &mut body, false);
262
263    return body;
264
265    /// Replace Pin<&mut ImplCoroutine> accesses (_1.0) into Pin<&mut ProxyCoroutine> accesses
266    struct FixProxyFutureDropVisitor<'tcx> {
267        tcx: TyCtxt<'tcx>,
268        replace_to: Local,
269    }
270
271    impl<'tcx> MutVisitor<'tcx> for FixProxyFutureDropVisitor<'tcx> {
272        fn tcx(&self) -> TyCtxt<'tcx> {
273            self.tcx
274        }
275
276        fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
277            if place.local == SELF_ARG
278                && let Some((first, rest)) = place.projection.split_first()
279            {
280                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, _)));
281                *place = Place::from(self.replace_to).project_deeper(rest, self.tcx);
282            }
283        }
284    }
285}
286
287// When dropping async drop coroutine, we continue its execution.
288// async_drop(async_drop(T))::future_drop_poll() => async_drop(T)::poll()
289fn build_adrop_for_adrop_shim<'tcx>(
290    tcx: TyCtxt<'tcx>,
291    proxy_ty: Ty<'tcx>,
292    impl_ty: Ty<'tcx>,
293    span: Span,
294    instance: ty::InstanceKind<'tcx>,
295) -> Body<'tcx> {
296    let source_info = SourceInfo::outermost(span);
297    let proxy_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, proxy_ty);
298    // taking _1.0 (impl from Pin)
299    let proxy_ref_place =
300        Place::from(SELF_ARG).project_deeper(&[PlaceElem::Field(FieldIdx::ZERO, proxy_ref)], tcx);
301    let cor_ref = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, impl_ty);
302
303    // ret_ty = `Poll<()>`
304    let poll_adt_ref = tcx.adt_def(tcx.require_lang_item(LangItem::Poll, span));
305    let ret_ty = Ty::new_adt(tcx, poll_adt_ref, tcx.mk_args(&[tcx.types.unit.into()]));
306    // env_ty = `Pin<&mut proxy_ty>`
307    let pin_adt_ref = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
308    let env_ty = Ty::new_adt(tcx, pin_adt_ref, tcx.mk_args(&[proxy_ref.into()]));
309    // sig = `fn (Pin<&mut proxy_ty>, &mut Context) -> Poll<()>`
310    let sig = tcx.mk_fn_sig_safe_rust_abi([env_ty, Ty::new_task_context(tcx)], ret_ty);
311    // This function will be called with pinned proxy coroutine layout.
312    // We need to extract `Arg0.0` to get proxy layout, and then get `.0`
313    // further to receive impl coroutine (may be needed)
314    let mut locals = local_decls_for_sig(&sig, span);
315    let mut blocks = IndexVec::with_capacity(3);
316
317    let proxy_ref_local = locals.push(LocalDecl::new(proxy_ref, span));
318
319    let call_bb = BasicBlock::new(1);
320    let return_bb = BasicBlock::new(2);
321
322    let mut statements = Vec::new();
323
324    statements.push(Statement::new(
325        source_info,
326        StatementKind::Assign(Box::new((
327            Place::from(proxy_ref_local),
328            Rvalue::Use(Operand::Copy(proxy_ref_place), WithRetag::Yes),
329        ))),
330    ));
331
332    let mut cor_ptr_local = proxy_ref_local;
333    proxy_ty.find_async_drop_impl_coroutine(tcx, |ty| {
334        if ty != proxy_ty {
335            let ty_ptr = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
336            let impl_ptr_place = Place::from(cor_ptr_local)
337                .project_deeper(&[PlaceElem::Deref, PlaceElem::Field(FieldIdx::ZERO, ty_ptr)], tcx);
338            cor_ptr_local = locals.push(LocalDecl::new(ty_ptr, span));
339            // _cor_ptr = _proxy.0.0 (... .0)
340            statements.push(Statement::new(
341                source_info,
342                StatementKind::Assign(Box::new((
343                    Place::from(cor_ptr_local),
344                    Rvalue::Use(Operand::Copy(impl_ptr_place), WithRetag::Yes),
345                ))),
346            ));
347        }
348    });
349
350    // convert impl coroutine ptr into ref
351    let reborrow = Rvalue::Ref(
352        tcx.lifetimes.re_erased,
353        BorrowKind::Mut { kind: MutBorrowKind::Default },
354        tcx.mk_place_deref(Place::from(cor_ptr_local)),
355    );
356    let cor_ref_place = Place::from(locals.push(LocalDecl::new(cor_ref, span)));
357    statements.push(Statement::new(
358        source_info,
359        StatementKind::Assign(Box::new((cor_ref_place, reborrow))),
360    ));
361
362    // cor_pin_ty = `Pin<&mut cor_ref>`
363    let cor_pin_ty = Ty::new_adt(tcx, pin_adt_ref, tcx.mk_args(&[cor_ref.into()]));
364    let cor_pin_place = Place::from(locals.push(LocalDecl::new(cor_pin_ty, span)));
365
366    let pin_fn = tcx.require_lang_item(LangItem::PinNewUnchecked, span);
367    // call Pin<FutTy>::new_unchecked(&mut impl_cor)
368    blocks.push(BasicBlockData::new_stmts(
369        statements,
370        Some(Terminator {
371            source_info,
372            kind: TerminatorKind::Call {
373                func: Operand::function_handle(tcx, pin_fn, [cor_ref.into()], span),
374                args: [dummy_spanned(Operand::Move(cor_ref_place))].into(),
375                destination: cor_pin_place,
376                target: Some(call_bb),
377                unwind: UnwindAction::Continue,
378                call_source: CallSource::Misc,
379                fn_span: span,
380            },
381
382            attributes: ThinVec::new(),
383        }),
384        false,
385    ));
386    // When dropping async drop coroutine, we continue its execution:
387    // we call impl::poll (impl_layout, ctx)
388    let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, span);
389    let resume_ctx = Place::from(Local::new(2));
390    blocks.push(BasicBlockData::new(
391        Some(Terminator {
392            source_info,
393            kind: TerminatorKind::Call {
394                func: Operand::function_handle(tcx, poll_fn, [impl_ty.into()], span),
395                args: [
396                    dummy_spanned(Operand::Move(cor_pin_place)),
397                    dummy_spanned(Operand::Move(resume_ctx)),
398                ]
399                .into(),
400                destination: Place::return_place(),
401                target: Some(return_bb),
402                unwind: UnwindAction::Continue,
403                call_source: CallSource::Misc,
404                fn_span: span,
405            },
406
407            attributes: ThinVec::new(),
408        }),
409        false,
410    ));
411    blocks.push(BasicBlockData::new(
412        Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }),
413        false,
414    ));
415
416    let source = MirSource::from_instance(instance);
417    let mut body = new_body(source, blocks, locals, sig.inputs().len(), span);
418    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
419    return body;
420}