Skip to main content

rustc_mir_transform/
elaborate_drop.rs

1use std::{fmt, iter, mem};
2
3use itertools::Itertools;
4use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
5use rustc_data_structures::thin_vec::ThinVec;
6use rustc_hir::lang_items::LangItem;
7use rustc_hir::{CoroutineDesugaring, CoroutineKind};
8use rustc_index::Idx;
9use rustc_middle::mir::*;
10use rustc_middle::ty::adjustment::PointerCoercion;
11use rustc_middle::ty::util::{Discr, IntTypeExt};
12use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt};
13use rustc_middle::{bug, span_bug};
14use rustc_span::{DUMMY_SP, dummy_spanned};
15use tracing::{debug, instrument};
16
17use crate::coroutine::CTX_ARG;
18use crate::patch::MirPatch;
19
20/// Describes how/if a value should be dropped.
21#[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)]
22pub(crate) enum DropStyle {
23    /// The value is already dead at the drop location, no drop will be executed.
24    Dead,
25
26    /// The value is known to always be initialized at the drop location, drop will always be
27    /// executed.
28    Static,
29
30    /// Whether the value needs to be dropped depends on its drop flag.
31    Conditional,
32
33    /// An "open" drop is one where only the fields of a value are dropped.
34    ///
35    /// For example, this happens when moving out of a struct field: The rest of the struct will be
36    /// dropped in such an "open" drop. It is also used to generate drop glue for the individual
37    /// components of a value, for example for dropping array elements.
38    Open,
39}
40
41/// Which drop flags to affect/check with an operation.
42#[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)]
43pub(crate) enum DropFlagMode {
44    /// Only affect the top-level drop flag, not that of any contained fields.
45    Shallow,
46    /// Affect all nested drop flags in addition to the top-level one.
47    Deep,
48}
49
50/// Describes if unwinding is necessary and where to unwind to if a panic occurs.
51#[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)]
52pub(crate) enum Unwind {
53    /// Unwind to this block.
54    To(BasicBlock),
55    /// Already in an unwind path, any panic will cause an abort.
56    InCleanup,
57}
58
59impl Unwind {
60    fn is_cleanup(self) -> bool {
61        match self {
62            Unwind::To(..) => false,
63            Unwind::InCleanup => true,
64        }
65    }
66
67    fn into_action(self) -> UnwindAction {
68        match self {
69            Unwind::To(bb) => UnwindAction::Cleanup(bb),
70            Unwind::InCleanup => UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
71        }
72    }
73
74    fn map<F>(self, f: F) -> Self
75    where
76        F: FnOnce(BasicBlock) -> BasicBlock,
77    {
78        match self {
79            Unwind::To(bb) => Unwind::To(f(bb)),
80            Unwind::InCleanup => Unwind::InCleanup,
81        }
82    }
83}
84
85pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
86    /// The type representing paths that can be moved out of.
87    ///
88    /// Users can move out of individual fields of a struct, such as `a.b.c`. This type is used to
89    /// represent such move paths. Sometimes tracking individual move paths is not necessary, in
90    /// which case this may be set to (for example) `()`.
91    type Path: Copy + fmt::Debug;
92
93    // Accessors
94
95    fn patch_ref(&self) -> &MirPatch<'tcx>;
96    fn patch(&mut self) -> &mut MirPatch<'tcx>;
97    fn body(&self) -> &'a Body<'tcx>;
98    fn tcx(&self) -> TyCtxt<'tcx>;
99    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
100    fn allow_async_drops(&self) -> bool;
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    /// Async-drop `place: drop_ty`.
205    ///
206    /// Conceptually, we want to run `async_drop_in_place(&mut obj).await`.
207    ///
208    /// Await syntax does not exist in MIR, so we need to manually expand it into a poll-yield
209    /// loop, essentially:
210    /// ```mir
211    ///   let fut = async_drop_in_place(&mut obj);
212    ///   loop {
213    ///     let pin_fut = Pin::new_unchecked(&mut fut);
214    ///     match Future::poll(pin_fut, CTX_ARG) {
215    ///       Poll::Ready => break,
216    ///       Poll::Pending(..) => CTX_ARG = yield (),
217    ///     }
218    ///   }
219    ///   // continue to `succ`
220    /// ```
221    ///
222    /// We also need to ensure that async drop also happens on the coroutine drop path, ie. when
223    /// `yield` branches along its `drop` target. This requires a second loop, this time jumping to
224    /// `dropline`.
225    ///
226    /// Arguments:
227    ///   `call_destructor_only`: call only `AsyncDrop::drop`, not full `async_drop_in_place` glue
228    x;#[instrument(level = "debug", skip(self), ret)]
229    fn build_async_drop(
230        &mut self,
231        place: Place<'tcx>,
232        drop_ty: Ty<'tcx>,
233        succ: BasicBlock,
234        unwind: Unwind,
235        dropline: Option<BasicBlock>,
236        call_destructor_only: bool,
237    ) -> BasicBlock {
238        let tcx = self.tcx();
239        let span = self.source_info.span;
240        let obj_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, drop_ty);
241
242        let async_drop_fn_def_id = if call_destructor_only {
243            // Resolving obj.<AsyncDrop::drop>()
244            let async_drop_trait = tcx.require_lang_item(LangItem::AsyncDrop, span);
245            tcx.associated_item_def_ids(async_drop_trait)[0]
246        } else {
247            // Resolving async_drop_in_place<T> function for drop_ty
248            tcx.require_lang_item(LangItem::AsyncDropInPlace, span)
249        };
250
251        let fut_ty = tcx
252            .instantiate_bound_regions_with_erased(
253                // FIXME(156581): actually instantiate the binder correctly (turbofishing/fndef changes)
254                Ty::new_fn_def(tcx, async_drop_fn_def_id, ty::Binder::dummy([drop_ty])).fn_sig(tcx),
255            )
256            .output();
257        let fut = self.new_temp(fut_ty);
258
259        // Create an intermediate block that does StorageDead(fut) then jumps to succ.
260        // This is necessary because we do not want to modify statements
261        // in existing blocks, in case those are used somewhere else in MIR.
262        let succ_with_dead = self.new_block_with_statements(
263            unwind,
264            vec![self.storage_dead(fut)],
265            TerminatorKind::Goto { target: succ },
266        );
267        let dropline_with_dead = dropline.map(|target| {
268            self.new_block_with_statements(
269                unwind,
270                vec![self.storage_dead(fut)],
271                TerminatorKind::Goto { target },
272            )
273        });
274        let unwind_with_dead = unwind.map(|target| {
275            self.new_block_with_statements(
276                Unwind::InCleanup,
277                vec![self.storage_dead(fut)],
278                TerminatorKind::Goto { target },
279            )
280        });
281
282        // The yielded value depends on the kind of coroutine, to match what AST lowering does.
283        let coroutine_kind = self.elaborator.body().coroutine_kind().unwrap();
284        let yield_value = match coroutine_kind {
285            // For async gen, we need `yield Poll<OptRet>::Pending`.
286            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
287                let full_yield_ty = self.elaborator.body().yield_ty().unwrap();
288                let ty::Adt(_poll_adt, args) = *full_yield_ty.kind() else { bug!() };
289                let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
290                let yield_ty = args.type_at(0);
291                Operand::unevaluated_constant(
292                    tcx,
293                    tcx.require_lang_item(LangItem::AsyncGenPending, span),
294                    tcx.mk_args(&[yield_ty.into()]),
295                    span,
296                )
297            }
298            // For regular async fn, we need `yield ()`.
299            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
300                Operand::zero_sized_constant(tcx.types.unit, span)
301            }
302            // `is_async_drop` should have checked that.
303            _ => panic!("unexpected coroutine for async drop {coroutine_kind:?}"),
304        };
305
306        // The branching here is tricky and deserves some explanation.
307        //
308        // If we are in the drop code path, ie. we are currently dropping the coroutine.
309        // The state machine follows the `drop` branch in the `yield` terminator.
310        // To repeatedly poll the future, the `drop` branch must loop.
311        // Meanwhile, the `resume` branch corresponds to anomalous execution,
312        // trying to resume the coroutine while it is being dropped. So that branch panics
313        // (`panic_bb`).
314        let panic_bb = self.build_resumed_after_drop_abort_block(unwind_with_dead, coroutine_kind);
315        let (drop_pin_bb, drop_resume_bb, drop_drop_bb) = self.build_pin_poll_yield_loop(
316            CTX_ARG.into(),
317            fut.into(),
318            yield_value.clone(),
319            // If `dropline_with_dead` is set, it points to the continuation of the drop execution.
320            // Otherwise, we are already dropping the coroutine, and `succ_with_dead` does.
321            dropline_with_dead.unwrap_or(succ_with_dead),
322            unwind_with_dead,
323        );
324        self.elaborator
325            .patch()
326            .patch_terminator(drop_resume_bb, TerminatorKind::Goto { target: panic_bb });
327        self.elaborator
328            .patch()
329            .patch_terminator(drop_drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
330
331        // If we are in the regular code path, `dropline_with_dead` is `Some`.
332        //
333        // In that case, the logic is reversed. Normal execution branches on `resume` from the
334        // `yield` terminator. To repeatedly poll the future, that `resume` branch must loop.
335        // When the future is dropped, the `yield` terminator branches to `drop`, which follows to
336        // the previous loop `drop_pin_bb`.
337        let succ_yield_loop = if dropline_with_dead.is_some() {
338            let (pin_bb, resume_bb, drop_bb) = self.build_pin_poll_yield_loop(
339                CTX_ARG.into(),
340                fut.into(),
341                yield_value,
342                // `dropline_with_dead` is `Some`, so the previous loop point to it.
343                succ_with_dead,
344                unwind_with_dead,
345            );
346            self.elaborator
347                .patch()
348                .patch_terminator(resume_bb, TerminatorKind::Goto { target: pin_bb });
349            self.elaborator
350                .patch()
351                .patch_terminator(drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
352            pin_bb
353        } else {
354            // We were already in the drop line, so return the loop we created for it.
355            drop_pin_bb
356        };
357
358        // #2:call_drop_bb >>>
359        //    call AsyncDrop::drop(pin_obj)
360        // OR call async_drop_in_place(pin_obj.pointer)
361        let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
362        let pin_obj_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[obj_ref_ty.into()]));
363        // Where we store the result of Pin<&drop_ty>::new_unchecked(&mut place).
364        let pin_obj_local = self.new_temp(pin_obj_ty);
365        let drop_arg = if call_destructor_only {
366            // `AsyncDrop::drop` takes `self: Pin<&mut Self>`.
367            Operand::Move(pin_obj_local.into())
368        } else {
369            // `async_drop_in_place` takes `obj: &mut T`.
370            Operand::Copy(tcx.mk_place_field(pin_obj_local.into(), FieldIdx::ZERO, obj_ref_ty))
371        };
372        let call_drop_bb = self.new_block_with_statements(
373            unwind_with_dead,
374            vec![self.storage_live(fut)],
375            TerminatorKind::Call {
376                // FIXME(156581): actually instantiate the binder correctly (turbofishing/fndef changes)
377                func: Operand::function_handle(
378                    tcx,
379                    async_drop_fn_def_id,
380                    ty::Binder::dummy([drop_ty.into()]),
381                    span,
382                ),
383                args: [dummy_spanned(drop_arg)].into(),
384                destination: fut.into(),
385                target: Some(succ_yield_loop),
386                unwind: unwind_with_dead.into_action(),
387                call_source: CallSource::Misc,
388                fn_span: self.source_info.span,
389            },
390        );
391
392        // #1:pin_obj_bb >>> call Pin<ObjTy>::new_unchecked(&mut obj)
393        let obj_ref_place = Place::from(self.new_temp(obj_ref_ty));
394        let pin_obj_new_unchecked_fn = tcx.require_lang_item(LangItem::PinNewUnchecked, span);
395        let assign_obj_ref_place = self.assign(
396            obj_ref_place,
397            Rvalue::Ref(
398                tcx.lifetimes.re_erased,
399                BorrowKind::Mut { kind: MutBorrowKind::Default },
400                place,
401            ),
402        );
403        self.new_block_with_statements(
404            unwind,
405            vec![assign_obj_ref_place],
406            TerminatorKind::Call {
407                func: Operand::function_handle(
408                    tcx,
409                    pin_obj_new_unchecked_fn,
410                    // FIXME(156581): actually instantiate the binder correctly (turbofishing/fndef changes)
411                    ty::Binder::dummy([obj_ref_ty.into()]),
412                    span,
413                ),
414                args: [dummy_spanned(Operand::Move(obj_ref_place))].into(),
415                destination: pin_obj_local.into(),
416                target: Some(call_drop_bb),
417                unwind: unwind.into_action(),
418                call_source: CallSource::Misc,
419                fn_span: span,
420            },
421        )
422    }
423
424    fn build_resumed_after_drop_abort_block(
425        &mut self,
426        unwind: Unwind,
427        coroutine_kind: CoroutineKind,
428    ) -> BasicBlock {
429        let tcx = self.tcx();
430        let panic_bb = self.new_block(unwind, TerminatorKind::Unreachable);
431        let msg = AssertMessage::ResumedAfterDrop(coroutine_kind);
432        let false_op = Operand::Constant(Box::new(ConstOperand {
433            span: self.source_info.span,
434            user_ty: None,
435            const_: Const::from_bool(tcx, false),
436        }));
437        self.elaborator.patch().patch_terminator(
438            panic_bb,
439            TerminatorKind::Assert {
440                cond: false_op,
441                expected: true,
442                msg: Box::new(msg),
443                target: panic_bb,
444                unwind: unwind.into_action(),
445            },
446        );
447        panic_bb
448    }
449
450    /// Build a small MIR loop that pins and polls a future, yielding when
451    /// the future returns `Poll::Pending` and continuing to `ready_target`
452    /// when it returns `Poll::Ready`.
453    ///
454    /// Pseudo-code:
455    /// ```mir
456    /// pin_bb:
457    ///   let pin_fut = Pin::new_unchecked(&mut fut_place);
458    ///   match Future::poll(pin_fut, CTX_ARG) {
459    ///     Poll::Ready => goto succ,
460    ///     Poll::Pending(..) => CTX_ARG = yield () [resume: resume_bb, drop: drop_bb],
461    ///   }
462    /// ```
463    ///
464    ///  Returns: the tuple `(pin_bb, resume_bb, drop_bb)`.
465    x;#[instrument(level = "trace", skip(self), ret)]
466    fn build_pin_poll_yield_loop(
467        &mut self,
468        resume_place: Place<'tcx>,
469        fut_place: Place<'tcx>,
470        yield_value: Operand<'tcx>,
471        succ: BasicBlock,
472        unwind: Unwind,
473    ) -> (BasicBlock, BasicBlock, BasicBlock) {
474        let tcx = self.tcx();
475        let source_info = self.source_info;
476
477        let resume_arg_ty = resume_place.ty(self.elaborator.body(), tcx).ty;
478        let context_ref_ty = Ty::new_task_context(tcx);
479
480        let poll_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Poll, source_info.span));
481        let poll_enum = Ty::new_adt(tcx, poll_adt_def, tcx.mk_args(&[tcx.types.unit.into()]));
482
483        let fut_ty = self.elaborator.patch_ref().local_ty(fut_place.local);
484        let fut_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, fut_ty);
485
486        let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, source_info.span));
487        let fut_pin_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[fut_ref_ty.into()]));
488
489        // Coroutine `transform_async_context` assumes that the local `resume_arg` to a yield
490        // is not used once, so create a special temp for it.
491        let yield_resume_local = self.new_temp(resume_arg_ty);
492        let resume_bb = self.new_block_with_statements(
493            unwind,
494            vec![
495                self.assign(
496                    resume_place,
497                    Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
498                ),
499                self.storage_dead(yield_resume_local),
500            ],
501            // This will be transformed by the caller.
502            TerminatorKind::Unreachable,
503        );
504        let dropline_bb = self.new_block_with_statements(
505            unwind,
506            vec![
507                self.assign(
508                    resume_place,
509                    Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
510                ),
511                self.storage_dead(yield_resume_local),
512            ],
513            // This will be transformed by the caller.
514            TerminatorKind::Unreachable,
515        );
516        let yield_bb = self.new_block_with_statements(
517            unwind,
518            vec![self.storage_live(yield_resume_local)],
519            TerminatorKind::Yield {
520                value: yield_value,
521                resume: resume_bb,
522                resume_arg: yield_resume_local.into(),
523                drop: Some(dropline_bb),
524            },
525        );
526
527        let poll_unit_local = self.new_temp(poll_enum);
528        let switch_bb = {
529            let poll_ready_variant =
530                tcx.require_lang_item(LangItem::PollReady, self.source_info.span);
531            let poll_ready_variant_idx = poll_adt_def.variant_index_with_id(poll_ready_variant);
532            let poll_pending_variant =
533                tcx.require_lang_item(LangItem::PollPending, self.source_info.span);
534            let poll_pending_variant_idx = poll_adt_def.variant_index_with_id(poll_pending_variant);
535
536            let Discr { val: poll_ready_discr, ty: poll_discr_ty } =
537                poll_enum.discriminant_for_variant(tcx, poll_ready_variant_idx).unwrap();
538            let Discr { val: poll_pending_discr, ty: _ } =
539                poll_enum.discriminant_for_variant(tcx, poll_pending_variant_idx).unwrap();
540
541            let poll_discr_local = self.new_temp(poll_discr_ty);
542            let otherwise_bb = self.elaborator.patch().unreachable_no_cleanup_block();
543            self.new_block_with_statements(
544                unwind,
545                vec![
546                    self.assign(
547                        poll_discr_local.into(),
548                        Rvalue::Discriminant(poll_unit_local.into()),
549                    ),
550                ],
551                TerminatorKind::SwitchInt {
552                    discr: Operand::Move(poll_discr_local.into()),
553                    targets: SwitchTargets::new(
554                        [
555                            // on `Ready`, exit the loop, jump to `succ`
556                            (poll_ready_discr, succ),
557                            // on `Pending`, yield and resume back into the loop
558                            (poll_pending_discr, yield_bb),
559                        ]
560                        .into_iter(),
561                        // otherwise: unreachable
562                        otherwise_bb,
563                    ),
564                },
565            )
566        };
567
568        let fut_pin_local = self.new_temp(fut_pin_ty);
569        let context_ref_local = self.new_temp(context_ref_ty);
570
571        let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, source_info.span);
572        let poll_bb = self.new_block_with_statements(
573            unwind,
574            Vec::new(),
575            TerminatorKind::Call {
576                // FIXME(156581): actually instantiate the binder correctly (turbofishing/fndef changes)
577                func: Operand::function_handle(
578                    tcx,
579                    poll_fn,
580                    ty::Binder::dummy([fut_ty.into()]),
581                    source_info.span,
582                ),
583                args: [
584                    dummy_spanned(Operand::Move(fut_pin_local.into())),
585                    dummy_spanned(Operand::Move(context_ref_local.into())),
586                ]
587                .into(),
588                destination: poll_unit_local.into(),
589                target: Some(switch_bb),
590                unwind: unwind.into_action(),
591                call_source: CallSource::Misc,
592                fn_span: source_info.span,
593            },
594        );
595
596        let get_context_fn = tcx.require_lang_item(LangItem::GetContext, source_info.span);
597        let get_context_bb = {
598            // Coroutine `transform_async_context` assumes that the local argument to `GetContext`
599            // is not used once, so create a special temp for it.
600            let entry_resume_local = self.new_temp(resume_arg_ty);
601            self.new_block_with_statements(
602                unwind,
603                vec![self.assign(
604                    entry_resume_local.into(),
605                    Rvalue::Use(Operand::Move(resume_place), WithRetag::Yes),
606                )],
607                TerminatorKind::Call {
608                    func: Operand::function_handle(
609                        tcx,
610                        get_context_fn,
611                        // FIXME(156581): actually instantiate the binder correctly (turbofishing/fndef changes)
612                        ty::Binder::dummy([
613                            tcx.lifetimes.re_erased.into(),
614                            tcx.lifetimes.re_erased.into(),
615                        ]),
616                        source_info.span,
617                    ),
618                    args: [dummy_spanned(Operand::Move(entry_resume_local.into()))].into(),
619                    destination: context_ref_local.into(),
620                    target: Some(poll_bb),
621                    unwind: unwind.into_action(),
622                    call_source: CallSource::Misc,
623                    fn_span: source_info.span,
624                },
625            )
626        };
627
628        let fut_ref_local = self.new_temp(fut_ref_ty);
629        let fut_pin_new_unchecked_fn =
630            tcx.require_lang_item(LangItem::PinNewUnchecked, source_info.span);
631        let pin_bb = self.new_block_with_statements(
632            unwind,
633            vec![self.assign(
634                fut_ref_local.into(),
635                Rvalue::Ref(
636                    tcx.lifetimes.re_erased,
637                    BorrowKind::Mut { kind: MutBorrowKind::Default },
638                    fut_place,
639                ),
640            )],
641            TerminatorKind::Call {
642                func: Operand::function_handle(
643                    tcx,
644                    fut_pin_new_unchecked_fn,
645                    ty::Binder::dummy([fut_ref_ty.into()]),
646                    source_info.span,
647                ),
648                args: [dummy_spanned(Operand::Move(fut_ref_local.into()))].into(),
649                destination: fut_pin_local.into(),
650                target: Some(get_context_bb),
651                unwind: unwind.into_action(),
652                call_source: CallSource::Misc,
653                fn_span: source_info.span,
654            },
655        );
656
657        (pin_bb, resume_bb, dropline_bb)
658    }
659
660    fn build_drop(&mut self, bb: BasicBlock) {
661        let drop_ty = self.place_ty(self.place);
662        if !self.elaborator.patch_ref().block(self.elaborator.body(), bb).is_cleanup
663            && self.check_if_can_async_drop(drop_ty, false)
664        {
665            let async_drop_bb = self.build_async_drop(
666                self.place,
667                drop_ty,
668                self.succ,
669                self.unwind,
670                self.dropline,
671                false,
672            );
673            self.elaborator
674                .patch()
675                .patch_terminator(bb, TerminatorKind::Goto { target: async_drop_bb });
676        } else {
677            self.elaborator.patch().patch_terminator(
678                bb,
679                TerminatorKind::Drop {
680                    place: self.place,
681                    target: self.succ,
682                    unwind: self.unwind.into_action(),
683                    replace: false,
684                    drop: None,
685                },
686            );
687        }
688    }
689
690    /// Function to check if we can generate an async drop here
691    fn check_if_can_async_drop(&mut self, drop_ty: Ty<'tcx>, call_destructor_only: bool) -> bool {
692        if !self.elaborator.allow_async_drops()
693            || !self
694                .elaborator
695                .body()
696                .coroutine
697                .as_ref()
698                .is_some_and(|ck| ck.coroutine_kind.is_async_desugaring())
699        {
700            return false;
701        }
702
703        if drop_ty == self.place_ty(Local::arg(0).into()) {
704            return false;
705        }
706
707        let is_async_drop_feature_enabled = if self.tcx().features().async_drop() {
708            true
709        } else {
710            // Check if the type needing async drop comes from a dependency crate.
711            if let ty::Adt(adt_def, _) = drop_ty.kind() {
712                !adt_def.did().is_local() && adt_def.async_destructor(self.tcx()).is_some()
713            } else {
714                false
715            }
716        };
717
718        // Short-circuit before calling needs_async_drop/is_async_drop, as those
719        // require the `async_drop` lang item to exist (which may not be present
720        // in minimal/custom core environments like cranelift's mini_core).
721        if !is_async_drop_feature_enabled {
722            return false;
723        }
724
725        let needs_async_drop = if call_destructor_only {
726            drop_ty.is_async_drop(self.tcx(), self.elaborator.typing_env())
727        } else {
728            drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
729        };
730
731        // Async drop in libstd/libcore would become insta-stable — catch that mistake.
732        if needs_async_drop && self.tcx().features().staged_api() {
733            ::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!(
734                self.source_info.span,
735                "don't use async drop in libstd, it becomes insta-stable"
736            );
737        }
738
739        needs_async_drop
740    }
741
742    /// This elaborates a single drop instruction, located at `bb`, and
743    /// patches over it.
744    ///
745    /// The elaborated drop checks the drop flags to only drop what
746    /// is initialized.
747    ///
748    /// In addition, the relevant drop flags also need to be cleared
749    /// to avoid double-drops. However, in the middle of a complex
750    /// drop, one must avoid clearing some of the flags before they
751    /// are read, as that would cause a memory leak.
752    ///
753    /// In particular, when dropping an ADT, multiple fields may be
754    /// joined together under the `rest` subpath. They are all controlled
755    /// by the primary drop flag, but only the last rest-field dropped
756    /// should clear it (and it must also not clear anything else).
757    //
758    // FIXME: I think we should just control the flags externally,
759    // and then we do not need this machinery.
760    #[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(760u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bb")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bb");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bb)
                                                            as &dyn ::tracing::field::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")]
