Skip to main content

rustc_mir_transform/
elaborate_drop.rs

1use std::{fmt, iter, mem};
2
3use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
4use rustc_hir::def::DefKind;
5use rustc_hir::lang_items::LangItem;
6use rustc_index::Idx;
7use rustc_middle::mir::*;
8use rustc_middle::ty::adjustment::PointerCoercion;
9use rustc_middle::ty::util::IntTypeExt;
10use rustc_middle::ty::{self, GenericArg, GenericArgsRef, Ty, TyCtxt};
11use rustc_middle::{bug, span_bug, traits};
12use rustc_span::DUMMY_SP;
13use rustc_span::source_map::{Spanned, dummy_spanned};
14use tracing::{debug, instrument};
15
16use crate::patch::MirPatch;
17
18/// Describes how/if a value should be dropped.
19#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropStyle {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DropStyle::Dead => "Dead",
                DropStyle::Static => "Static",
                DropStyle::Conditional => "Conditional",
                DropStyle::Open => "Open",
            })
    }
}Debug)]
20pub(crate) enum DropStyle {
21    /// The value is already dead at the drop location, no drop will be executed.
22    Dead,
23
24    /// The value is known to always be initialized at the drop location, drop will always be
25    /// executed.
26    Static,
27
28    /// Whether the value needs to be dropped depends on its drop flag.
29    Conditional,
30
31    /// An "open" drop is one where only the fields of a value are dropped.
32    ///
33    /// For example, this happens when moving out of a struct field: The rest of the struct will be
34    /// dropped in such an "open" drop. It is also used to generate drop glue for the individual
35    /// components of a value, for example for dropping array elements.
36    Open,
37}
38
39/// Which drop flags to affect/check with an operation.
40#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropFlagMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DropFlagMode::Shallow => "Shallow",
                DropFlagMode::Deep => "Deep",
            })
    }
}Debug)]
41pub(crate) enum DropFlagMode {
42    /// Only affect the top-level drop flag, not that of any contained fields.
43    Shallow,
44    /// Affect all nested drop flags in addition to the top-level one.
45    Deep,
46}
47
48/// Describes if unwinding is necessary and where to unwind to if a panic occurs.
49#[derive(#[automatically_derived]
impl ::core::marker::Copy for Unwind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Unwind {
    #[inline]
    fn clone(&self) -> Unwind {
        let _: ::core::clone::AssertParamIsClone<BasicBlock>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Unwind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Unwind::To(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "To",
                    &__self_0),
            Unwind::InCleanup =>
                ::core::fmt::Formatter::write_str(f, "InCleanup"),
        }
    }
}Debug)]
50pub(crate) enum Unwind {
51    /// Unwind to this block.
52    To(BasicBlock),
53    /// Already in an unwind path, any panic will cause an abort.
54    InCleanup,
55}
56
57impl Unwind {
58    fn is_cleanup(self) -> bool {
59        match self {
60            Unwind::To(..) => false,
61            Unwind::InCleanup => true,
62        }
63    }
64
65    fn into_action(self) -> UnwindAction {
66        match self {
67            Unwind::To(bb) => UnwindAction::Cleanup(bb),
68            Unwind::InCleanup => UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
69        }
70    }
71
72    fn map<F>(self, f: F) -> Self
73    where
74        F: FnOnce(BasicBlock) -> BasicBlock,
75    {
76        match self {
77            Unwind::To(bb) => Unwind::To(f(bb)),
78            Unwind::InCleanup => Unwind::InCleanup,
79        }
80    }
81}
82
83pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
84    /// The type representing paths that can be moved out of.
85    ///
86    /// Users can move out of individual fields of a struct, such as `a.b.c`. This type is used to
87    /// represent such move paths. Sometimes tracking individual move paths is not necessary, in
88    /// which case this may be set to (for example) `()`.
89    type Path: Copy + fmt::Debug;
90
91    // Accessors
92
93    fn patch_ref(&self) -> &MirPatch<'tcx>;
94    fn patch(&mut self) -> &mut MirPatch<'tcx>;
95    fn body(&self) -> &'a Body<'tcx>;
96    fn tcx(&self) -> TyCtxt<'tcx>;
97    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
98    fn allow_async_drops(&self) -> bool;
99
100    fn terminator_loc(&self, bb: BasicBlock) -> Location;
101
102    // Drop logic
103
104    /// Returns how `path` should be dropped, given `mode`.
105    fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
106
107    /// Returns the drop flag of `path` as a MIR `Operand` (or `None` if `path` has no drop flag).
108    fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
109
110    /// Modifies the MIR patch so that the drop flag of `path` (if any) is cleared at `location`.
111    ///
112    /// If `mode` is deep, drop flags of all child paths should also be cleared by inserting
113    /// additional statements.
114    fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
115
116    // Subpaths
117
118    /// Returns the subpath of a field of `path` (or `None` if there is no dedicated subpath).
119    ///
120    /// If this returns `None`, `field` will not get a dedicated drop flag.
121    fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path>;
122
123    /// Returns the subpath of a dereference of `path` (or `None` if there is no dedicated subpath).
124    ///
125    /// If this returns `None`, `*path` will not get a dedicated drop flag.
126    ///
127    /// This is only relevant for `Box<T>`, where the contained `T` can be moved out of the box.
128    fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
129
130    /// Returns the subpath of downcasting `path` to one of its variants.
131    ///
132    /// If this returns `None`, the downcast of `path` will not get a dedicated drop flag.
133    fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
134
135    /// Returns the subpath of indexing a fixed-size array `path`.
136    ///
137    /// If this returns `None`, elements of `path` will not get a dedicated drop flag.
138    ///
139    /// This is only relevant for array patterns, which can move out of individual array elements.
140    fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path>;
141}
142
143#[derive(#[automatically_derived]
impl<'a, 'b, 'tcx, D: ::core::fmt::Debug> ::core::fmt::Debug for
    DropCtxt<'a, 'b, 'tcx, D> where D: DropElaborator<'b, 'tcx>,
    D::Path: ::core::fmt::Debug {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["elaborator", "source_info", "place", "path", "succ", "unwind",
                        "dropline"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.elaborator, &self.source_info, &self.place, &self.path,
                        &self.succ, &self.unwind, &&self.dropline];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "DropCtxt",
            names, values)
    }
}Debug)]
144struct DropCtxt<'a, 'b, 'tcx, D>
145where
146    D: DropElaborator<'b, 'tcx>,
147{
148    elaborator: &'a mut D,
149
150    source_info: SourceInfo,
151
152    place: Place<'tcx>,
153    path: D::Path,
154    succ: BasicBlock,
155    unwind: Unwind,
156    dropline: Option<BasicBlock>,
157}
158
159/// "Elaborates" a drop of `place`/`path` and patches `bb`'s terminator to execute it.
160///
161/// The passed `elaborator` is used to determine what should happen at the drop terminator. It
162/// decides whether the drop can be statically determined or whether it needs a dynamic drop flag,
163/// and whether the drop is "open", ie. should be expanded to drop all subfields of the dropped
164/// value.
165///
166/// When this returns, the MIR patch in the `elaborator` contains the necessary changes.
167pub(crate) fn elaborate_drop<'b, 'tcx, D>(
168    elaborator: &mut D,
169    source_info: SourceInfo,
170    place: Place<'tcx>,
171    path: D::Path,
172    succ: BasicBlock,
173    unwind: Unwind,
174    bb: BasicBlock,
175    dropline: Option<BasicBlock>,
176) where
177    D: DropElaborator<'b, 'tcx>,
178    'tcx: 'b,
179{
180    DropCtxt { elaborator, source_info, place, path, succ, unwind, dropline }.elaborate_drop(bb)
181}
182
183impl<'a, 'b, 'tcx, D> DropCtxt<'a, 'b, 'tcx, D>
184where
185    D: DropElaborator<'b, 'tcx>,
186    'tcx: 'b,
187{
188    x;#[instrument(level = "trace", skip(self), ret)]
189    fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
190        if place.local < self.elaborator.body().local_decls.next_index() {
191            place.ty(self.elaborator.body(), self.tcx()).ty
192        } else {
193            // We don't have a slice with all the locals, since some are in the patch.
194            PlaceTy::from_ty(self.elaborator.patch_ref().local_ty(place.local))
195                .multi_projection_ty(self.elaborator.tcx(), place.projection)
196                .ty
197        }
198    }
199
200    fn tcx(&self) -> TyCtxt<'tcx> {
201        self.elaborator.tcx()
202    }
203
204    // Generates three blocks:
205    // * #1:pin_obj_bb:   call Pin<ObjTy>::new_unchecked(&mut obj)
206    // * #2:call_drop_bb: fut = call obj.<AsyncDrop::drop>() OR call async_drop_in_place<T>(obj)
207    // * #3:drop_term_bb: drop (obj, fut, ...)
208    // We keep async drop unexpanded to poll-loop here, to expand it later, at StateTransform -
209    //   into states expand.
210    // call_destructor_only - to call only AsyncDrop::drop, not full async_drop_in_place glue
211    fn build_async_drop(
212        &mut self,
213        place: Place<'tcx>,
214        drop_ty: Ty<'tcx>,
215        bb: Option<BasicBlock>,
216        succ: BasicBlock,
217        unwind: Unwind,
218        dropline: Option<BasicBlock>,
219        call_destructor_only: bool,
220    ) -> BasicBlock {
221        let tcx = self.tcx();
222        let span = self.source_info.span;
223
224        let pin_obj_bb = bb.unwrap_or_else(|| {
225            self.elaborator.patch().new_block(BasicBlockData::new(
226                Some(Terminator {
227                    // Temporary terminator, will be replaced by patch
228                    source_info: self.source_info,
229                    kind: TerminatorKind::Return,
230                }),
231                false,
232            ))
233        });
234
235        let (fut_ty, drop_fn_def_id, trait_args) = if call_destructor_only {
236            // Resolving obj.<AsyncDrop::drop>()
237            let trait_ref =
238                ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::AsyncDrop, span), [drop_ty]);
239            let (drop_trait, trait_args) = match tcx.codegen_select_candidate(
240                ty::TypingEnv::fully_monomorphized().as_query_input(trait_ref),
241            ) {
242                Ok(traits::ImplSource::UserDefined(traits::ImplSourceUserDefinedData {
243                    impl_def_id,
244                    args,
245                    ..
246                })) => (*impl_def_id, *args),
247                impl_source => {
248                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("invalid `AsyncDrop` impl_source: {0:?}", impl_source));span_bug!(span, "invalid `AsyncDrop` impl_source: {:?}", impl_source);
249                }
250            };
251            // impl_item_refs may be empty if drop fn is not implemented in 'impl AsyncDrop for ...'
252            // (#140974).
253            // Such code will report error, so just generate sync drop here and return
254            let Some(drop_fn_def_id) =
255                tcx.associated_item_def_ids(drop_trait).first().and_then(|&def_id| {
256                    if tcx.def_kind(def_id) == DefKind::AssocFn
257                        && tcx.check_args_compatible(def_id, trait_args)
258                    {
259                        Some(def_id)
260                    } else {
261                        None
262                    }
263                })
264            else {
265                tcx.dcx().span_delayed_bug(
266                    self.elaborator.body().span,
267                    "AsyncDrop type without correct `async fn drop(...)`.",
268                );
269                self.elaborator.patch().patch_terminator(
270                    pin_obj_bb,
271                    TerminatorKind::Drop {
272                        place,
273                        target: succ,
274                        unwind: unwind.into_action(),
275                        replace: false,
276                        drop: None,
277                        async_fut: None,
278                    },
279                );
280                return pin_obj_bb;
281            };
282            let drop_fn = Ty::new_fn_def(tcx, drop_fn_def_id, trait_args);
283            let sig = drop_fn.fn_sig(tcx);
284            let sig = tcx.instantiate_bound_regions_with_erased(sig);
285            (sig.output(), drop_fn_def_id, trait_args)
286        } else {
287            // Resolving async_drop_in_place<T> function for drop_ty
288            let drop_fn_def_id = tcx.require_lang_item(LangItem::AsyncDropInPlace, span);
289            let trait_args = tcx.mk_args(&[drop_ty.into()]);
290            let sig = tcx.fn_sig(drop_fn_def_id).instantiate(tcx, trait_args);
291            let sig = tcx.instantiate_bound_regions_with_erased(sig);
292            (sig.output(), drop_fn_def_id, trait_args)
293        };
294
295        let fut = Place::from(self.new_temp(fut_ty));
296
297        // #1:pin_obj_bb >>> obj_ref = &mut obj
298        let obj_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, drop_ty);
299        let obj_ref_place = Place::from(self.new_temp(obj_ref_ty));
300
301        let term_loc = self.elaborator.terminator_loc(pin_obj_bb);
302        self.elaborator.patch().add_assign(
303            term_loc,
304            obj_ref_place,
305            Rvalue::Ref(
306                tcx.lifetimes.re_erased,
307                BorrowKind::Mut { kind: MutBorrowKind::Default },
308                place,
309            ),
310        );
311
312        // pin_obj_place preparation
313        let pin_obj_new_unchecked_fn = Ty::new_fn_def(
314            tcx,
315            tcx.require_lang_item(LangItem::PinNewUnchecked, span),
316            [GenericArg::from(obj_ref_ty)],
317        );
318        let pin_obj_ty = pin_obj_new_unchecked_fn.fn_sig(tcx).output().no_bound_vars().unwrap();
319        let pin_obj_place = Place::from(self.new_temp(pin_obj_ty));
320        let pin_obj_new_unchecked_fn = Operand::Constant(Box::new(ConstOperand {
321            span,
322            user_ty: None,
323            const_: Const::zero_sized(pin_obj_new_unchecked_fn),
324        }));
325
326        // #3:drop_term_bb
327        let drop_term_bb = self.new_block(
328            unwind,
329            TerminatorKind::Drop {
330                place,
331                target: succ,
332                unwind: unwind.into_action(),
333                replace: false,
334                drop: dropline,
335                async_fut: Some(fut.local),
336            },
337        );
338
339        // #2:call_drop_bb
340        let mut call_statements = Vec::new();
341        let drop_arg = if call_destructor_only {
342            pin_obj_place
343        } else {
344            let ty::Adt(adt_def, adt_args) = pin_obj_ty.kind() else {
345                ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
346            };
347            let obj_ptr_ty = Ty::new_mut_ptr(tcx, drop_ty);
348            let unwrap_ty = adt_def.non_enum_variant().fields[FieldIdx::ZERO].ty(tcx, adt_args);
349            let obj_ref_place = Place::from(self.new_temp(unwrap_ty));
350            call_statements.push(self.assign(
351                obj_ref_place,
352                Rvalue::Use(Operand::Copy(tcx.mk_place_field(
353                    pin_obj_place,
354                    FieldIdx::ZERO,
355                    unwrap_ty,
356                ))),
357            ));
358
359            let obj_ptr_place = Place::from(self.new_temp(obj_ptr_ty));
360
361            let addr = Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_deref(obj_ref_place));
362            call_statements.push(self.assign(obj_ptr_place, addr));
363            obj_ptr_place
364        };
365        call_statements
366            .push(Statement::new(self.source_info, StatementKind::StorageLive(fut.local)));
367
368        let call_drop_bb = self.new_block_with_statements(
369            unwind,
370            call_statements,
371            TerminatorKind::Call {
372                func: Operand::function_handle(tcx, drop_fn_def_id, trait_args, span),
373                args: [Spanned { node: Operand::Move(drop_arg), span: DUMMY_SP }].into(),
374                destination: fut,
375                target: Some(drop_term_bb),
376                unwind: unwind.into_action(),
377                call_source: CallSource::Misc,
378                fn_span: self.source_info.span,
379            },
380        );
381
382        // StorageDead(fut) in self.succ block (at the begin)
383        self.elaborator.patch().add_statement(
384            Location { block: self.succ, statement_index: 0 },
385            StatementKind::StorageDead(fut.local),
386        );
387        // StorageDead(fut) in unwind block (at the begin)
388        if let Unwind::To(block) = unwind {
389            self.elaborator.patch().add_statement(
390                Location { block, statement_index: 0 },
391                StatementKind::StorageDead(fut.local),
392            );
393        }
394        // StorageDead(fut) in dropline block (at the begin)
395        if let Some(block) = dropline {
396            self.elaborator.patch().add_statement(
397                Location { block, statement_index: 0 },
398                StatementKind::StorageDead(fut.local),
399            );
400        }
401
402        // #1:pin_obj_bb >>> call Pin<ObjTy>::new_unchecked(&mut obj)
403        self.elaborator.patch().patch_terminator(
404            pin_obj_bb,
405            TerminatorKind::Call {
406                func: pin_obj_new_unchecked_fn,
407                args: [dummy_spanned(Operand::Move(obj_ref_place))].into(),
408                destination: pin_obj_place,
409                target: Some(call_drop_bb),
410                unwind: unwind.into_action(),
411                call_source: CallSource::Misc,
412                fn_span: span,
413            },
414        );
415        pin_obj_bb
416    }
417
418    fn build_drop(&mut self, bb: BasicBlock) {
419        let drop_ty = self.place_ty(self.place);
420        if self.tcx().features().async_drop()
421            && self.elaborator.body().coroutine.is_some()
422            && self.elaborator.allow_async_drops()
423            && !self.elaborator.patch_ref().block(self.elaborator.body(), bb).is_cleanup
424            && drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
425        {
426            self.build_async_drop(
427                self.place,
428                drop_ty,
429                Some(bb),
430                self.succ,
431                self.unwind,
432                self.dropline,
433                false,
434            );
435        } else {
436            self.elaborator.patch().patch_terminator(
437                bb,
438                TerminatorKind::Drop {
439                    place: self.place,
440                    target: self.succ,
441                    unwind: self.unwind.into_action(),
442                    replace: false,
443                    drop: None,
444                    async_fut: None,
445                },
446            );
447        }
448    }
449
450    /// This elaborates a single drop instruction, located at `bb`, and
451    /// patches over it.
452    ///
453    /// The elaborated drop checks the drop flags to only drop what
454    /// is initialized.
455    ///
456    /// In addition, the relevant drop flags also need to be cleared
457    /// to avoid double-drops. However, in the middle of a complex
458    /// drop, one must avoid clearing some of the flags before they
459    /// are read, as that would cause a memory leak.
460    ///
461    /// In particular, when dropping an ADT, multiple fields may be
462    /// joined together under the `rest` subpath. They are all controlled
463    /// by the primary drop flag, but only the last rest-field dropped
464    /// should clear it (and it must also not clear anything else).
465    //
466    // FIXME: I think we should just control the flags externally,
467    // and then we do not need this machinery.
468    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("elaborate_drop",
                                    "rustc_mir_transform::elaborate_drop",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                                    ::tracing_core::__macro_support::Option::Some(468u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                                    ::tracing_core::field::FieldSet::new(&["self", "bb"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bb)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
                DropStyle::Dead => {
                    self.elaborator.patch().patch_terminator(bb,
                        TerminatorKind::Goto { target: self.succ });
                }
                DropStyle::Static => { self.build_drop(bb); }
                DropStyle::Conditional => {
                    let drop_bb = self.complete_drop(self.succ, self.unwind);
                    self.elaborator.patch().patch_terminator(bb,
                        TerminatorKind::Goto { target: drop_bb });
                }
                DropStyle::Open => {
                    let drop_bb = self.open_drop();
                    self.elaborator.patch().patch_terminator(bb,
                        TerminatorKind::Goto { target: drop_bb });
                }
            }
        }
    }
}#[instrument(level = "debug")]
469    fn elaborate_drop(&mut self, bb: BasicBlock) {
470        match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
471            DropStyle::Dead => {
472                self.elaborator
473                    .patch()
474                    .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
475            }
476            DropStyle::Static => {
477                self.build_drop(bb);
478            }
479            DropStyle::Conditional => {
480                let drop_bb = self.complete_drop(self.succ, self.unwind);
481                self.elaborator
482                    .patch()
483                    .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
484            }
485            DropStyle::Open => {
486                let drop_bb = self.open_drop();
487                self.elaborator
488                    .patch()
489                    .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
490            }
491        }
492    }
493
494    /// Returns the place and move path for each field of `variant`,
495    /// (the move path is `None` if the field is a rest field).
496    fn move_paths_for_fields(
497        &self,
498        base_place: Place<'tcx>,
499        variant_path: D::Path,
500        variant: &'tcx ty::VariantDef,
501        args: GenericArgsRef<'tcx>,
502    ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
503        variant
504            .fields
505            .iter_enumerated()
506            .map(|(field_idx, field)| {
507                let subpath = self.elaborator.field_subpath(variant_path, field_idx);
508                let tcx = self.tcx();
509
510                match (&self.elaborator.typing_env().typing_mode,
        &ty::TypingMode::PostAnalysis) {
    (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);
        }
    }
};assert_eq!(self.elaborator.typing_env().typing_mode, ty::TypingMode::PostAnalysis);
511                let field_ty = field.ty(tcx, args);
512                // We silently leave an unnormalized type here to support polymorphic drop
513                // elaboration for users of rustc internal APIs
514                let field_ty = tcx
515                    .try_normalize_erasing_regions(self.elaborator.typing_env(), field_ty)
516                    .unwrap_or(field_ty);
517
518                (tcx.mk_place_field(base_place, field_idx, field_ty), subpath)
519            })
520            .collect()
521    }
522
523    fn drop_subpath(
524        &mut self,
525        place: Place<'tcx>,
526        path: Option<D::Path>,
527        succ: BasicBlock,
528        unwind: Unwind,
529        dropline: Option<BasicBlock>,
530    ) -> BasicBlock {
531        if let Some(path) = path {
532            {
    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/elaborate_drop.rs:532",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(532u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_subpath: for std field {0:?}",
                                                    place) as &dyn Value))])
            });
    } else { ; }
};debug!("drop_subpath: for std field {:?}", place);
533
534            DropCtxt {
535                elaborator: self.elaborator,
536                source_info: self.source_info,
537                path,
538                place,
539                succ,
540                unwind,
541                dropline,
542            }
543            .elaborated_drop_block()
544        } else {
545            {
    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/elaborate_drop.rs:545",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(545u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_subpath: for rest field {0:?}",
                                                    place) as &dyn Value))])
            });
    } else { ; }
};debug!("drop_subpath: for rest field {:?}", place);
546
547            DropCtxt {
548                elaborator: self.elaborator,
549                source_info: self.source_info,
550                place,
551                succ,
552                unwind,
553                dropline,
554                // Using `self.path` here to condition the drop on
555                // our own drop flag.
556                path: self.path,
557            }
558            .complete_drop(succ, unwind)
559        }
560    }
561
562    /// Creates one-half of the drop ladder for a list of fields, and return
563    /// the list of steps in it in reverse order, with the first step
564    /// dropping 0 fields and so on.
565    ///
566    /// `unwind_ladder` is such a list of steps in reverse order,
567    /// which is called if the matching step of the drop glue panics.
568    ///
569    /// `dropline_ladder` is a similar list of steps in reverse order,
570    /// which is called if the matching step of the drop glue will contain async drop
571    /// (expanded later to Yield) and the containing coroutine will be dropped at this point.
572    fn drop_halfladder(
573        &mut self,
574        unwind_ladder: &[Unwind],
575        dropline_ladder: &[Option<BasicBlock>],
576        mut succ: BasicBlock,
577        fields: &[(Place<'tcx>, Option<D::Path>)],
578    ) -> Vec<BasicBlock> {
579        iter::once(succ)
580            .chain(::itertools::__std_iter::IntoIterator::into_iter(fields.iter().rev()).zip(unwind_ladder).zip(dropline_ladder).map(|((a,
            b), b)| (a, b, b))itertools::izip!(fields.iter().rev(), unwind_ladder, dropline_ladder).map(
581                |(&(place, path), &unwind_succ, &dropline_to)| {
582                    succ = self.drop_subpath(place, path, succ, unwind_succ, dropline_to);
583                    succ
584                },
585            ))
586            .collect()
587    }
588
589    fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind, Option<BasicBlock>) {
590        // Clear the "master" drop flag at the end. This is needed
591        // because the "master" drop protects the ADT's discriminant,
592        // which is invalidated after the ADT is dropped.
593        (
594            self.drop_flag_reset_block(DropFlagMode::Shallow, self.succ, self.unwind),
595            self.unwind,
596            self.dropline,
597        )
598    }
599
600    /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
601    ///
602    /// For example, with 3 fields, the drop ladder is
603    ///
604    /// ```text
605    /// .d0:
606    ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
607    /// .d1:
608    ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
609    /// .d2:
610    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
611    /// .c1:
612    ///     ELAB(drop location.1 [target=.c2])
613    /// .c2:
614    ///     ELAB(drop location.2 [target=`self.unwind`])
615    /// ```
616    ///
617    /// For possible-async drops in coroutines we also need dropline ladder
618    /// ```text
619    /// .d0 (mainline):
620    ///     ELAB(drop location.0 [target=.d1, unwind=.c1, drop=.e1])
621    /// .d1 (mainline):
622    ///     ELAB(drop location.1 [target=.d2, unwind=.c2, drop=.e2])
623    /// .d2 (mainline):
624    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`, drop=`self.drop`])
625    /// .c1 (unwind):
626    ///     ELAB(drop location.1 [target=.c2])
627    /// .c2 (unwind):
628    ///     ELAB(drop location.2 [target=`self.unwind`])
629    /// .e1 (dropline):
630    ///     ELAB(drop location.1 [target=.e2, unwind=.c2])
631    /// .e2 (dropline):
632    ///     ELAB(drop location.2 [target=`self.drop`, unwind=`self.unwind`])
633    /// ```
634    ///
635    /// NOTE: this does not clear the master drop flag, so you need
636    /// to point succ/unwind on a `drop_ladder_bottom`.
637    fn drop_ladder(
638        &mut self,
639        fields: Vec<(Place<'tcx>, Option<D::Path>)>,
640        succ: BasicBlock,
641        unwind: Unwind,
642        dropline: Option<BasicBlock>,
643    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
644        {
    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/elaborate_drop.rs:644",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(644u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_ladder({0:?}, {1:?})",
                                                    self, fields) as &dyn Value))])
            });
    } else { ; }
};debug!("drop_ladder({:?}, {:?})", self, fields);
645        if !if unwind.is_cleanup() { dropline.is_none() } else { true } {
    {
        ::core::panicking::panic_fmt(format_args!("Dropline is set for cleanup drop ladder"));
    }
};assert!(
646            if unwind.is_cleanup() { dropline.is_none() } else { true },
647            "Dropline is set for cleanup drop ladder"
648        );
649
650        let mut fields = fields;
651        fields.retain(|&(place, _)| {
652            self.place_ty(place).needs_drop(self.tcx(), self.elaborator.typing_env())
653        });
654
655        {
    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/elaborate_drop.rs:655",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(655u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_ladder - fields needing drop: {0:?}",
                                                    fields) as &dyn Value))])
            });
    } else { ; }
};debug!("drop_ladder - fields needing drop: {:?}", fields);
656
657        let dropline_ladder: Vec<Option<BasicBlock>> = ::alloc::vec::from_elem(None, fields.len() + 1)vec![None; fields.len() + 1];
658        let unwind_ladder = ::alloc::vec::from_elem(Unwind::InCleanup, fields.len() + 1)vec![Unwind::InCleanup; fields.len() + 1];
659        let unwind_ladder: Vec<_> = if let Unwind::To(succ) = unwind {
660            let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
661            halfladder.into_iter().map(Unwind::To).collect()
662        } else {
663            unwind_ladder
664        };
665        let dropline_ladder: Vec<_> = if let Some(succ) = dropline {
666            let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
667            halfladder.into_iter().map(Some).collect()
668        } else {
669            dropline_ladder
670        };
671
672        let normal_ladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
673
674        (
675            *normal_ladder.last().unwrap(),
676            *unwind_ladder.last().unwrap(),
677            *dropline_ladder.last().unwrap(),
678        )
679    }
680
681    fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
682        {
    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/elaborate_drop.rs:682",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(682u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("open_drop_for_tuple({0:?}, {1:?})",
                                                    self, tys) as &dyn Value))])
            });
    } else { ; }
};debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
683
684        let fields = tys
685            .iter()
686            .enumerate()
687            .map(|(i, &ty)| {
688                (
689                    self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
690                    self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
691                )
692            })
693            .collect();
694
695        let (succ, unwind, dropline) = self.drop_ladder_bottom();
696        self.drop_ladder(fields, succ, unwind, dropline).0
697    }
698
699    /// Drops the T contained in a `Box<T>` if it has not been moved out of
700    x;#[instrument(level = "debug", ret)]
701    fn open_drop_for_box_contents(
702        &mut self,
703        adt: ty::AdtDef<'tcx>,
704        args: GenericArgsRef<'tcx>,
705        succ: BasicBlock,
706        unwind: Unwind,
707        dropline: Option<BasicBlock>,
708    ) -> BasicBlock {
709        // drop glue is sent straight to codegen
710        // box cannot be directly dereferenced
711        let unique_ty = adt.non_enum_variant().fields[FieldIdx::ZERO].ty(self.tcx(), args);
712        let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant();
713        let nonnull_ty = unique_variant.fields[FieldIdx::ZERO].ty(self.tcx(), args);
714        let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty());
715
716        let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
717        let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
718
719        let ptr_local = self.new_temp(ptr_ty);
720
721        let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
722        let interior_path = self.elaborator.deref_subpath(self.path);
723
724        let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind, dropline);
725
726        let setup_bbd = BasicBlockData::new_stmts(
727            vec![self.assign(
728                Place::from(ptr_local),
729                Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
730            )],
731            Some(Terminator {
732                kind: TerminatorKind::Goto { target: do_drop_bb },
733                source_info: self.source_info,
734            }),
735            unwind.is_cleanup(),
736        );
737        self.elaborator.patch().new_block(setup_bbd)
738    }
739
740    x;#[instrument(level = "debug", ret)]
741    fn open_drop_for_adt(
742        &mut self,
743        adt: ty::AdtDef<'tcx>,
744        args: GenericArgsRef<'tcx>,
745    ) -> BasicBlock {
746        if adt.variants().is_empty() {
747            return self.elaborator.patch().new_block(BasicBlockData::new(
748                Some(Terminator {
749                    source_info: self.source_info,
750                    kind: TerminatorKind::Unreachable,
751                }),
752                self.unwind.is_cleanup(),
753            ));
754        }
755
756        let skip_contents = adt.is_union() || adt.is_manually_drop();
757        let contents_drop = if skip_contents {
758            if adt.has_dtor(self.tcx()) && self.elaborator.get_drop_flag(self.path).is_some() {
759                // the top-level drop flag is usually cleared by open_drop_for_adt_contents
760                // types with destructors would still need an empty drop ladder to clear it
761
762                // however, these types are only open dropped in `DropShimElaborator`
763                // which does not have drop flags
764                // a future box-like "DerefMove" trait would allow for this case to happen
765                span_bug!(self.source_info.span, "open dropping partially moved union");
766            }
767
768            (self.succ, self.unwind, self.dropline)
769        } else {
770            self.open_drop_for_adt_contents(adt, args)
771        };
772
773        if adt.has_dtor(self.tcx()) {
774            let destructor_block = if adt.is_box() {
775                // we need to drop the inside of the box before running the destructor
776                let succ = self.destructor_call_block_sync((contents_drop.0, contents_drop.1));
777                let unwind = contents_drop
778                    .1
779                    .map(|unwind| self.destructor_call_block_sync((unwind, Unwind::InCleanup)));
780                let dropline = contents_drop
781                    .2
782                    .map(|dropline| self.destructor_call_block_sync((dropline, contents_drop.1)));
783                self.open_drop_for_box_contents(adt, args, succ, unwind, dropline)
784            } else {
785                self.destructor_call_block(contents_drop)
786            };
787
788            self.drop_flag_test_block(destructor_block, contents_drop.0, contents_drop.1)
789        } else {
790            contents_drop.0
791        }
792    }
793
794    fn open_drop_for_adt_contents(
795        &mut self,
796        adt: ty::AdtDef<'tcx>,
797        args: GenericArgsRef<'tcx>,
798    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
799        let (succ, unwind, dropline) = self.drop_ladder_bottom();
800        if !adt.is_enum() {
801            let fields =
802                self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args);
803            self.drop_ladder(fields, succ, unwind, dropline)
804        } else {
805            self.open_drop_for_multivariant(adt, args, succ, unwind, dropline)
806        }
807    }
808
809    fn open_drop_for_multivariant(
810        &mut self,
811        adt: ty::AdtDef<'tcx>,
812        args: GenericArgsRef<'tcx>,
813        succ: BasicBlock,
814        unwind: Unwind,
815        dropline: Option<BasicBlock>,
816    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
817        let mut values = Vec::with_capacity(adt.variants().len());
818        let mut normal_blocks = Vec::with_capacity(adt.variants().len());
819        let mut unwind_blocks =
820            if unwind.is_cleanup() { None } else { Some(Vec::with_capacity(adt.variants().len())) };
821        let mut dropline_blocks =
822            if dropline.is_none() { None } else { Some(Vec::with_capacity(adt.variants().len())) };
823
824        let mut have_otherwise_with_drop_glue = false;
825        let mut have_otherwise = false;
826        let tcx = self.tcx();
827
828        for (variant_index, discr) in adt.discriminants(tcx) {
829            let variant = &adt.variant(variant_index);
830            let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
831
832            if let Some(variant_path) = subpath {
833                let base_place = tcx.mk_place_elem(
834                    self.place,
835                    ProjectionElem::Downcast(Some(variant.name), variant_index),
836                );
837                let fields = self.move_paths_for_fields(base_place, variant_path, variant, args);
838                values.push(discr.val);
839                if let Unwind::To(unwind) = unwind {
840                    // We can't use the half-ladder from the original
841                    // drop ladder, because this breaks the
842                    // "funclet can't have 2 successor funclets"
843                    // requirement from MSVC:
844                    //
845                    //           switch       unwind-switch
846                    //          /      \         /        \
847                    //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
848                    //         |        |      /             |
849                    //    v1.1-unwind  v2.1-unwind           |
850                    //      ^                                |
851                    //       \-------------------------------/
852                    //
853                    // Create a duplicate half-ladder to avoid that. We
854                    // could technically only do this on MSVC, but I
855                    // I want to minimize the divergence between MSVC
856                    // and non-MSVC.
857
858                    let unwind_blocks = unwind_blocks.as_mut().unwrap();
859                    let unwind_ladder = ::alloc::vec::from_elem(Unwind::InCleanup, fields.len() + 1)vec![Unwind::InCleanup; fields.len() + 1];
860                    let dropline_ladder: Vec<Option<BasicBlock>> = ::alloc::vec::from_elem(None, fields.len() + 1)vec![None; fields.len() + 1];
861                    let halfladder =
862                        self.drop_halfladder(&unwind_ladder, &dropline_ladder, unwind, &fields);
863                    unwind_blocks.push(halfladder.last().cloned().unwrap());
864                }
865                let (normal, _, drop_bb) = self.drop_ladder(fields, succ, unwind, dropline);
866                normal_blocks.push(normal);
867                if dropline.is_some() {
868                    dropline_blocks.as_mut().unwrap().push(drop_bb.unwrap());
869                }
870            } else {
871                have_otherwise = true;
872
873                let typing_env = self.elaborator.typing_env();
874                let have_field_with_drop_glue = variant
875                    .fields
876                    .iter()
877                    .any(|field| field.ty(tcx, args).needs_drop(tcx, typing_env));
878                if have_field_with_drop_glue {
879                    have_otherwise_with_drop_glue = true;
880                }
881            }
882        }
883
884        if !have_otherwise {
885            values.pop();
886        } else if !have_otherwise_with_drop_glue {
887            normal_blocks.push(self.goto_block(succ, unwind));
888            if let Unwind::To(unwind) = unwind {
889                unwind_blocks.as_mut().unwrap().push(self.goto_block(unwind, Unwind::InCleanup));
890            }
891        } else {
892            normal_blocks.push(self.drop_block(succ, unwind));
893            if let Unwind::To(unwind) = unwind {
894                unwind_blocks.as_mut().unwrap().push(self.drop_block(unwind, Unwind::InCleanup));
895            }
896        }
897
898        (
899            self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
900            unwind.map(|unwind| {
901                self.adt_switch_block(
902                    adt,
903                    unwind_blocks.unwrap(),
904                    &values,
905                    unwind,
906                    Unwind::InCleanup,
907                )
908            }),
909            dropline.map(|dropline| {
910                self.adt_switch_block(adt, dropline_blocks.unwrap(), &values, dropline, unwind)
911            }),
912        )
913    }
914
915    fn adt_switch_block(
916        &mut self,
917        adt: ty::AdtDef<'tcx>,
918        blocks: Vec<BasicBlock>,
919        values: &[u128],
920        succ: BasicBlock,
921        unwind: Unwind,
922    ) -> BasicBlock {
923        // If there are multiple variants, then if something
924        // is present within the enum the discriminant, tracked
925        // by the rest path, must be initialized.
926        //
927        // Additionally, we do not want to switch on the
928        // discriminant after it is free-ed, because that
929        // way lies only trouble.
930        let discr_ty = adt.repr().discr_type().to_ty(self.tcx());
931        let discr = Place::from(self.new_temp(discr_ty));
932        let discr_rv = Rvalue::Discriminant(self.place);
933        let switch_block = BasicBlockData::new_stmts(
934            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.assign(discr, discr_rv)]))vec![self.assign(discr, discr_rv)],
935            Some(Terminator {
936                source_info: self.source_info,
937                kind: TerminatorKind::SwitchInt {
938                    discr: Operand::Move(discr),
939                    targets: SwitchTargets::new(
940                        values.iter().copied().zip(blocks.iter().copied()),
941                        *blocks.last().unwrap(),
942                    ),
943                },
944            }),
945            unwind.is_cleanup(),
946        );
947        let switch_block = self.elaborator.patch().new_block(switch_block);
948        self.drop_flag_test_block(switch_block, succ, unwind)
949    }
950
951    fn destructor_call_block_sync(&mut self, (succ, unwind): (BasicBlock, Unwind)) -> BasicBlock {
952        {
    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/elaborate_drop.rs:952",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(952u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("destructor_call_block_sync({0:?}, {1:?})",
                                                    self, succ) as &dyn Value))])
            });
    } else { ; }
};debug!("destructor_call_block_sync({:?}, {:?})", self, succ);
953        let tcx = self.tcx();
954        let drop_trait = tcx.require_lang_item(LangItem::Drop, DUMMY_SP);
955        let drop_fn = tcx.associated_item_def_ids(drop_trait)[0];
956        let ty = self.place_ty(self.place);
957
958        let ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
959        let ref_place = self.new_temp(ref_ty);
960        let unit_temp = Place::from(self.new_temp(tcx.types.unit));
961
962        let result = BasicBlockData::new_stmts(
963            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.assign(Place::from(ref_place),
                    Rvalue::Ref(tcx.lifetimes.re_erased,
                        BorrowKind::Mut { kind: MutBorrowKind::Default },
                        self.place))]))vec![self.assign(
964                Place::from(ref_place),
965                Rvalue::Ref(
966                    tcx.lifetimes.re_erased,
967                    BorrowKind::Mut { kind: MutBorrowKind::Default },
968                    self.place,
969                ),
970            )],
971            Some(Terminator {
972                kind: TerminatorKind::Call {
973                    func: Operand::function_handle(
974                        tcx,
975                        drop_fn,
976                        [ty.into()],
977                        self.source_info.span,
978                    ),
979                    args: [Spanned { node: Operand::Move(Place::from(ref_place)), span: DUMMY_SP }]
980                        .into(),
981                    destination: unit_temp,
982                    target: Some(succ),
983                    unwind: unwind.into_action(),
984                    call_source: CallSource::Misc,
985                    fn_span: self.source_info.span,
986                },
987                source_info: self.source_info,
988            }),
989            unwind.is_cleanup(),
990        );
991
992        self.elaborator.patch().new_block(result)
993    }
994
995    fn destructor_call_block(
996        &mut self,
997        (succ, unwind, dropline): (BasicBlock, Unwind, Option<BasicBlock>),
998    ) -> BasicBlock {
999        {
    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/elaborate_drop.rs:999",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(999u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("destructor_call_block({0:?}, {1:?})",
                                                    self, succ) as &dyn Value))])
            });
    } else { ; }
};debug!("destructor_call_block({:?}, {:?})", self, succ);
1000        let ty = self.place_ty(self.place);
1001        if self.tcx().features().async_drop()
1002            && self.elaborator.body().coroutine.is_some()
1003            && self.elaborator.allow_async_drops()
1004            && !unwind.is_cleanup()
1005            && ty.is_async_drop(self.tcx(), self.elaborator.typing_env())
1006        {
1007            self.build_async_drop(self.place, ty, None, succ, unwind, dropline, true)
1008        } else {
1009            self.destructor_call_block_sync((succ, unwind))
1010        }
1011    }
1012
1013    /// Create a loop that drops an array:
1014    ///
1015    /// ```text
1016    /// loop-block:
1017    ///    can_go = cur == len
1018    ///    if can_go then succ else drop-block
1019    /// drop-block:
1020    ///    ptr = &raw mut P[cur]
1021    ///    cur = cur + 1
1022    ///    drop(ptr)
1023    /// ```
1024    fn drop_loop(
1025        &mut self,
1026        succ: BasicBlock,
1027        cur: Local,
1028        len: Local,
1029        ety: Ty<'tcx>,
1030        unwind: Unwind,
1031        dropline: Option<BasicBlock>,
1032    ) -> BasicBlock {
1033        let copy = |place: Place<'tcx>| Operand::Copy(place);
1034        let move_ = |place: Place<'tcx>| Operand::Move(place);
1035        let tcx = self.tcx();
1036
1037        let ptr_ty = Ty::new_mut_ptr(tcx, ety);
1038        let ptr = Place::from(self.new_temp(ptr_ty));
1039        let can_go = Place::from(self.new_temp(tcx.types.bool));
1040        let one = self.constant_usize(1);
1041
1042        let drop_block = BasicBlockData::new_stmts(
1043            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.assign(ptr,
                    Rvalue::RawPtr(RawPtrKind::Mut,
                        tcx.mk_place_index(self.place, cur))),
                self.assign(cur.into(),
                    Rvalue::BinaryOp(BinOp::Add,
                        Box::new((move_(cur.into()), one))))]))vec![
1044                self.assign(
1045                    ptr,
1046                    Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_index(self.place, cur)),
1047                ),
1048                self.assign(
1049                    cur.into(),
1050                    Rvalue::BinaryOp(BinOp::Add, Box::new((move_(cur.into()), one))),
1051                ),
1052            ],
1053            Some(Terminator {
1054                source_info: self.source_info,
1055                // this gets overwritten by drop elaboration.
1056                kind: TerminatorKind::Unreachable,
1057            }),
1058            unwind.is_cleanup(),
1059        );
1060        let drop_block = self.elaborator.patch().new_block(drop_block);
1061
1062        let loop_block = BasicBlockData::new_stmts(
1063            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.assign(can_go,
                    Rvalue::BinaryOp(BinOp::Eq,
                        Box::new((copy(Place::from(cur)), copy(len.into())))))]))vec![self.assign(
1064                can_go,
1065                Rvalue::BinaryOp(BinOp::Eq, Box::new((copy(Place::from(cur)), copy(len.into())))),
1066            )],
1067            Some(Terminator {
1068                source_info: self.source_info,
1069                kind: TerminatorKind::if_(move_(can_go), succ, drop_block),
1070            }),
1071            unwind.is_cleanup(),
1072        );
1073        let loop_block = self.elaborator.patch().new_block(loop_block);
1074
1075        let place = tcx.mk_place_deref(ptr);
1076        if self.tcx().features().async_drop()
1077            && self.elaborator.body().coroutine.is_some()
1078            && self.elaborator.allow_async_drops()
1079            && !unwind.is_cleanup()
1080            && ety.needs_async_drop(self.tcx(), self.elaborator.typing_env())
1081        {
1082            self.build_async_drop(
1083                place,
1084                ety,
1085                Some(drop_block),
1086                loop_block,
1087                unwind,
1088                dropline,
1089                false,
1090            );
1091        } else {
1092            self.elaborator.patch().patch_terminator(
1093                drop_block,
1094                TerminatorKind::Drop {
1095                    place,
1096                    target: loop_block,
1097                    unwind: unwind.into_action(),
1098                    replace: false,
1099                    drop: None,
1100                    async_fut: None,
1101                },
1102            );
1103        }
1104        loop_block
1105    }
1106
1107    fn open_drop_for_array(
1108        &mut self,
1109        array_ty: Ty<'tcx>,
1110        ety: Ty<'tcx>,
1111        opt_size: Option<u64>,
1112    ) -> BasicBlock {
1113        {
    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/elaborate_drop.rs:1113",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(1113u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("open_drop_for_array({0:?}, {1:?}, {2:?})",
                                                    array_ty, ety, opt_size) as &dyn Value))])
            });
    } else { ; }
};debug!("open_drop_for_array({:?}, {:?}, {:?})", array_ty, ety, opt_size);
1114        let tcx = self.tcx();
1115
1116        if let Some(size) = opt_size {
1117            enum ProjectionKind<Path> {
1118                Drop(std::ops::Range<u64>),
1119                Keep(u64, Path),
1120            }
1121            // Previously, we'd make a projection for every element in the array and create a drop
1122            // ladder if any `array_subpath` was `Some`, i.e. moving out with an array pattern.
1123            // This caused huge memory usage when generating the drops for large arrays, so we instead
1124            // record the *subslices* which are dropped and the *indexes* which are kept
1125            let mut drop_ranges = ::alloc::vec::Vec::new()vec![];
1126            let mut dropping = true;
1127            let mut start = 0;
1128            for i in 0..size {
1129                let path = self.elaborator.array_subpath(self.path, i, size);
1130                if dropping && path.is_some() {
1131                    drop_ranges.push(ProjectionKind::Drop(start..i));
1132                    dropping = false;
1133                } else if !dropping && path.is_none() {
1134                    dropping = true;
1135                    start = i;
1136                }
1137                if let Some(path) = path {
1138                    drop_ranges.push(ProjectionKind::Keep(i, path));
1139                }
1140            }
1141            if !drop_ranges.is_empty() {
1142                if dropping {
1143                    drop_ranges.push(ProjectionKind::Drop(start..size));
1144                }
1145                let fields = drop_ranges
1146                    .iter()
1147                    .rev()
1148                    .map(|p| {
1149                        let (project, path) = match p {
1150                            ProjectionKind::Drop(r) => (
1151                                ProjectionElem::Subslice {
1152                                    from: r.start,
1153                                    to: r.end,
1154                                    from_end: false,
1155                                },
1156                                None,
1157                            ),
1158                            &ProjectionKind::Keep(offset, path) => (
1159                                ProjectionElem::ConstantIndex {
1160                                    offset,
1161                                    min_length: size,
1162                                    from_end: false,
1163                                },
1164                                Some(path),
1165                            ),
1166                        };
1167                        (tcx.mk_place_elem(self.place, project), path)
1168                    })
1169                    .collect::<Vec<_>>();
1170                let (succ, unwind, dropline) = self.drop_ladder_bottom();
1171                return self.drop_ladder(fields, succ, unwind, dropline).0;
1172            }
1173        }
1174
1175        let array_ptr_ty = Ty::new_mut_ptr(tcx, array_ty);
1176        let array_ptr = self.new_temp(array_ptr_ty);
1177
1178        let slice_ty = Ty::new_slice(tcx, ety);
1179        let slice_ptr_ty = Ty::new_mut_ptr(tcx, slice_ty);
1180        let slice_ptr = self.new_temp(slice_ptr_ty);
1181
1182        let mut delegate_block = BasicBlockData::new_stmts(
1183            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.assign(Place::from(array_ptr),
                    Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
                self.assign(Place::from(slice_ptr),
                    Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize,
                            CoercionSource::Implicit),
                        Operand::Move(Place::from(array_ptr)), slice_ptr_ty))]))vec![
1184                self.assign(Place::from(array_ptr), Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
1185                self.assign(
1186                    Place::from(slice_ptr),
1187                    Rvalue::Cast(
1188                        CastKind::PointerCoercion(
1189                            PointerCoercion::Unsize,
1190                            CoercionSource::Implicit,
1191                        ),
1192                        Operand::Move(Place::from(array_ptr)),
1193                        slice_ptr_ty,
1194                    ),
1195                ),
1196            ],
1197            None,
1198            self.unwind.is_cleanup(),
1199        );
1200
1201        let array_place = mem::replace(
1202            &mut self.place,
1203            Place::from(slice_ptr).project_deeper(&[PlaceElem::Deref], tcx),
1204        );
1205        let slice_block = self.drop_loop_trio_for_slice(ety);
1206        self.place = array_place;
1207
1208        delegate_block.terminator = Some(Terminator {
1209            source_info: self.source_info,
1210            kind: TerminatorKind::Goto { target: slice_block },
1211        });
1212        self.elaborator.patch().new_block(delegate_block)
1213    }
1214
1215    /// Creates a trio of drop-loops of `place`, which drops its contents, even
1216    /// in the case of 1 panic or in the case of coroutine drop
1217    fn drop_loop_trio_for_slice(&mut self, ety: Ty<'tcx>) -> BasicBlock {
1218        {
    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/elaborate_drop.rs:1218",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(1218u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_loop_trio_for_slice({0:?})",
                                                    ety) as &dyn Value))])
            });
    } else { ; }
};debug!("drop_loop_trio_for_slice({:?})", ety);
1219        let tcx = self.tcx();
1220        let len = self.new_temp(tcx.types.usize);
1221        let cur = self.new_temp(tcx.types.usize);
1222
1223        let unwind = self
1224            .unwind
1225            .map(|unwind| self.drop_loop(unwind, cur, len, ety, Unwind::InCleanup, None));
1226
1227        let dropline =
1228            self.dropline.map(|dropline| self.drop_loop(dropline, cur, len, ety, unwind, None));
1229
1230        let loop_block = self.drop_loop(self.succ, cur, len, ety, unwind, dropline);
1231
1232        let [PlaceElem::Deref] = self.place.projection.as_slice() else {
1233            ::rustc_middle::util::bug::span_bug_fmt(self.source_info.span,
    format_args!("Expected place for slice drop shim to be *_n, but it\'s {0:?}",
        self.place));span_bug!(
1234                self.source_info.span,
1235                "Expected place for slice drop shim to be *_n, but it's {:?}",
1236                self.place,
1237            );
1238        };
1239
1240        let zero = self.constant_usize(0);
1241        let block = BasicBlockData::new_stmts(
1242            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.assign(len.into(),
                    Rvalue::UnaryOp(UnOp::PtrMetadata,
                        Operand::Copy(Place::from(self.place.local)))),
                self.assign(cur.into(), Rvalue::Use(zero))]))vec![
1243                self.assign(
1244                    len.into(),
1245                    Rvalue::UnaryOp(
1246                        UnOp::PtrMetadata,
1247                        Operand::Copy(Place::from(self.place.local)),
1248                    ),
1249                ),
1250                self.assign(cur.into(), Rvalue::Use(zero)),
1251            ],
1252            Some(Terminator {
1253                source_info: self.source_info,
1254                kind: TerminatorKind::Goto { target: loop_block },
1255            }),
1256            unwind.is_cleanup(),
1257        );
1258
1259        let drop_block = self.elaborator.patch().new_block(block);
1260        // FIXME(#34708): handle partially-dropped array/slice elements.
1261        let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
1262        self.drop_flag_test_block(reset_block, self.succ, unwind)
1263    }
1264
1265    /// The slow-path - create an "open", elaborated drop for a type
1266    /// which is moved-out-of only partially, and patch `bb` to a jump
1267    /// to it. This must not be called on ADTs with a destructor,
1268    /// as these can't be moved-out-of, except for `Box<T>`, which is
1269    /// special-cased.
1270    ///
1271    /// This creates a "drop ladder" that drops the needed fields of the
1272    /// ADT, both in the success case or if one of the destructors fail.
1273    fn open_drop(&mut self) -> BasicBlock {
1274        let ty = self.place_ty(self.place);
1275        match ty.kind() {
1276            ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()),
1277            ty::CoroutineClosure(_, args) => {
1278                self.open_drop_for_tuple(args.as_coroutine_closure().upvar_tys())
1279            }
1280            // Note that `elaborate_drops` only drops the upvars of a coroutine,
1281            // and this is ok because `open_drop` here can only be reached
1282            // within that own coroutine's resume function.
1283            // This should only happen for the self argument on the resume function.
1284            // It effectively only contains upvars until the coroutine transformation runs.
1285            // See librustc_body/transform/coroutine.rs for more details.
1286            ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()),
1287            ty::Tuple(fields) => self.open_drop_for_tuple(fields),
1288            ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
1289            ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
1290            ty::Array(ety, size) => {
1291                let size = size.try_to_target_usize(self.tcx());
1292                self.open_drop_for_array(ty, *ety, size)
1293            }
1294            ty::Slice(ety) => self.drop_loop_trio_for_slice(*ety),
1295
1296            ty::UnsafeBinder(_) => {
1297                // Unsafe binders may elaborate drops if their inner type isn't copy.
1298                // This is enforced in typeck, so this should never happen.
1299                self.tcx().dcx().span_delayed_bug(
1300                    self.source_info.span,
1301                    "open drop for unsafe binder shouldn't be encountered",
1302                );
1303                self.elaborator.patch().new_block(BasicBlockData::new(
1304                    Some(Terminator {
1305                        source_info: self.source_info,
1306                        kind: TerminatorKind::Unreachable,
1307                    }),
1308                    self.unwind.is_cleanup(),
1309                ))
1310            }
1311
1312            _ => ::rustc_middle::util::bug::span_bug_fmt(self.source_info.span,
    format_args!("open drop from non-ADT `{0:?}`", ty))span_bug!(self.source_info.span, "open drop from non-ADT `{:?}`", ty),
