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