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