1313        }
1314    }
1315
1316    fn complete_drop(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1317        {
    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/elaborate_drop.rs:1317",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(1317u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("complete_drop(succ={0:?}, unwind={1:?})",
                                                    succ, unwind) as &dyn Value))])
            });
    } else { ; }
};debug!("complete_drop(succ={:?}, unwind={:?})", succ, unwind);
1318
1319        let drop_block = self.drop_block(succ, unwind);
1320
1321        self.drop_flag_test_block(drop_block, succ, unwind)
1322    }
1323
1324    /// Creates a block that resets the drop flag. If `mode` is deep, all children drop flags will
1325    /// also be cleared.
1326    fn drop_flag_reset_block(
1327        &mut self,
1328        mode: DropFlagMode,
1329        succ: BasicBlock,
1330        unwind: Unwind,
1331    ) -> BasicBlock {
1332        {
    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/elaborate_drop.rs:1332",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(1332u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_flag_reset_block({0:?},{1:?})",
                                                    self, mode) as &dyn Value))])
            });
    } else { ; }
};debug!("drop_flag_reset_block({:?},{:?})", self, mode);
1333
1334        if unwind.is_cleanup() {
1335            // The drop flag isn't read again on the unwind path, so don't
1336            // bother setting it.
1337            return succ;
1338        }
1339        let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
1340        let block_start = Location { block, statement_index: 0 };
1341        self.elaborator.clear_drop_flag(block_start, self.path, mode);
1342        block
1343    }
1344
1345    fn elaborated_drop_block(&mut self) -> BasicBlock {
1346        {
    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/elaborate_drop.rs:1346",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(1346u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("elaborated_drop_block({0:?})",
                                                    self) as &dyn Value))])
            });
    } else { ; }
};debug!("elaborated_drop_block({:?})", self);
1347        let blk = self.drop_block_simple(self.succ, self.unwind);
1348        self.elaborate_drop(blk);
1349        blk
1350    }
1351
1352    fn drop_block_simple(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1353        let block = TerminatorKind::Drop {
1354            place: self.place,
1355            target,
1356            unwind: unwind.into_action(),
1357            replace: false,
1358            drop: self.dropline,
1359            async_fut: None,
1360        };
1361        self.new_block(unwind, block)
1362    }
1363
1364    fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1365        let drop_ty = self.place_ty(self.place);
1366        if self.tcx().features().async_drop()
1367            && self.elaborator.body().coroutine.is_some()
1368            && self.elaborator.allow_async_drops()
1369            && !unwind.is_cleanup()
1370            && drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
1371        {
1372            self.build_async_drop(
1373                self.place,
1374                drop_ty,
1375                None,
1376                self.succ,
1377                unwind,
1378                self.dropline,
1379                false,
1380            )
1381        } else {
1382            let block = TerminatorKind::Drop {
1383                place: self.place,
1384                target,
1385                unwind: unwind.into_action(),
1386                replace: false,
1387                drop: None,
1388                async_fut: None,
1389            };
1390            self.new_block(unwind, block)
1391        }
1392    }
1393
1394    fn goto_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1395        let block = TerminatorKind::Goto { target };
1396        self.new_block(unwind, block)
1397    }
1398
1399    /// Returns the block to jump to in order to test the drop flag and execute the drop.
1400    ///
1401    /// Depending on the required `DropStyle`, this might be a generated block with an `if`
1402    /// terminator (for dynamic/open drops), or it might be `on_set` or `on_unset` itself, in case
1403    /// the drop can be statically determined.
1404    fn drop_flag_test_block(
1405        &mut self,
1406        on_set: BasicBlock,
1407        on_unset: BasicBlock,
1408        unwind: Unwind,
1409    ) -> BasicBlock {
1410        let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
1411        {
    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/elaborate_drop.rs:1411",
                        "rustc_mir_transform::elaborate_drop",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
                        ::tracing_core::__macro_support::Option::Some(1411u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                        ::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!("drop_flag_test_block({0:?},{1:?},{2:?},{3:?}) - {4:?}",
                                                    self, on_set, on_unset, unwind, style) as &dyn Value))])
            });
    } else { ; }
};debug!(
1412            "drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
1413            self, on_set, on_unset, unwind, style
1414        );
1415
1416        match style {
1417            DropStyle::Dead => on_unset,
1418            DropStyle::Static => on_set,
1419            DropStyle::Conditional | DropStyle::Open => {
1420                let flag = self.elaborator.get_drop_flag(self.path).unwrap();
1421                let term = TerminatorKind::if_(flag, on_set, on_unset);
1422                self.new_block(unwind, term)
1423            }
1424        }
1425    }
1426
1427    fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
1428        self.elaborator.patch().new_block(BasicBlockData::new(
1429            Some(Terminator { source_info: self.source_info, kind: k }),
1430            unwind.is_cleanup(),
1431        ))
1432    }
1433
1434    fn new_block_with_statements(
1435        &mut self,
1436        unwind: Unwind,
1437        statements: Vec<Statement<'tcx>>,
1438        k: TerminatorKind<'tcx>,
1439    ) -> BasicBlock {
1440        self.elaborator.patch().new_block(BasicBlockData::new_stmts(
1441            statements,
1442            Some(Terminator { source_info: self.source_info, kind: k }),
1443            unwind.is_cleanup(),
1444        ))
1445    }
1446
1447    fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
1448        self.elaborator.patch().new_temp(ty, self.source_info.span)
1449    }
1450
1451    fn constant_usize(&self, val: u16) -> Operand<'tcx> {
1452        Operand::Constant(Box::new(ConstOperand {
1453            span: self.source_info.span,
1454            user_ty: None,
1455            const_: Const::from_usize(self.tcx(), val.into()),
1456        }))
1457    }
1458
1459    fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
1460        Statement::new(self.source_info, StatementKind::Assign(Box::new((lhs, rhs))))
1461    }
1462}