761    fn elaborate_drop(&mut self, bb: BasicBlock) {
762        match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
763            DropStyle::Dead => {
764                self.elaborator
765                    .patch()
766                    .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
767            }
768            DropStyle::Static => {
769                self.build_drop(bb);
770            }
771            DropStyle::Conditional => {
772                let drop_bb = self.complete_drop(self.succ, self.unwind);
773                self.elaborator
774                    .patch()
775                    .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
776            }
777            DropStyle::Open => {
778                let drop_bb = self.open_drop();
779                self.elaborator
780                    .patch()
781                    .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
782            }
783        }
784    }
785
786    /// Returns the place and move path for each field of `variant`,
787    /// (the move path is `None` if the field is a rest field).
788    fn move_paths_for_fields(
789        &self,
790        base_place: Place<'tcx>,
791        variant_path: D::Path,
792        variant: &'tcx ty::VariantDef,
793        args: GenericArgsRef<'tcx>,
794    ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
795        variant
796            .fields
797            .iter_enumerated()
798            .map(|(field_idx, field)| {
799                let subpath = self.elaborator.field_subpath(variant_path, field_idx);
800                let tcx = self.tcx();
801
802                match self.elaborator.typing_env().typing_mode().assert_not_erased() {
803                    ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {}
804                    ty::TypingMode::Coherence
805                    | ty::TypingMode::Typeck { .. }
806                    | ty::TypingMode::PostTypeckUntilBorrowck { .. }
807                    | ty::TypingMode::PostBorrowck { .. } => {
808                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
809                    }
810                }
811
812                let field_ty = field.ty(tcx, args);
813                // We silently leave an unnormalized type here to support polymorphic drop
814                // elaboration for users of rustc internal APIs
815                let field_ty = tcx
816                    .try_normalize_erasing_regions(self.elaborator.typing_env(), field_ty)
817                    .unwrap_or(field_ty.skip_norm_wip());
818
819                (tcx.mk_place_field(base_place, field_idx, field_ty), subpath)
820            })
821            .filter(|path| self.should_retain_for_ladder(path))
822            .collect()
823    }
824
825    x;#[instrument(level = "debug", skip(self), ret)]
826    fn drop_subpath(
827        &mut self,
828        place: Place<'tcx>,
829        path: Option<D::Path>,
830        succ: BasicBlock,
831        unwind: Unwind,
832        dropline: Option<BasicBlock>,
833    ) -> BasicBlock {
834        if let Some(path) = path {
835            DropCtxt {
836                elaborator: self.elaborator,
837                source_info: self.source_info,
838                path,
839                place,
840                succ,
841                unwind,
842                dropline,
843            }
844            .elaborated_drop_block()
845        } else {
846            DropCtxt {
847                elaborator: self.elaborator,
848                source_info: self.source_info,
849                place,
850                succ,
851                unwind,
852                dropline,
853                // Using `self.path` here to condition the drop on our own drop flag.
854                path: self.path,
855            }
856            .complete_drop(succ, unwind)
857        }
858    }
859
860    /// Creates one-half of the drop ladder for a list of fields, and return
861    /// the list of steps in it in reverse order, with the first step
862    /// dropping 0 fields and so on.
863    ///
864    /// `unwind_ladder` is such a list of steps in reverse order,
865    /// which is called if the matching step of the drop glue panics.
866    ///
867    /// `dropline_ladder` is a similar list of steps in reverse order,
868    /// which is called if the matching step of the drop glue will contain async drop
869    /// (expanded later to Yield) and the containing coroutine will be dropped at this point.
870    x;#[instrument(level = "debug", skip(self), ret)]
871    fn drop_halfladder(
872        &mut self,
873        unwind_ladder: &[Unwind],
874        dropline_ladder: &[Option<BasicBlock>],
875        mut succ: BasicBlock,
876        fields: &[(Place<'tcx>, Option<D::Path>)],
877    ) -> Vec<BasicBlock> {
878        iter::once(succ)
879            .chain(itertools::izip!(fields.iter().rev(), unwind_ladder, dropline_ladder).map(
880                |(&(place, path), &unwind_succ, &dropline_to)| {
881                    succ = self.drop_subpath(place, path, succ, unwind_succ, dropline_to);
882                    succ
883                },
884            ))
885            .collect()
886    }
887
888    fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind, Option<BasicBlock>) {
889        // Clear the "master" drop flag at the end. This is needed
890        // because the "master" drop protects the ADT's discriminant,
891        // which is invalidated after the ADT is dropped.
892        (
893            self.drop_flag_reset_block(DropFlagMode::Shallow, self.succ, self.unwind),
894            self.unwind,
895            self.dropline,
896        )
897    }
898
899    /// Whether this drop is useful. This is purely an optimization to avoid generating useless blocks.
900    fn should_retain_for_ladder(&self, (place, subpath): &(Place<'tcx>, Option<D::Path>)) -> bool {
901        if !self.place_ty(*place).needs_drop(self.tcx(), self.elaborator.typing_env()) {
902            return false;
903        }
904        if let Some(subpath) = subpath
905            && let DropStyle::Dead = self.elaborator.drop_style(*subpath, DropFlagMode::Deep)
906        {
907            return false;
908        }
909        true
910    }
911
912    /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
913    ///
914    /// For example, with 3 fields, the drop ladder is
915    ///
916    /// ```text
917    /// .d0:
918    ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
919    /// .d1:
920    ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
921    /// .d2:
922    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
923    /// .c1:
924    ///     ELAB(drop location.1 [target=.c2])
925    /// .c2:
926    ///     ELAB(drop location.2 [target=`self.unwind`])
927    /// ```
928    ///
929    /// For possible-async drops in coroutines we also need dropline ladder
930    /// ```text
931    /// .d0 (mainline):
932    ///     ELAB(drop location.0 [target=.d1, unwind=.c1, drop=.e1])
933    /// .d1 (mainline):
934    ///     ELAB(drop location.1 [target=.d2, unwind=.c2, drop=.e2])
935    /// .d2 (mainline):
936    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`, drop=`self.drop`])
937    /// .c1 (unwind):
938    ///     ELAB(drop location.1 [target=.c2])
939    /// .c2 (unwind):
940    ///     ELAB(drop location.2 [target=`self.unwind`])
941    /// .e1 (dropline):
942    ///     ELAB(drop location.1 [target=.e2, unwind=.c2])
943    /// .e2 (dropline):
944    ///     ELAB(drop location.2 [target=`self.drop`, unwind=`self.unwind`])
945    /// ```
946    ///
947    /// NOTE: this does not clear the master drop flag, so you need
948    /// to point succ/unwind on a `drop_ladder_bottom`.
949    x;#[instrument(level = "debug", skip(self), ret)]
950    fn drop_ladder(
951        &mut self,
952        mut fields: Vec<(Place<'tcx>, Option<D::Path>)>,
953        succ: BasicBlock,
954        unwind: Unwind,
955        dropline: Option<BasicBlock>,
956    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
957        assert!(
958            if unwind.is_cleanup() { dropline.is_none() } else { true },
959            "Dropline is set for cleanup drop ladder"
960        );
961
962        fields.retain(|path| self.should_retain_for_ladder(path));
963
964        debug!("drop_ladder - fields needing drop: {:?}", fields);
965
966        let dropline_ladder: Vec<Option<BasicBlock>> = vec![None; fields.len() + 1];
967        let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
968        let unwind_ladder: Vec<_> = if let Unwind::To(succ) = unwind {
969            let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
970            halfladder.into_iter().map(Unwind::To).collect()
971        } else {
972            unwind_ladder
973        };
974        let dropline_ladder: Vec<_> = if let Some(succ) = dropline {
975            let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
976            halfladder.into_iter().map(Some).collect()
977        } else {
978            dropline_ladder
979        };
980
981        let normal_ladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
982
983        (
984            *normal_ladder.last().unwrap(),
985            *unwind_ladder.last().unwrap(),
986            *dropline_ladder.last().unwrap(),
987        )
988    }
989
990    x;#[instrument(level = "debug", skip(self), ret)]
991    fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
992        let fields = tys
993            .iter()
994            .enumerate()
995            .map(|(i, &ty)| {
996                (
997                    self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
998                    self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
999                )
1000            })
1001            .collect();
1002
1003        let (succ, unwind, dropline) = self.drop_ladder_bottom();
1004        self.drop_ladder(fields, succ, unwind, dropline).0
1005    }
1006
1007    /// Drops the T contained in a `Box<T>` if it has not been moved out of
1008    x;#[instrument(level = "debug", ret)]
1009    fn open_drop_for_box_contents(
1010        &mut self,
1011        adt: ty::AdtDef<'tcx>,
1012        args: GenericArgsRef<'tcx>,
1013        succ: BasicBlock,
1014        unwind: Unwind,
1015        dropline: Option<BasicBlock>,
1016    ) -> BasicBlock {
1017        // drop glue is sent straight to codegen
1018        // box cannot be directly dereferenced
1019        let unique_ty =
1020            adt.non_enum_variant().fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1021        let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant();
1022        let nonnull_ty = unique_variant.fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1023        let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty());
1024
1025        let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
1026        let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
1027
1028        let ptr_local = self.new_temp(ptr_ty);
1029
1030        let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
1031        let interior_path = self.elaborator.deref_subpath(self.path);
1032
1033        let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind, dropline);
1034
1035        self.new_block_with_statements(
1036            unwind,
1037            vec![self.assign(
1038                Place::from(ptr_local),
1039                Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
1040            )],
1041            TerminatorKind::Goto { target: do_drop_bb },
1042        )
1043    }
1044
1045    x;#[instrument(level = "debug", ret)]
1046    fn open_drop_for_adt(
1047        &mut self,
1048        adt: ty::AdtDef<'tcx>,
1049        args: GenericArgsRef<'tcx>,
1050    ) -> BasicBlock {
1051        if adt.variants().is_empty() {
1052            return self.new_block(self.unwind, TerminatorKind::Unreachable);
1053        }
1054
1055        let skip_contents = adt.is_union() || adt.is_manually_drop();
1056        let (contents_succ, contents_unwind, contents_dropline) = if skip_contents {
1057            if adt.has_dtor(self.tcx()) && self.elaborator.get_drop_flag(self.path).is_some() {
1058                // the top-level drop flag is usually cleared by open_drop_for_adt_contents
1059                // types with destructors would still need an empty drop ladder to clear it
1060
1061                // however, these types are only open dropped in `DropShimElaborator`
1062                // which does not have drop flags
1063                // a future box-like "DerefMove" trait would allow for this case to happen
1064                span_bug!(self.source_info.span, "open dropping partially moved union");
1065            }
1066
1067            (self.succ, self.unwind, self.dropline)
1068        } else {
1069            self.open_drop_for_adt_contents(adt, args)
1070        };
1071
1072        if adt.has_dtor(self.tcx()) {
1073            let destructor_block = if adt.is_box() {
1074                // we need to drop the inside of the box before running the destructor
1075                let succ = self.destructor_call_block_sync(contents_succ, contents_unwind);
1076                let unwind = contents_unwind
1077                    .map(|unwind| self.destructor_call_block_sync(unwind, Unwind::InCleanup));
1078                let dropline = contents_dropline
1079                    .map(|dropline| self.destructor_call_block_sync(dropline, contents_unwind));
1080                self.open_drop_for_box_contents(adt, args, succ, unwind, dropline)
1081            } else {
1082                self.destructor_call_block(contents_succ, contents_unwind, contents_dropline)
1083            };
1084
1085            self.drop_flag_test_block(destructor_block, contents_succ, contents_unwind)
1086        } else {
1087            contents_succ
1088        }
1089    }
1090
1091    fn open_drop_for_adt_contents(
1092        &mut self,
1093        adt: ty::AdtDef<'tcx>,
1094        args: GenericArgsRef<'tcx>,
1095    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1096        let (succ, unwind, dropline) = self.drop_ladder_bottom();
1097        if !adt.is_enum() {
1098            let fields =
1099                self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args);
1100            self.drop_ladder(fields, succ, unwind, dropline)
1101        } else {
1102            self.open_drop_for_multivariant(adt, args, succ, unwind, dropline)
1103        }
1104    }
1105
1106    fn open_drop_for_multivariant(
1107        &mut self,
1108        adt: ty::AdtDef<'tcx>,
1109        args: GenericArgsRef<'tcx>,
1110        succ: BasicBlock,
1111        unwind: Unwind,
1112        dropline: Option<BasicBlock>,
1113    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1114        let mut values = Vec::with_capacity(adt.variants().len());
1115        let mut normal_blocks = Vec::with_capacity(adt.variants().len());
1116        let mut unwind_blocks =
1117            Vec::with_capacity(if unwind.is_cleanup() { 0 } else { adt.variants().len() });
1118        let mut dropline_blocks =
1119            Vec::with_capacity(if dropline.is_none() { 0 } else { adt.variants().len() });
1120
1121        let mut have_otherwise_with_drop_glue = false;
1122        let mut have_otherwise = false;
1123        let tcx = self.tcx();
1124
1125        for (variant_index, discr) in adt.discriminants(tcx) {
1126            let variant = &adt.variant(variant_index);
1127            let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
1128
1129            if let Some(variant_path) = subpath {
1130                let base_place = tcx.mk_place_elem(
1131                    self.place,
1132                    ProjectionElem::Downcast(Some(variant.name), variant_index),
1133                );
1134                let fields = self.move_paths_for_fields(base_place, variant_path, variant, args);
1135                values.push(discr.val);
1136                if let Unwind::To(unwind) = unwind {
1137                    // We can't use the half-ladder from the original
1138                    // drop ladder, because this breaks the
1139                    // "funclet can't have 2 successor funclets"
1140                    // requirement from MSVC:
1141                    //
1142                    //           switch       unwind-switch
1143                    //          /      \         /        \
1144                    //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
1145                    //         |        |      /             |
1146                    //    v1.1-unwind  v2.1-unwind           |
1147                    //      ^                                |
1148                    //       \-------------------------------/
1149                    //
1150                    // Create a duplicate half-ladder to avoid that. We
1151                    // could technically only do this on MSVC, but I
1152                    // I want to minimize the divergence between MSVC
1153                    // and non-MSVC.
1154
1155                    let unwind_ladder = ::alloc::vec::from_elem(Unwind::InCleanup, fields.len() + 1)vec![Unwind::InCleanup; fields.len() + 1];
1156                    let dropline_ladder: Vec<Option<BasicBlock>> = ::alloc::vec::from_elem(None, fields.len() + 1)vec![None; fields.len() + 1];
1157                    let halfladder =
1158                        self.drop_halfladder(&unwind_ladder, &dropline_ladder, unwind, &fields);
1159                    unwind_blocks.push(halfladder.last().cloned().unwrap());
1160                }
1161                let (normal, _, drop_bb) = self.drop_ladder(fields, succ, unwind, dropline);
1162                normal_blocks.push(normal);
1163                if dropline.is_some() {
1164                    dropline_blocks.push(drop_bb.unwrap());
1165                }
1166            } else {
1167                have_otherwise = true;
1168
1169                let typing_env = self.elaborator.typing_env();
1170                let have_field_with_drop_glue = variant
1171                    .fields
1172                    .iter()
1173                    .any(|field| field.ty(tcx, args).skip_norm_wip().needs_drop(tcx, typing_env));
1174                if have_field_with_drop_glue {
1175                    have_otherwise_with_drop_glue = true;
1176                }
1177            }
1178        }
1179
1180        if !have_otherwise {
1181            values.pop();
1182        } else if !have_otherwise_with_drop_glue {
1183            normal_blocks.push(succ);
1184            if let Unwind::To(unwind) = unwind {
1185                unwind_blocks.push(unwind);
1186            }
1187            if let Some(dropline) = dropline {
1188                dropline_blocks.push(dropline);
1189            }
1190        } else {
1191            normal_blocks.push(self.drop_block(succ, unwind));
1192            if let Unwind::To(unwind) = unwind {
1193                unwind_blocks.push(self.drop_block(unwind, Unwind::InCleanup));
1194            }
1195            if let Some(dropline) = dropline {
1196                dropline_blocks.push(self.drop_block(dropline, unwind));
1197            }
1198        }
1199
1200        (
1201            self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
1202            unwind.map(|unwind| {
1203                self.adt_switch_block(adt, unwind_blocks, &values, unwind, Unwind::InCleanup)
1204            }),
1205            dropline.map(|dropline| {
1206                self.adt_switch_block(adt, dropline_blocks, &values, dropline, unwind)
1207            }),
1208        )
1209    }
1210
1211    fn adt_switch_block(
1212        &mut self,
1213        adt: ty::AdtDef<'tcx>,
1214        blocks: Vec<BasicBlock>,
1215        values: &[u128],
1216        succ: BasicBlock,
1217        unwind: Unwind,
1218    ) -> BasicBlock {
1219        let switch_block = blocks.iter().copied().all_equal_value().unwrap_or_else(|_| {
1220            // If there are multiple variants, then if something
1221            // is present within the enum the discriminant, tracked
1222            // by the rest path, must be initialized.
1223            //
1224            // Additionally, we do not want to switch on the
1225            // discriminant after it is free-ed, because that
1226            // way lies only trouble.
1227            let discr_ty = adt.repr().discr_type().to_ty(self.tcx());
1228            let discr = Place::from(self.new_temp(discr_ty));
1229            let discr_rv = Rvalue::Discriminant(self.place);
1230            self.new_block_with_statements(
1231                unwind,
1232                ::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)],
1233                TerminatorKind::SwitchInt {
1234                    discr: Operand::Move(discr),
1235                    targets: SwitchTargets::new(
1236                        values.iter().copied().zip(blocks.iter().copied()),
1237                        *blocks.last().unwrap(),
1238                    ),
1239                },
1240            )
1241        });
1242        self.drop_flag_test_block(switch_block, succ, unwind)
1243    }
1244
1245    x;#[instrument(level = "debug", skip(self), ret)]
1246    fn destructor_call_block_sync(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1247        let tcx = self.tcx();
1248        let drop_trait = tcx.require_lang_item(LangItem::Drop, DUMMY_SP);
1249        let drop_fn = tcx.associated_item_def_ids(drop_trait)[0];
1250        let ty = self.place_ty(self.place);
1251
1252        let ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
1253        let ref_place = self.new_temp(ref_ty);
1254        let unit_temp = Place::from(self.new_temp(tcx.types.unit));
1255
1256        self.new_block_with_statements(
1257            unwind,
1258            vec![self.assign(
1259                Place::from(ref_place),
1260                Rvalue::Ref(
1261                    tcx.lifetimes.re_erased,
1262                    BorrowKind::Mut { kind: MutBorrowKind::Default },
1263                    self.place,
1264                ),
1265            )],
1266            TerminatorKind::Call {
1267                // FIXME(156581): actually instantiate the binder correctly (turbofishing/fndef changes)
1268                func: Operand::function_handle(
1269                    tcx,
1270                    drop_fn,
1271                    ty::Binder::dummy([ty.into()]),
1272                    self.source_info.span,
1273                ),
1274                args: [dummy_spanned(Operand::Move(Place::from(ref_place)))].into(),
1275                destination: unit_temp,
1276                target: Some(succ),
1277                unwind: unwind.into_action(),
1278                call_source: CallSource::Misc,
1279                fn_span: self.source_info.span,
1280            },
1281        )
1282    }
1283
1284    x;#[instrument(level = "debug", skip(self), ret)]
1285    fn destructor_call_block(
1286        &mut self,
1287        succ: BasicBlock,
1288        unwind: Unwind,
1289        dropline: Option<BasicBlock>,
1290    ) -> BasicBlock {
1291        let ty = self.place_ty(self.place);
1292        if !unwind.is_cleanup() && self.check_if_can_async_drop(ty, true) {
1293            self.build_async_drop(self.place, ty, succ, unwind, dropline, true)
1294        } else {
1295            self.destructor_call_block_sync(succ, unwind)
1296        }
1297    }
1298
1299    /// Create a loop that drops an array:
1300    ///
1301    /// ```text
1302    /// loop-block:
1303    ///    can_go = cur == len
1304    ///    if can_go then succ else drop-block
1305    /// drop-block:
1306    ///    ptr = &raw mut P[cur]
1307    ///    cur = cur + 1
1308    ///    drop(ptr)
1309    /// ```
1310    fn drop_loop(
1311        &mut self,
1312        succ: BasicBlock,
1313        cur: Local,
1314        len: Local,
1315        ety: Ty<'tcx>,
1316        unwind: Unwind,
1317        dropline: Option<BasicBlock>,
1318    ) -> BasicBlock {
1319        let copy = |place: Place<'tcx>| Operand::Copy(place);
1320        let move_ = |place: Place<'tcx>| Operand::Move(place);
1321        let tcx = self.tcx();
1322
1323        let ptr_ty = Ty::new_mut_ptr(tcx, ety);
1324        let ptr = Place::from(self.new_temp(ptr_ty));
1325        let can_go = Place::from(self.new_temp(tcx.types.bool));
1326        let one = self.constant_usize(1);
1327
1328        let drop_block = self.new_block_with_statements(
1329            unwind,
1330            ::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![
1331                self.assign(
1332                    ptr,
1333                    Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_index(self.place, cur)),
1334                ),
1335                self.assign(
1336                    cur.into(),
1337                    Rvalue::BinaryOp(BinOp::Add, Box::new((move_(cur.into()), one))),
1338                ),
1339            ],
1340            // this gets overwritten by drop elaboration.
1341            TerminatorKind::Unreachable,
1342        );
1343
1344        let loop_block = self.new_block_with_statements(
1345            unwind,
1346            ::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(
1347                can_go,
1348                Rvalue::BinaryOp(BinOp::Eq, Box::new((copy(Place::from(cur)), copy(len.into())))),
1349            )],
1350            TerminatorKind::if_(move_(can_go), succ, drop_block),
1351        );
1352
1353        let place = tcx.mk_place_deref(ptr);
1354        if !unwind.is_cleanup() && self.check_if_can_async_drop(ety, false) {
1355            let async_drop_bb =
1356                self.build_async_drop(place, ety, loop_block, unwind, dropline, false);
1357            self.elaborator
1358                .patch()
1359                .patch_terminator(drop_block, TerminatorKind::Goto { target: async_drop_bb });
1360        } else {
1361            self.elaborator.patch().patch_terminator(
1362                drop_block,
1363                TerminatorKind::Drop {
1364                    place,
1365                    target: loop_block,
1366                    unwind: unwind.into_action(),
1367                    replace: false,
1368                    drop: None,
1369                },
1370            );
1371        }
1372        loop_block
1373    }
1374
1375    x;#[instrument(level = "debug", skip(self), ret)]
1376    fn open_drop_for_array(
1377        &mut self,
1378        array_ty: Ty<'tcx>,
1379        ety: Ty<'tcx>,
1380        opt_size: Option<u64>,
1381    ) -> BasicBlock {
1382        let tcx = self.tcx();
1383
1384        if let Some(size) = opt_size {
1385            enum ProjectionKind<Path> {
1386                Drop(std::ops::Range<u64>),
1387                Keep(u64, Path),
1388            }
1389            // Previously, we'd make a projection for every element in the array and create a drop
1390            // ladder if any `array_subpath` was `Some`, i.e. moving out with an array pattern.
1391            // This caused huge memory usage when generating the drops for large arrays, so we instead
1392            // record the *subslices* which are dropped and the *indexes* which are kept
1393            let mut drop_ranges = vec![];
1394            let mut dropping = true;
1395            let mut start = 0;
1396            for i in 0..size {
1397                let path = self.elaborator.array_subpath(self.path, i, size);
1398                if dropping && path.is_some() {
1399                    drop_ranges.push(ProjectionKind::Drop(start..i));
1400                    dropping = false;
1401                } else if !dropping && path.is_none() {
1402                    dropping = true;
1403                    start = i;
1404                }
1405                if let Some(path) = path {
1406                    drop_ranges.push(ProjectionKind::Keep(i, path));
1407                }
1408            }
1409            if !drop_ranges.is_empty() {
1410                if dropping {
1411                    drop_ranges.push(ProjectionKind::Drop(start..size));
1412                }
1413                let fields = drop_ranges
1414                    .iter()
1415                    .rev()
1416                    .map(|p| {
1417                        let (project, path) = match p {
1418                            ProjectionKind::Drop(r) => (
1419                                ProjectionElem::Subslice {
1420                                    from: r.start,
1421                                    to: r.end,
1422                                    from_end: false,
1423                                },
1424                                None,
1425                            ),
1426                            &ProjectionKind::Keep(offset, path) => (
1427                                ProjectionElem::ConstantIndex {
1428                                    offset,
1429                                    min_length: size,
1430                                    from_end: false,
1431                                },
1432                                Some(path),
1433                            ),
1434                        };
1435                        (tcx.mk_place_elem(self.place, project), path)
1436                    })
1437                    .collect::<Vec<_>>();
1438                let (succ, unwind, dropline) = self.drop_ladder_bottom();
1439                return self.drop_ladder(fields, succ, unwind, dropline).0;
1440            }
1441        }
1442
1443        let array_ptr_ty = Ty::new_mut_ptr(tcx, array_ty);
1444        let array_ptr = self.new_temp(array_ptr_ty);
1445
1446        let slice_ty = Ty::new_slice(tcx, ety);
1447        let slice_ptr_ty = Ty::new_mut_ptr(tcx, slice_ty);
1448        let slice_ptr = self.new_temp(slice_ptr_ty);
1449
1450        let array_place = mem::replace(
1451            &mut self.place,
1452            Place::from(slice_ptr).project_deeper(&[PlaceElem::Deref], tcx),
1453        );
1454        let slice_block = self.drop_loop_trio_for_slice(ety);
1455        self.place = array_place;
1456
1457        self.new_block_with_statements(
1458            self.unwind,
1459            vec![
1460                self.assign(Place::from(array_ptr), Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
1461                self.assign(
1462                    Place::from(slice_ptr),
1463                    Rvalue::Cast(
1464                        CastKind::PointerCoercion(
1465                            PointerCoercion::Unsize,
1466                            CoercionSource::Implicit,
1467                        ),
1468                        Operand::Move(Place::from(array_ptr)),
1469                        slice_ptr_ty,
1470                    ),
1471                ),
1472            ],
1473            TerminatorKind::Goto { target: slice_block },
1474        )
1475    }
1476
1477    /// Creates a trio of drop-loops of `place`, which drops its contents, even
1478    /// in the case of 1 panic or in the case of coroutine drop
1479    x;#[instrument(level = "debug", skip(self), ret)]
1480    fn drop_loop_trio_for_slice(&mut self, ety: Ty<'tcx>) -> BasicBlock {
1481        let tcx = self.tcx();
1482        let len = self.new_temp(tcx.types.usize);
1483        let cur = self.new_temp(tcx.types.usize);
1484
1485        let unwind = self
1486            .unwind
1487            .map(|unwind| self.drop_loop(unwind, cur, len, ety, Unwind::InCleanup, None));
1488
1489        let dropline =
1490            self.dropline.map(|dropline| self.drop_loop(dropline, cur, len, ety, unwind, None));
1491
1492        let loop_block = self.drop_loop(self.succ, cur, len, ety, unwind, dropline);
1493
1494        let [PlaceElem::Deref] = self.place.projection.as_slice() else {
1495            span_bug!(
1496                self.source_info.span,
1497                "Expected place for slice drop shim to be *_n, but it's {:?}",
1498                self.place,
1499            );
1500        };
1501
1502        let zero = self.constant_usize(0);
1503        let drop_block = self.new_block_with_statements(
1504            unwind,
1505            vec![
1506                self.assign(
1507                    len.into(),
1508                    Rvalue::UnaryOp(
1509                        UnOp::PtrMetadata,
1510                        Operand::Copy(Place::from(self.place.local)),
1511                    ),
1512                ),
1513                self.assign(cur.into(), Rvalue::Use(zero, WithRetag::Yes)),
1514            ],
1515            TerminatorKind::Goto { target: loop_block },
1516        );
1517
1518        // FIXME(#34708): handle partially-dropped array/slice elements.
1519        let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
1520        self.drop_flag_test_block(reset_block, self.succ, unwind)
1521    }
1522
1523    /// The slow-path - create an "open", elaborated drop for a type
1524    /// which is moved-out-of only partially, and patch `bb` to a jump
1525    /// to it. This must not be called on ADTs with a destructor,
1526    /// as these can't be moved-out-of, except for `Box<T>`, which is
1527    /// special-cased.
1528    ///
1529    /// This creates a "drop ladder" that drops the needed fields of the
1530    /// ADT, both in the success case or if one of the destructors fail.
1531    fn open_drop(&mut self) -> BasicBlock {
1532        let ty = self.place_ty(self.place);
1533        match ty.kind() {
1534            ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()),
1535            ty::CoroutineClosure(_, args) => {
1536                self.open_drop_for_tuple(args.as_coroutine_closure().upvar_tys())
1537            }
1538            // Note that `elaborate_drops` only drops the upvars of a coroutine,
1539            // and this is ok because `open_drop` here can only be reached
1540            // within that own coroutine's resume function.
1541            // This should only happen for the self argument on the resume function.
1542            // It effectively only contains upvars until the coroutine transformation runs.
1543            // See librustc_body/transform/coroutine.rs for more details.
1544            ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()),
1545            ty::Tuple(fields) => self.open_drop_for_tuple(fields),
1546            ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
1547            ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
1548            ty::Array(ety, size) => {
1549                let size = size.try_to_target_usize(self.tcx());
1550                self.open_drop_for_array(ty, *ety, size)
1551            }
1552            ty::Slice(ety) => self.drop_loop_trio_for_slice(*ety),
1553
1554            ty::UnsafeBinder(_) => {
1555                // Unsafe binders may elaborate drops if their inner type isn't copy.
1556                // This is enforced in typeck, so this should never happen.
1557                self.tcx().dcx().span_delayed_bug(
1558                    self.source_info.span,
1559                    "open drop for unsafe binder shouldn't be encountered",
1560                );
1561                self.new_block(self.unwind, TerminatorKind::Unreachable)
1562            }
1563
1564            _ => ::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),
1565        }
1566    }
1567
1568    x;#[instrument(level = "debug", skip(self), ret)]
1569    fn complete_drop(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1570        let drop_block = self.drop_block(succ, unwind);
1571        self.drop_flag_test_block(drop_block, succ, unwind)
1572    }
1573
1574    /// Creates a block that resets the drop flag. If `mode` is deep, all children drop flags will
1575    /// also be cleared.
1576    x;#[instrument(level = "debug", skip(self), ret)]
1577    fn drop_flag_reset_block(
1578        &mut self,
1579        mode: DropFlagMode,
1580        succ: BasicBlock,
1581        unwind: Unwind,
1582    ) -> BasicBlock {
1583        if unwind.is_cleanup() {
1584            // The drop flag isn't read again on the unwind path, so don't
1585            // bother setting it.
1586            return succ;
1587        }
1588        let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
1589        let block_start = Location { block, statement_index: 0 };
1590        self.elaborator.clear_drop_flag(block_start, self.path, mode);
1591        block
1592    }
1593
1594    x;#[instrument(level = "debug", skip(self), ret)]
1595    fn elaborated_drop_block(&mut self) -> BasicBlock {
1596        let blk = self.new_block(
1597            self.unwind,
1598            TerminatorKind::Drop {
1599                place: self.place,
1600                target: self.succ,
1601                unwind: self.unwind.into_action(),
1602                replace: false,
1603                drop: self.dropline,
1604            },
1605        );
1606        self.elaborate_drop(blk);
1607        blk
1608    }
1609
1610    fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1611        let drop_ty = self.place_ty(self.place);
1612        if !unwind.is_cleanup() && self.check_if_can_async_drop(drop_ty, false) {
1613            self.build_async_drop(self.place, drop_ty, self.succ, unwind, self.dropline, false)
1614        } else {
1615            self.new_block(
1616                unwind,
1617                TerminatorKind::Drop {
1618                    place: self.place,
1619                    target,
1620                    unwind: unwind.into_action(),
1621                    replace: false,
1622                    drop: None,
1623                },
1624            )
1625        }
1626    }
1627
1628    /// Returns the block to jump to in order to test the drop flag and execute the drop.
1629    ///
1630    /// Depending on the required `DropStyle`, this might be a generated block with an `if`
1631    /// terminator (for dynamic/open drops), or it might be `on_set` or `on_unset` itself, in case
1632    /// the drop can be statically determined.
1633    x;#[instrument(level = "debug", skip(self), ret)]
1634    fn drop_flag_test_block(
1635        &mut self,
1636        on_set: BasicBlock,
1637        on_unset: BasicBlock,
1638        unwind: Unwind,
1639    ) -> BasicBlock {
1640        let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
1641        match style {
1642            DropStyle::Dead => on_unset,
1643            DropStyle::Static => on_set,
1644            DropStyle::Conditional | DropStyle::Open => {
1645                let flag = self.elaborator.get_drop_flag(self.path).unwrap();
1646                let term = TerminatorKind::if_(flag, on_set, on_unset);
1647                self.new_block(unwind, term)
1648            }
1649        }
1650    }
1651
1652    x;#[instrument(level = "trace", skip(self), ret)]
1653    fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
1654        self.elaborator.patch().new_block(BasicBlockData::new(
1655            Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1656            unwind.is_cleanup(),
1657        ))
1658    }
1659
1660    x;#[instrument(level = "trace", skip(self, statements), ret)]
1661    fn new_block_with_statements(
1662        &mut self,
1663        unwind: Unwind,
1664        statements: Vec<Statement<'tcx>>,
1665        k: TerminatorKind<'tcx>,
1666    ) -> BasicBlock {
1667        self.elaborator.patch().new_block(BasicBlockData::new_stmts(
1668            statements,
1669            Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1670            unwind.is_cleanup(),
1671        ))
1672    }
1673
1674    fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
1675        self.elaborator.patch().new_temp(ty, self.source_info.span)
1676    }
1677
1678    fn constant_usize(&self, val: u16) -> Operand<'tcx> {
1679        Operand::Constant(Box::new(ConstOperand {
1680            span: self.source_info.span,
1681            user_ty: None,
1682            const_: Const::from_usize(self.tcx(), val.into()),
1683        }))
1684    }
1685
1686    fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
1687        Statement::new(self.source_info, StatementKind::Assign(Box::new((lhs, rhs))))
1688    }
1689
1690    fn storage_live(&self, local: Local) -> Statement<'tcx> {
1691        Statement::new(self.source_info, StatementKind::StorageLive(local))
1692    }
1693
1694    fn storage_dead(&self, local: Local) -> Statement<'tcx> {
1695        Statement::new(self.source_info, StatementKind::StorageDead(local))
1696    }
1697}