rustc_mir_transform/
elaborate_drop.rs

1use std::{fmt, iter, mem};
2
3use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
4use rustc_hir::lang_items::LangItem;
5use rustc_index::Idx;
6use rustc_middle::mir::*;
7use rustc_middle::ty::adjustment::PointerCoercion;
8use rustc_middle::ty::util::IntTypeExt;
9use rustc_middle::ty::{self, GenericArg, GenericArgsRef, Ty, TyCtxt};
10use rustc_middle::{bug, span_bug, traits};
11use rustc_span::DUMMY_SP;
12use rustc_span::source_map::{Spanned, dummy_spanned};
13use tracing::{debug, instrument};
14
15use crate::patch::MirPatch;
16
17/// Describes how/if a value should be dropped.
18#[derive(Debug)]
19pub(crate) enum DropStyle {
20    /// The value is already dead at the drop location, no drop will be executed.
21    Dead,
22
23    /// The value is known to always be initialized at the drop location, drop will always be
24    /// executed.
25    Static,
26
27    /// Whether the value needs to be dropped depends on its drop flag.
28    Conditional,
29
30    /// An "open" drop is one where only the fields of a value are dropped.
31    ///
32    /// For example, this happens when moving out of a struct field: The rest of the struct will be
33    /// dropped in such an "open" drop. It is also used to generate drop glue for the individual
34    /// components of a value, for example for dropping array elements.
35    Open,
36}
37
38/// Which drop flags to affect/check with an operation.
39#[derive(Debug)]
40pub(crate) enum DropFlagMode {
41    /// Only affect the top-level drop flag, not that of any contained fields.
42    Shallow,
43    /// Affect all nested drop flags in addition to the top-level one.
44    Deep,
45}
46
47/// Describes if unwinding is necessary and where to unwind to if a panic occurs.
48#[derive(Copy, Clone, Debug)]
49pub(crate) enum Unwind {
50    /// Unwind to this block.
51    To(BasicBlock),
52    /// Already in an unwind path, any panic will cause an abort.
53    InCleanup,
54}
55
56impl Unwind {
57    fn is_cleanup(self) -> bool {
58        match self {
59            Unwind::To(..) => false,
60            Unwind::InCleanup => true,
61        }
62    }
63
64    fn into_action(self) -> UnwindAction {
65        match self {
66            Unwind::To(bb) => UnwindAction::Cleanup(bb),
67            Unwind::InCleanup => UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
68        }
69    }
70
71    fn map<F>(self, f: F) -> Self
72    where
73        F: FnOnce(BasicBlock) -> BasicBlock,
74    {
75        match self {
76            Unwind::To(bb) => Unwind::To(f(bb)),
77            Unwind::InCleanup => Unwind::InCleanup,
78        }
79    }
80}
81
82pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
83    /// The type representing paths that can be moved out of.
84    ///
85    /// Users can move out of individual fields of a struct, such as `a.b.c`. This type is used to
86    /// represent such move paths. Sometimes tracking individual move paths is not necessary, in
87    /// which case this may be set to (for example) `()`.
88    type Path: Copy + fmt::Debug;
89
90    // Accessors
91
92    fn patch_ref(&self) -> &MirPatch<'tcx>;
93    fn patch(&mut self) -> &mut MirPatch<'tcx>;
94    fn body(&self) -> &'a Body<'tcx>;
95    fn tcx(&self) -> TyCtxt<'tcx>;
96    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
97    fn allow_async_drops(&self) -> bool;
98
99    fn terminator_loc(&self, bb: BasicBlock) -> Location;
100
101    // Drop logic
102
103    /// Returns how `path` should be dropped, given `mode`.
104    fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
105
106    /// Returns the drop flag of `path` as a MIR `Operand` (or `None` if `path` has no drop flag).
107    fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
108
109    /// Modifies the MIR patch so that the drop flag of `path` (if any) is cleared at `location`.
110    ///
111    /// If `mode` is deep, drop flags of all child paths should also be cleared by inserting
112    /// additional statements.
113    fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
114
115    // Subpaths
116
117    /// Returns the subpath of a field of `path` (or `None` if there is no dedicated subpath).
118    ///
119    /// If this returns `None`, `field` will not get a dedicated drop flag.
120    fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path>;
121
122    /// Returns the subpath of a dereference of `path` (or `None` if there is no dedicated subpath).
123    ///
124    /// If this returns `None`, `*path` will not get a dedicated drop flag.
125    ///
126    /// This is only relevant for `Box<T>`, where the contained `T` can be moved out of the box.
127    fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
128
129    /// Returns the subpath of downcasting `path` to one of its variants.
130    ///
131    /// If this returns `None`, the downcast of `path` will not get a dedicated drop flag.
132    fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
133
134    /// Returns the subpath of indexing a fixed-size array `path`.
135    ///
136    /// If this returns `None`, elements of `path` will not get a dedicated drop flag.
137    ///
138    /// This is only relevant for array patterns, which can move out of individual array elements.
139    fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path>;
140}
141
142#[derive(Debug)]
143struct DropCtxt<'a, 'b, 'tcx, D>
144where
145    D: DropElaborator<'b, 'tcx>,
146{
147    elaborator: &'a mut D,
148
149    source_info: SourceInfo,
150
151    place: Place<'tcx>,
152    path: D::Path,
153    succ: BasicBlock,
154    unwind: Unwind,
155    dropline: Option<BasicBlock>,
156}
157
158/// "Elaborates" a drop of `place`/`path` and patches `bb`'s terminator to execute it.
159///
160/// The passed `elaborator` is used to determine what should happen at the drop terminator. It
161/// decides whether the drop can be statically determined or whether it needs a dynamic drop flag,
162/// and whether the drop is "open", ie. should be expanded to drop all subfields of the dropped
163/// value.
164///
165/// When this returns, the MIR patch in the `elaborator` contains the necessary changes.
166pub(crate) fn elaborate_drop<'b, 'tcx, D>(
167    elaborator: &mut D,
168    source_info: SourceInfo,
169    place: Place<'tcx>,
170    path: D::Path,
171    succ: BasicBlock,
172    unwind: Unwind,
173    bb: BasicBlock,
174    dropline: Option<BasicBlock>,
175) where
176    D: DropElaborator<'b, 'tcx>,
177    'tcx: 'b,
178{
179    DropCtxt { elaborator, source_info, place, path, succ, unwind, dropline }.elaborate_drop(bb)
180}
181
182impl<'a, 'b, 'tcx, D> DropCtxt<'a, 'b, 'tcx, D>
183where
184    D: DropElaborator<'b, 'tcx>,
185    'tcx: 'b,
186{
187    #[instrument(level = "trace", skip(self), ret)]
188    fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
189        if place.local < self.elaborator.body().local_decls.next_index() {
190            place.ty(self.elaborator.body(), self.tcx()).ty
191        } else {
192            // We don't have a slice with all the locals, since some are in the patch.
193            PlaceTy::from_ty(self.elaborator.patch_ref().local_ty(place.local))
194                .multi_projection_ty(self.elaborator.tcx(), place.projection)
195                .ty
196        }
197    }
198
199    fn tcx(&self) -> TyCtxt<'tcx> {
200        self.elaborator.tcx()
201    }
202
203    // Generates three blocks:
204    // * #1:pin_obj_bb:   call Pin<ObjTy>::new_unchecked(&mut obj)
205    // * #2:call_drop_bb: fut = call obj.<AsyncDrop::drop>() OR call async_drop_in_place<T>(obj)
206    // * #3:drop_term_bb: drop (obj, fut, ...)
207    // We keep async drop unexpanded to poll-loop here, to expand it later, at StateTransform -
208    //   into states expand.
209    // call_destructor_only - to call only AsyncDrop::drop, not full async_drop_in_place glue
210    fn build_async_drop(
211        &mut self,
212        place: Place<'tcx>,
213        drop_ty: Ty<'tcx>,
214        bb: Option<BasicBlock>,
215        succ: BasicBlock,
216        unwind: Unwind,
217        dropline: Option<BasicBlock>,
218        call_destructor_only: bool,
219    ) -> BasicBlock {
220        let tcx = self.tcx();
221        let span = self.source_info.span;
222
223        let pin_obj_bb = bb.unwrap_or_else(|| {
224            self.elaborator.patch().new_block(BasicBlockData {
225                statements: vec![],
226                terminator: Some(Terminator {
227                    // Temporary terminator, will be replaced by patch
228                    source_info: self.source_info,
229                    kind: TerminatorKind::Return,
230                }),
231                is_cleanup: false,
232            })
233        });
234
235        let (fut_ty, drop_fn_def_id, trait_args) = if call_destructor_only {
236            // Resolving obj.<AsyncDrop::drop>()
237            let trait_ref = ty::TraitRef::new(
238                tcx,
239                tcx.require_lang_item(LangItem::AsyncDrop, Some(span)),
240                [drop_ty],
241            );
242            let (drop_trait, trait_args) = match tcx.codegen_select_candidate(
243                ty::TypingEnv::fully_monomorphized().as_query_input(trait_ref),
244            ) {
245                Ok(traits::ImplSource::UserDefined(traits::ImplSourceUserDefinedData {
246                    impl_def_id,
247                    args,
248                    ..
249                })) => (*impl_def_id, *args),
250                impl_source => {
251                    span_bug!(span, "invalid `AsyncDrop` impl_source: {:?}", impl_source);
252                }
253            };
254            let drop_fn_def_id = tcx.associated_item_def_ids(drop_trait)[0];
255            let drop_fn = Ty::new_fn_def(tcx, drop_fn_def_id, trait_args);
256            let sig = drop_fn.fn_sig(tcx);
257            let sig = tcx.instantiate_bound_regions_with_erased(sig);
258            (sig.output(), drop_fn_def_id, trait_args)
259        } else {
260            // Resolving async_drop_in_place<T> function for drop_ty
261            let drop_fn_def_id = tcx.require_lang_item(LangItem::AsyncDropInPlace, Some(span));
262            let trait_args = tcx.mk_args(&[drop_ty.into()]);
263            let sig = tcx.fn_sig(drop_fn_def_id).instantiate(tcx, trait_args);
264            let sig = tcx.instantiate_bound_regions_with_erased(sig);
265            (sig.output(), drop_fn_def_id, trait_args)
266        };
267
268        let fut = Place::from(self.new_temp(fut_ty));
269
270        // #1:pin_obj_bb >>> obj_ref = &mut obj
271        let obj_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, drop_ty);
272        let obj_ref_place = Place::from(self.new_temp(obj_ref_ty));
273
274        let term_loc = self.elaborator.terminator_loc(pin_obj_bb);
275        self.elaborator.patch().add_assign(
276            term_loc,
277            obj_ref_place,
278            Rvalue::Ref(
279                tcx.lifetimes.re_erased,
280                BorrowKind::Mut { kind: MutBorrowKind::Default },
281                place,
282            ),
283        );
284
285        // pin_obj_place preparation
286        let pin_obj_new_unchecked_fn = Ty::new_fn_def(
287            tcx,
288            tcx.require_lang_item(LangItem::PinNewUnchecked, Some(span)),
289            [GenericArg::from(obj_ref_ty)],
290        );
291        let pin_obj_ty = pin_obj_new_unchecked_fn.fn_sig(tcx).output().no_bound_vars().unwrap();
292        let pin_obj_place = Place::from(self.new_temp(pin_obj_ty));
293        let pin_obj_new_unchecked_fn = Operand::Constant(Box::new(ConstOperand {
294            span,
295            user_ty: None,
296            const_: Const::zero_sized(pin_obj_new_unchecked_fn),
297        }));
298
299        // #3:drop_term_bb
300        let drop_term_bb = self.new_block(
301            unwind,
302            TerminatorKind::Drop {
303                place,
304                target: succ,
305                unwind: unwind.into_action(),
306                replace: false,
307                drop: dropline,
308                async_fut: Some(fut.local),
309            },
310        );
311
312        // #2:call_drop_bb
313        let mut call_statements = Vec::new();
314        let drop_arg = if call_destructor_only {
315            pin_obj_place
316        } else {
317            let ty::Adt(adt_def, adt_args) = pin_obj_ty.kind() else {
318                bug!();
319            };
320            let obj_ptr_ty = Ty::new_mut_ptr(tcx, drop_ty);
321            let obj_ptr_place = Place::from(self.new_temp(obj_ptr_ty));
322            let unwrap_ty = adt_def.non_enum_variant().fields[FieldIdx::ZERO].ty(tcx, adt_args);
323            let addr = Rvalue::RawPtr(
324                RawPtrKind::Mut,
325                pin_obj_place.project_deeper(
326                    &[ProjectionElem::Field(FieldIdx::ZERO, unwrap_ty), ProjectionElem::Deref],
327                    tcx,
328                ),
329            );
330            call_statements.push(self.assign(obj_ptr_place, addr));
331            obj_ptr_place
332        };
333        call_statements.push(Statement {
334            source_info: self.source_info,
335            kind: StatementKind::StorageLive(fut.local),
336        });
337
338        let call_drop_bb = self.new_block_with_statements(
339            unwind,
340            call_statements,
341            TerminatorKind::Call {
342                func: Operand::function_handle(tcx, drop_fn_def_id, trait_args, span),
343                args: [Spanned { node: Operand::Move(drop_arg), span: DUMMY_SP }].into(),
344                destination: fut,
345                target: Some(drop_term_bb),
346                unwind: unwind.into_action(),
347                call_source: CallSource::Misc,
348                fn_span: self.source_info.span,
349            },
350        );
351
352        // StorageDead(fut) in self.succ block (at the begin)
353        self.elaborator.patch().add_statement(
354            Location { block: self.succ, statement_index: 0 },
355            StatementKind::StorageDead(fut.local),
356        );
357
358        // #1:pin_obj_bb >>> call Pin<ObjTy>::new_unchecked(&mut obj)
359        self.elaborator.patch().patch_terminator(
360            pin_obj_bb,
361            TerminatorKind::Call {
362                func: pin_obj_new_unchecked_fn,
363                args: [dummy_spanned(Operand::Move(obj_ref_place))].into(),
364                destination: pin_obj_place,
365                target: Some(call_drop_bb),
366                unwind: unwind.into_action(),
367                call_source: CallSource::Misc,
368                fn_span: span,
369            },
370        );
371        pin_obj_bb
372    }
373
374    fn build_drop(&mut self, bb: BasicBlock) {
375        let drop_ty = self.place_ty(self.place);
376        if self.tcx().features().async_drop()
377            && self.elaborator.body().coroutine.is_some()
378            && self.elaborator.allow_async_drops()
379            && !self.elaborator.patch_ref().block(self.elaborator.body(), bb).is_cleanup
380            && drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
381        {
382            self.build_async_drop(
383                self.place,
384                drop_ty,
385                Some(bb),
386                self.succ,
387                self.unwind,
388                self.dropline,
389                false,
390            );
391        } else {
392            self.elaborator.patch().patch_terminator(
393                bb,
394                TerminatorKind::Drop {
395                    place: self.place,
396                    target: self.succ,
397                    unwind: self.unwind.into_action(),
398                    replace: false,
399                    drop: None,
400                    async_fut: None,
401                },
402            );
403        }
404    }
405
406    /// This elaborates a single drop instruction, located at `bb`, and
407    /// patches over it.
408    ///
409    /// The elaborated drop checks the drop flags to only drop what
410    /// is initialized.
411    ///
412    /// In addition, the relevant drop flags also need to be cleared
413    /// to avoid double-drops. However, in the middle of a complex
414    /// drop, one must avoid clearing some of the flags before they
415    /// are read, as that would cause a memory leak.
416    ///
417    /// In particular, when dropping an ADT, multiple fields may be
418    /// joined together under the `rest` subpath. They are all controlled
419    /// by the primary drop flag, but only the last rest-field dropped
420    /// should clear it (and it must also not clear anything else).
421    //
422    // FIXME: I think we should just control the flags externally,
423    // and then we do not need this machinery.
424    #[instrument(level = "debug")]
425    fn elaborate_drop(&mut self, bb: BasicBlock) {
426        match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
427            DropStyle::Dead => {
428                self.elaborator
429                    .patch()
430                    .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
431            }
432            DropStyle::Static => {
433                self.build_drop(bb);
434            }
435            DropStyle::Conditional => {
436                let drop_bb = self.complete_drop(self.succ, self.unwind);
437                self.elaborator
438                    .patch()
439                    .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
440            }
441            DropStyle::Open => {
442                let drop_bb = self.open_drop();
443                self.elaborator
444                    .patch()
445                    .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
446            }
447        }
448    }
449
450    /// Returns the place and move path for each field of `variant`,
451    /// (the move path is `None` if the field is a rest field).
452    fn move_paths_for_fields(
453        &self,
454        base_place: Place<'tcx>,
455        variant_path: D::Path,
456        variant: &'tcx ty::VariantDef,
457        args: GenericArgsRef<'tcx>,
458    ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
459        variant
460            .fields
461            .iter_enumerated()
462            .map(|(field_idx, field)| {
463                let subpath = self.elaborator.field_subpath(variant_path, field_idx);
464                let tcx = self.tcx();
465
466                assert_eq!(self.elaborator.typing_env().typing_mode, ty::TypingMode::PostAnalysis);
467                let field_ty = match tcx.try_normalize_erasing_regions(
468                    self.elaborator.typing_env(),
469                    field.ty(tcx, args),
470                ) {
471                    Ok(t) => t,
472                    Err(_) => Ty::new_error(
473                        self.tcx(),
474                        self.tcx().dcx().span_delayed_bug(
475                            self.elaborator.body().span,
476                            "Error normalizing in drop elaboration.",
477                        ),
478                    ),
479                };
480
481                (tcx.mk_place_field(base_place, field_idx, field_ty), subpath)
482            })
483            .collect()
484    }
485
486    fn drop_subpath(
487        &mut self,
488        place: Place<'tcx>,
489        path: Option<D::Path>,
490        succ: BasicBlock,
491        unwind: Unwind,
492        dropline: Option<BasicBlock>,
493    ) -> BasicBlock {
494        if let Some(path) = path {
495            debug!("drop_subpath: for std field {:?}", place);
496
497            DropCtxt {
498                elaborator: self.elaborator,
499                source_info: self.source_info,
500                path,
501                place,
502                succ,
503                unwind,
504                dropline,
505            }
506            .elaborated_drop_block()
507        } else {
508            debug!("drop_subpath: for rest field {:?}", place);
509
510            DropCtxt {
511                elaborator: self.elaborator,
512                source_info: self.source_info,
513                place,
514                succ,
515                unwind,
516                dropline,
517                // Using `self.path` here to condition the drop on
518                // our own drop flag.
519                path: self.path,
520            }
521            .complete_drop(succ, unwind)
522        }
523    }
524
525    /// Creates one-half of the drop ladder for a list of fields, and return
526    /// the list of steps in it in reverse order, with the first step
527    /// dropping 0 fields and so on.
528    ///
529    /// `unwind_ladder` is such a list of steps in reverse order,
530    /// which is called if the matching step of the drop glue panics.
531    ///
532    /// `dropline_ladder` is a similar list of steps in reverse order,
533    /// which is called if the matching step of the drop glue will contain async drop
534    /// (expanded later to Yield) and the containing coroutine will be dropped at this point.
535    fn drop_halfladder(
536        &mut self,
537        unwind_ladder: &[Unwind],
538        dropline_ladder: &[Option<BasicBlock>],
539        mut succ: BasicBlock,
540        fields: &[(Place<'tcx>, Option<D::Path>)],
541    ) -> Vec<BasicBlock> {
542        iter::once(succ)
543            .chain(itertools::izip!(fields.iter().rev(), unwind_ladder, dropline_ladder).map(
544                |(&(place, path), &unwind_succ, &dropline_to)| {
545                    succ = self.drop_subpath(place, path, succ, unwind_succ, dropline_to);
546                    succ
547                },
548            ))
549            .collect()
550    }
551
552    fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind, Option<BasicBlock>) {
553        // Clear the "master" drop flag at the end. This is needed
554        // because the "master" drop protects the ADT's discriminant,
555        // which is invalidated after the ADT is dropped.
556        (
557            self.drop_flag_reset_block(DropFlagMode::Shallow, self.succ, self.unwind),
558            self.unwind,
559            self.dropline,
560        )
561    }
562
563    /// Creates a full drop ladder, consisting of 2 connected half-drop-ladders
564    ///
565    /// For example, with 3 fields, the drop ladder is
566    ///
567    /// .d0:
568    ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
569    /// .d1:
570    ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
571    /// .d2:
572    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
573    /// .c1:
574    ///     ELAB(drop location.1 [target=.c2])
575    /// .c2:
576    ///     ELAB(drop location.2 [target=`self.unwind`])
577    ///
578    /// For possible-async drops in coroutines we also need dropline ladder
579    /// .d0 (mainline):
580    ///     ELAB(drop location.0 [target=.d1, unwind=.c1, drop=.e1])
581    /// .d1 (mainline):
582    ///     ELAB(drop location.1 [target=.d2, unwind=.c2, drop=.e2])
583    /// .d2 (mainline):
584    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`, drop=`self.drop`])
585    /// .c1 (unwind):
586    ///     ELAB(drop location.1 [target=.c2])
587    /// .c2 (unwind):
588    ///     ELAB(drop location.2 [target=`self.unwind`])
589    /// .e1 (dropline):
590    ///     ELAB(drop location.1 [target=.e2, unwind=.c2])
591    /// .e2 (dropline):
592    ///     ELAB(drop location.2 [target=`self.drop`, unwind=`self.unwind`])
593    ///
594    /// NOTE: this does not clear the master drop flag, so you need
595    /// to point succ/unwind on a `drop_ladder_bottom`.
596    fn drop_ladder(
597        &mut self,
598        fields: Vec<(Place<'tcx>, Option<D::Path>)>,
599        succ: BasicBlock,
600        unwind: Unwind,
601        dropline: Option<BasicBlock>,
602    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
603        debug!("drop_ladder({:?}, {:?})", self, fields);
604        assert!(
605            if unwind.is_cleanup() { dropline.is_none() } else { true },
606            "Dropline is set for cleanup drop ladder"
607        );
608
609        let mut fields = fields;
610        fields.retain(|&(place, _)| {
611            self.place_ty(place).needs_drop(self.tcx(), self.elaborator.typing_env())
612        });
613
614        debug!("drop_ladder - fields needing drop: {:?}", fields);
615
616        let dropline_ladder: Vec<Option<BasicBlock>> = vec![None; fields.len() + 1];
617        let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
618        let unwind_ladder: Vec<_> = if let Unwind::To(succ) = unwind {
619            let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
620            halfladder.into_iter().map(Unwind::To).collect()
621        } else {
622            unwind_ladder
623        };
624        let dropline_ladder: Vec<_> = if let Some(succ) = dropline {
625            let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
626            halfladder.into_iter().map(Some).collect()
627        } else {
628            dropline_ladder
629        };
630
631        let normal_ladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
632
633        (
634            *normal_ladder.last().unwrap(),
635            *unwind_ladder.last().unwrap(),
636            *dropline_ladder.last().unwrap(),
637        )
638    }
639
640    fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
641        debug!("open_drop_for_tuple({:?}, {:?})", self, tys);
642
643        let fields = tys
644            .iter()
645            .enumerate()
646            .map(|(i, &ty)| {
647                (
648                    self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
649                    self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
650                )
651            })
652            .collect();
653
654        let (succ, unwind, dropline) = self.drop_ladder_bottom();
655        self.drop_ladder(fields, succ, unwind, dropline).0
656    }
657
658    /// Drops the T contained in a `Box<T>` if it has not been moved out of
659    #[instrument(level = "debug", ret)]
660    fn open_drop_for_box_contents(
661        &mut self,
662        adt: ty::AdtDef<'tcx>,
663        args: GenericArgsRef<'tcx>,
664        succ: BasicBlock,
665        unwind: Unwind,
666        dropline: Option<BasicBlock>,
667    ) -> BasicBlock {
668        // drop glue is sent straight to codegen
669        // box cannot be directly dereferenced
670        let unique_ty = adt.non_enum_variant().fields[FieldIdx::ZERO].ty(self.tcx(), args);
671        let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant();
672        let nonnull_ty = unique_variant.fields[FieldIdx::ZERO].ty(self.tcx(), args);
673        let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty());
674
675        let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
676        let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
677
678        let ptr_local = self.new_temp(ptr_ty);
679
680        let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
681        let interior_path = self.elaborator.deref_subpath(self.path);
682
683        let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind, dropline);
684
685        let setup_bbd = BasicBlockData {
686            statements: vec![self.assign(
687                Place::from(ptr_local),
688                Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
689            )],
690            terminator: Some(Terminator {
691                kind: TerminatorKind::Goto { target: do_drop_bb },
692                source_info: self.source_info,
693            }),
694            is_cleanup: unwind.is_cleanup(),
695        };
696        self.elaborator.patch().new_block(setup_bbd)
697    }
698
699    #[instrument(level = "debug", ret)]
700    fn open_drop_for_adt(
701        &mut self,
702        adt: ty::AdtDef<'tcx>,
703        args: GenericArgsRef<'tcx>,
704    ) -> BasicBlock {
705        if adt.variants().is_empty() {
706            return self.elaborator.patch().new_block(BasicBlockData {
707                statements: vec![],
708                terminator: Some(Terminator {
709                    source_info: self.source_info,
710                    kind: TerminatorKind::Unreachable,
711                }),
712                is_cleanup: self.unwind.is_cleanup(),
713            });
714        }
715
716        let skip_contents = adt.is_union() || adt.is_manually_drop();
717        let contents_drop = if skip_contents {
718            (self.succ, self.unwind, self.dropline)
719        } else {
720            self.open_drop_for_adt_contents(adt, args)
721        };
722
723        if adt.is_box() {
724            // we need to drop the inside of the box before running the destructor
725            let succ = self.destructor_call_block_sync((contents_drop.0, contents_drop.1));
726            let unwind = contents_drop
727                .1
728                .map(|unwind| self.destructor_call_block_sync((unwind, Unwind::InCleanup)));
729            let dropline = contents_drop
730                .2
731                .map(|dropline| self.destructor_call_block_sync((dropline, contents_drop.1)));
732
733            self.open_drop_for_box_contents(adt, args, succ, unwind, dropline)
734        } else if adt.has_dtor(self.tcx()) {
735            self.destructor_call_block(contents_drop)
736        } else {
737            contents_drop.0
738        }
739    }
740
741    fn open_drop_for_adt_contents(
742        &mut self,
743        adt: ty::AdtDef<'tcx>,
744        args: GenericArgsRef<'tcx>,
745    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
746        let (succ, unwind, dropline) = self.drop_ladder_bottom();
747        if !adt.is_enum() {
748            let fields =
749                self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args);
750            self.drop_ladder(fields, succ, unwind, dropline)
751        } else {
752            self.open_drop_for_multivariant(adt, args, succ, unwind, dropline)
753        }
754    }
755
756    fn open_drop_for_multivariant(
757        &mut self,
758        adt: ty::AdtDef<'tcx>,
759        args: GenericArgsRef<'tcx>,
760        succ: BasicBlock,
761        unwind: Unwind,
762        dropline: Option<BasicBlock>,
763    ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
764        let mut values = Vec::with_capacity(adt.variants().len());
765        let mut normal_blocks = Vec::with_capacity(adt.variants().len());
766        let mut unwind_blocks =
767            if unwind.is_cleanup() { None } else { Some(Vec::with_capacity(adt.variants().len())) };
768        let mut dropline_blocks =
769            if dropline.is_none() { None } else { Some(Vec::with_capacity(adt.variants().len())) };
770
771        let mut have_otherwise_with_drop_glue = false;
772        let mut have_otherwise = false;
773        let tcx = self.tcx();
774
775        for (variant_index, discr) in adt.discriminants(tcx) {
776            let variant = &adt.variant(variant_index);
777            let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
778
779            if let Some(variant_path) = subpath {
780                let base_place = tcx.mk_place_elem(
781                    self.place,
782                    ProjectionElem::Downcast(Some(variant.name), variant_index),
783                );
784                let fields = self.move_paths_for_fields(base_place, variant_path, variant, args);
785                values.push(discr.val);
786                if let Unwind::To(unwind) = unwind {
787                    // We can't use the half-ladder from the original
788                    // drop ladder, because this breaks the
789                    // "funclet can't have 2 successor funclets"
790                    // requirement from MSVC:
791                    //
792                    //           switch       unwind-switch
793                    //          /      \         /        \
794                    //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
795                    //         |        |      /             |
796                    //    v1.1-unwind  v2.1-unwind           |
797                    //      ^                                |
798                    //       \-------------------------------/
799                    //
800                    // Create a duplicate half-ladder to avoid that. We
801                    // could technically only do this on MSVC, but I
802                    // I want to minimize the divergence between MSVC
803                    // and non-MSVC.
804
805                    let unwind_blocks = unwind_blocks.as_mut().unwrap();
806                    let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
807                    let dropline_ladder: Vec<Option<BasicBlock>> = vec![None; fields.len() + 1];
808                    let halfladder =
809                        self.drop_halfladder(&unwind_ladder, &dropline_ladder, unwind, &fields);
810                    unwind_blocks.push(halfladder.last().cloned().unwrap());
811                }
812                let (normal, _, drop_bb) = self.drop_ladder(fields, succ, unwind, dropline);
813                normal_blocks.push(normal);
814                if dropline.is_some() {
815                    dropline_blocks.as_mut().unwrap().push(drop_bb.unwrap());
816                }
817            } else {
818                have_otherwise = true;
819
820                let typing_env = self.elaborator.typing_env();
821                let have_field_with_drop_glue = variant
822                    .fields
823                    .iter()
824                    .any(|field| field.ty(tcx, args).needs_drop(tcx, typing_env));
825                if have_field_with_drop_glue {
826                    have_otherwise_with_drop_glue = true;
827                }
828            }
829        }
830
831        if !have_otherwise {
832            values.pop();
833        } else if !have_otherwise_with_drop_glue {
834            normal_blocks.push(self.goto_block(succ, unwind));
835            if let Unwind::To(unwind) = unwind {
836                unwind_blocks.as_mut().unwrap().push(self.goto_block(unwind, Unwind::InCleanup));
837            }
838        } else {
839            normal_blocks.push(self.drop_block(succ, unwind));
840            if let Unwind::To(unwind) = unwind {
841                unwind_blocks.as_mut().unwrap().push(self.drop_block(unwind, Unwind::InCleanup));
842            }
843        }
844
845        (
846            self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
847            unwind.map(|unwind| {
848                self.adt_switch_block(
849                    adt,
850                    unwind_blocks.unwrap(),
851                    &values,
852                    unwind,
853                    Unwind::InCleanup,
854                )
855            }),
856            dropline.map(|dropline| {
857                self.adt_switch_block(adt, dropline_blocks.unwrap(), &values, dropline, unwind)
858            }),
859        )
860    }
861
862    fn adt_switch_block(
863        &mut self,
864        adt: ty::AdtDef<'tcx>,
865        blocks: Vec<BasicBlock>,
866        values: &[u128],
867        succ: BasicBlock,
868        unwind: Unwind,
869    ) -> BasicBlock {
870        // If there are multiple variants, then if something
871        // is present within the enum the discriminant, tracked
872        // by the rest path, must be initialized.
873        //
874        // Additionally, we do not want to switch on the
875        // discriminant after it is free-ed, because that
876        // way lies only trouble.
877        let discr_ty = adt.repr().discr_type().to_ty(self.tcx());
878        let discr = Place::from(self.new_temp(discr_ty));
879        let discr_rv = Rvalue::Discriminant(self.place);
880        let switch_block = BasicBlockData {
881            statements: vec![self.assign(discr, discr_rv)],
882            terminator: Some(Terminator {
883                source_info: self.source_info,
884                kind: TerminatorKind::SwitchInt {
885                    discr: Operand::Move(discr),
886                    targets: SwitchTargets::new(
887                        values.iter().copied().zip(blocks.iter().copied()),
888                        *blocks.last().unwrap(),
889                    ),
890                },
891            }),
892            is_cleanup: unwind.is_cleanup(),
893        };
894        let switch_block = self.elaborator.patch().new_block(switch_block);
895        self.drop_flag_test_block(switch_block, succ, unwind)
896    }
897
898    fn destructor_call_block_sync(&mut self, (succ, unwind): (BasicBlock, Unwind)) -> BasicBlock {
899        debug!("destructor_call_block_sync({:?}, {:?})", self, succ);
900        let tcx = self.tcx();
901        let drop_trait = tcx.require_lang_item(LangItem::Drop, None);
902        let drop_fn = tcx.associated_item_def_ids(drop_trait)[0];
903        let ty = self.place_ty(self.place);
904
905        let ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
906        let ref_place = self.new_temp(ref_ty);
907        let unit_temp = Place::from(self.new_temp(tcx.types.unit));
908
909        let result = BasicBlockData {
910            statements: vec![self.assign(
911                Place::from(ref_place),
912                Rvalue::Ref(
913                    tcx.lifetimes.re_erased,
914                    BorrowKind::Mut { kind: MutBorrowKind::Default },
915                    self.place,
916                ),
917            )],
918            terminator: Some(Terminator {
919                kind: TerminatorKind::Call {
920                    func: Operand::function_handle(
921                        tcx,
922                        drop_fn,
923                        [ty.into()],
924                        self.source_info.span,
925                    ),
926                    args: [Spanned { node: Operand::Move(Place::from(ref_place)), span: DUMMY_SP }]
927                        .into(),
928                    destination: unit_temp,
929                    target: Some(succ),
930                    unwind: unwind.into_action(),
931                    call_source: CallSource::Misc,
932                    fn_span: self.source_info.span,
933                },
934                source_info: self.source_info,
935            }),
936            is_cleanup: unwind.is_cleanup(),
937        };
938
939        let destructor_block = self.elaborator.patch().new_block(result);
940
941        let block_start = Location { block: destructor_block, statement_index: 0 };
942        self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
943
944        self.drop_flag_test_block(destructor_block, succ, unwind)
945    }
946
947    fn destructor_call_block(
948        &mut self,
949        (succ, unwind, dropline): (BasicBlock, Unwind, Option<BasicBlock>),
950    ) -> BasicBlock {
951        debug!("destructor_call_block({:?}, {:?})", self, succ);
952        let ty = self.place_ty(self.place);
953        if self.tcx().features().async_drop()
954            && self.elaborator.body().coroutine.is_some()
955            && self.elaborator.allow_async_drops()
956            && !unwind.is_cleanup()
957            && ty.is_async_drop(self.tcx(), self.elaborator.typing_env())
958        {
959            let destructor_block =
960                self.build_async_drop(self.place, ty, None, succ, unwind, dropline, true);
961
962            let block_start = Location { block: destructor_block, statement_index: 0 };
963            self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
964
965            self.drop_flag_test_block(destructor_block, succ, unwind)
966        } else {
967            self.destructor_call_block_sync((succ, unwind))
968        }
969    }
970
971    /// Create a loop that drops an array:
972    ///
973    /// ```text
974    /// loop-block:
975    ///    can_go = cur == len
976    ///    if can_go then succ else drop-block
977    /// drop-block:
978    ///    ptr = &raw mut P[cur]
979    ///    cur = cur + 1
980    ///    drop(ptr)
981    /// ```
982    fn drop_loop(
983        &mut self,
984        succ: BasicBlock,
985        cur: Local,
986        len: Local,
987        ety: Ty<'tcx>,
988        unwind: Unwind,
989        dropline: Option<BasicBlock>,
990    ) -> BasicBlock {
991        let copy = |place: Place<'tcx>| Operand::Copy(place);
992        let move_ = |place: Place<'tcx>| Operand::Move(place);
993        let tcx = self.tcx();
994
995        let ptr_ty = Ty::new_mut_ptr(tcx, ety);
996        let ptr = Place::from(self.new_temp(ptr_ty));
997        let can_go = Place::from(self.new_temp(tcx.types.bool));
998        let one = self.constant_usize(1);
999
1000        let drop_block = BasicBlockData {
1001            statements: vec![
1002                self.assign(
1003                    ptr,
1004                    Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_index(self.place, cur)),
1005                ),
1006                self.assign(
1007                    cur.into(),
1008                    Rvalue::BinaryOp(BinOp::Add, Box::new((move_(cur.into()), one))),
1009                ),
1010            ],
1011            is_cleanup: unwind.is_cleanup(),
1012            terminator: Some(Terminator {
1013                source_info: self.source_info,
1014                // this gets overwritten by drop elaboration.
1015                kind: TerminatorKind::Unreachable,
1016            }),
1017        };
1018        let drop_block = self.elaborator.patch().new_block(drop_block);
1019
1020        let loop_block = BasicBlockData {
1021            statements: vec![self.assign(
1022                can_go,
1023                Rvalue::BinaryOp(BinOp::Eq, Box::new((copy(Place::from(cur)), copy(len.into())))),
1024            )],
1025            is_cleanup: unwind.is_cleanup(),
1026            terminator: Some(Terminator {
1027                source_info: self.source_info,
1028                kind: TerminatorKind::if_(move_(can_go), succ, drop_block),
1029            }),
1030        };
1031        let loop_block = self.elaborator.patch().new_block(loop_block);
1032
1033        let place = tcx.mk_place_deref(ptr);
1034        if self.tcx().features().async_drop()
1035            && self.elaborator.body().coroutine.is_some()
1036            && self.elaborator.allow_async_drops()
1037            && !unwind.is_cleanup()
1038            && ety.needs_async_drop(self.tcx(), self.elaborator.typing_env())
1039        {
1040            self.build_async_drop(
1041                place,
1042                ety,
1043                Some(drop_block),
1044                loop_block,
1045                unwind,
1046                dropline,
1047                false,
1048            );
1049        } else {
1050            self.elaborator.patch().patch_terminator(
1051                drop_block,
1052                TerminatorKind::Drop {
1053                    place,
1054                    target: loop_block,
1055                    unwind: unwind.into_action(),
1056                    replace: false,
1057                    drop: None,
1058                    async_fut: None,
1059                },
1060            );
1061        }
1062        loop_block
1063    }
1064
1065    fn open_drop_for_array(
1066        &mut self,
1067        array_ty: Ty<'tcx>,
1068        ety: Ty<'tcx>,
1069        opt_size: Option<u64>,
1070    ) -> BasicBlock {
1071        debug!("open_drop_for_array({:?}, {:?}, {:?})", array_ty, ety, opt_size);
1072        let tcx = self.tcx();
1073
1074        if let Some(size) = opt_size {
1075            enum ProjectionKind<Path> {
1076                Drop(std::ops::Range<u64>),
1077                Keep(u64, Path),
1078            }
1079            // Previously, we'd make a projection for every element in the array and create a drop
1080            // ladder if any `array_subpath` was `Some`, i.e. moving out with an array pattern.
1081            // This caused huge memory usage when generating the drops for large arrays, so we instead
1082            // record the *subslices* which are dropped and the *indexes* which are kept
1083            let mut drop_ranges = vec![];
1084            let mut dropping = true;
1085            let mut start = 0;
1086            for i in 0..size {
1087                let path = self.elaborator.array_subpath(self.path, i, size);
1088                if dropping && path.is_some() {
1089                    drop_ranges.push(ProjectionKind::Drop(start..i));
1090                    dropping = false;
1091                } else if !dropping && path.is_none() {
1092                    dropping = true;
1093                    start = i;
1094                }
1095                if let Some(path) = path {
1096                    drop_ranges.push(ProjectionKind::Keep(i, path));
1097                }
1098            }
1099            if !drop_ranges.is_empty() {
1100                if dropping {
1101                    drop_ranges.push(ProjectionKind::Drop(start..size));
1102                }
1103                let fields = drop_ranges
1104                    .iter()
1105                    .rev()
1106                    .map(|p| {
1107                        let (project, path) = match p {
1108                            ProjectionKind::Drop(r) => (
1109                                ProjectionElem::Subslice {
1110                                    from: r.start,
1111                                    to: r.end,
1112                                    from_end: false,
1113                                },
1114                                None,
1115                            ),
1116                            &ProjectionKind::Keep(offset, path) => (
1117                                ProjectionElem::ConstantIndex {
1118                                    offset,
1119                                    min_length: size,
1120                                    from_end: false,
1121                                },
1122                                Some(path),
1123                            ),
1124                        };
1125                        (tcx.mk_place_elem(self.place, project), path)
1126                    })
1127                    .collect::<Vec<_>>();
1128                let (succ, unwind, dropline) = self.drop_ladder_bottom();
1129                return self.drop_ladder(fields, succ, unwind, dropline).0;
1130            }
1131        }
1132
1133        let array_ptr_ty = Ty::new_mut_ptr(tcx, array_ty);
1134        let array_ptr = self.new_temp(array_ptr_ty);
1135
1136        let slice_ty = Ty::new_slice(tcx, ety);
1137        let slice_ptr_ty = Ty::new_mut_ptr(tcx, slice_ty);
1138        let slice_ptr = self.new_temp(slice_ptr_ty);
1139
1140        let mut delegate_block = BasicBlockData {
1141            statements: vec![
1142                self.assign(Place::from(array_ptr), Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
1143                self.assign(
1144                    Place::from(slice_ptr),
1145                    Rvalue::Cast(
1146                        CastKind::PointerCoercion(
1147                            PointerCoercion::Unsize,
1148                            CoercionSource::Implicit,
1149                        ),
1150                        Operand::Move(Place::from(array_ptr)),
1151                        slice_ptr_ty,
1152                    ),
1153                ),
1154            ],
1155            is_cleanup: self.unwind.is_cleanup(),
1156            terminator: None,
1157        };
1158
1159        let array_place = mem::replace(
1160            &mut self.place,
1161            Place::from(slice_ptr).project_deeper(&[PlaceElem::Deref], tcx),
1162        );
1163        let slice_block = self.drop_loop_trio_for_slice(ety);
1164        self.place = array_place;
1165
1166        delegate_block.terminator = Some(Terminator {
1167            source_info: self.source_info,
1168            kind: TerminatorKind::Goto { target: slice_block },
1169        });
1170        self.elaborator.patch().new_block(delegate_block)
1171    }
1172
1173    /// Creates a trio of drop-loops of `place`, which drops its contents, even
1174    /// in the case of 1 panic or in the case of coroutine drop
1175    fn drop_loop_trio_for_slice(&mut self, ety: Ty<'tcx>) -> BasicBlock {
1176        debug!("drop_loop_trio_for_slice({:?})", ety);
1177        let tcx = self.tcx();
1178        let len = self.new_temp(tcx.types.usize);
1179        let cur = self.new_temp(tcx.types.usize);
1180
1181        let unwind = self
1182            .unwind
1183            .map(|unwind| self.drop_loop(unwind, cur, len, ety, Unwind::InCleanup, None));
1184
1185        let dropline =
1186            self.dropline.map(|dropline| self.drop_loop(dropline, cur, len, ety, unwind, None));
1187
1188        let loop_block = self.drop_loop(self.succ, cur, len, ety, unwind, dropline);
1189
1190        let [PlaceElem::Deref] = self.place.projection.as_slice() else {
1191            span_bug!(
1192                self.source_info.span,
1193                "Expected place for slice drop shim to be *_n, but it's {:?}",
1194                self.place,
1195            );
1196        };
1197
1198        let zero = self.constant_usize(0);
1199        let block = BasicBlockData {
1200            statements: vec![
1201                self.assign(
1202                    len.into(),
1203                    Rvalue::UnaryOp(
1204                        UnOp::PtrMetadata,
1205                        Operand::Copy(Place::from(self.place.local)),
1206                    ),
1207                ),
1208                self.assign(cur.into(), Rvalue::Use(zero)),
1209            ],
1210            is_cleanup: unwind.is_cleanup(),
1211            terminator: Some(Terminator {
1212                source_info: self.source_info,
1213                kind: TerminatorKind::Goto { target: loop_block },
1214            }),
1215        };
1216
1217        let drop_block = self.elaborator.patch().new_block(block);
1218        // FIXME(#34708): handle partially-dropped array/slice elements.
1219        let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
1220        self.drop_flag_test_block(reset_block, self.succ, unwind)
1221    }
1222
1223    /// The slow-path - create an "open", elaborated drop for a type
1224    /// which is moved-out-of only partially, and patch `bb` to a jump
1225    /// to it. This must not be called on ADTs with a destructor,
1226    /// as these can't be moved-out-of, except for `Box<T>`, which is
1227    /// special-cased.
1228    ///
1229    /// This creates a "drop ladder" that drops the needed fields of the
1230    /// ADT, both in the success case or if one of the destructors fail.
1231    fn open_drop(&mut self) -> BasicBlock {
1232        let ty = self.place_ty(self.place);
1233        match ty.kind() {
1234            ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()),
1235            ty::CoroutineClosure(_, args) => {
1236                self.open_drop_for_tuple(args.as_coroutine_closure().upvar_tys())
1237            }
1238            // Note that `elaborate_drops` only drops the upvars of a coroutine,
1239            // and this is ok because `open_drop` here can only be reached
1240            // within that own coroutine's resume function.
1241            // This should only happen for the self argument on the resume function.
1242            // It effectively only contains upvars until the coroutine transformation runs.
1243            // See librustc_body/transform/coroutine.rs for more details.
1244            ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()),
1245            ty::Tuple(fields) => self.open_drop_for_tuple(fields),
1246            ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
1247            ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
1248            ty::Array(ety, size) => {
1249                let size = size.try_to_target_usize(self.tcx());
1250                self.open_drop_for_array(ty, *ety, size)
1251            }
1252            ty::Slice(ety) => self.drop_loop_trio_for_slice(*ety),
1253
1254            _ => span_bug!(self.source_info.span, "open drop from non-ADT `{:?}`", ty),
1255        }
1256    }
1257
1258    fn complete_drop(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1259        debug!("complete_drop(succ={:?}, unwind={:?})", succ, unwind);
1260
1261        let drop_block = self.drop_block(succ, unwind);
1262
1263        self.drop_flag_test_block(drop_block, succ, unwind)
1264    }
1265
1266    /// Creates a block that resets the drop flag. If `mode` is deep, all children drop flags will
1267    /// also be cleared.
1268    fn drop_flag_reset_block(
1269        &mut self,
1270        mode: DropFlagMode,
1271        succ: BasicBlock,
1272        unwind: Unwind,
1273    ) -> BasicBlock {
1274        debug!("drop_flag_reset_block({:?},{:?})", self, mode);
1275
1276        if unwind.is_cleanup() {
1277            // The drop flag isn't read again on the unwind path, so don't
1278            // bother setting it.
1279            return succ;
1280        }
1281        let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
1282        let block_start = Location { block, statement_index: 0 };
1283        self.elaborator.clear_drop_flag(block_start, self.path, mode);
1284        block
1285    }
1286
1287    fn elaborated_drop_block(&mut self) -> BasicBlock {
1288        debug!("elaborated_drop_block({:?})", self);
1289        let blk = self.drop_block_simple(self.succ, self.unwind);
1290        self.elaborate_drop(blk);
1291        blk
1292    }
1293
1294    fn drop_block_simple(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1295        let block = TerminatorKind::Drop {
1296            place: self.place,
1297            target,
1298            unwind: unwind.into_action(),
1299            replace: false,
1300            drop: self.dropline,
1301            async_fut: None,
1302        };
1303        self.new_block(unwind, block)
1304    }
1305
1306    fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1307        let drop_ty = self.place_ty(self.place);
1308        if self.tcx().features().async_drop()
1309            && self.elaborator.body().coroutine.is_some()
1310            && self.elaborator.allow_async_drops()
1311            && !unwind.is_cleanup()
1312            && drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
1313        {
1314            self.build_async_drop(
1315                self.place,
1316                drop_ty,
1317                None,
1318                self.succ,
1319                unwind,
1320                self.dropline,
1321                false,
1322            )
1323        } else {
1324            let block = TerminatorKind::Drop {
1325                place: self.place,
1326                target,
1327                unwind: unwind.into_action(),
1328                replace: false,
1329                drop: None,
1330                async_fut: None,
1331            };
1332            self.new_block(unwind, block)
1333        }
1334    }
1335
1336    fn goto_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1337        let block = TerminatorKind::Goto { target };
1338        self.new_block(unwind, block)
1339    }
1340
1341    /// Returns the block to jump to in order to test the drop flag and execute the drop.
1342    ///
1343    /// Depending on the required `DropStyle`, this might be a generated block with an `if`
1344    /// terminator (for dynamic/open drops), or it might be `on_set` or `on_unset` itself, in case
1345    /// the drop can be statically determined.
1346    fn drop_flag_test_block(
1347        &mut self,
1348        on_set: BasicBlock,
1349        on_unset: BasicBlock,
1350        unwind: Unwind,
1351    ) -> BasicBlock {
1352        let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
1353        debug!(
1354            "drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
1355            self, on_set, on_unset, unwind, style
1356        );
1357
1358        match style {
1359            DropStyle::Dead => on_unset,
1360            DropStyle::Static => on_set,
1361            DropStyle::Conditional | DropStyle::Open => {
1362                let flag = self.elaborator.get_drop_flag(self.path).unwrap();
1363                let term = TerminatorKind::if_(flag, on_set, on_unset);
1364                self.new_block(unwind, term)
1365            }
1366        }
1367    }
1368
1369    fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
1370        self.elaborator.patch().new_block(BasicBlockData {
1371            statements: vec![],
1372            terminator: Some(Terminator { source_info: self.source_info, kind: k }),
1373            is_cleanup: unwind.is_cleanup(),
1374        })
1375    }
1376
1377    fn new_block_with_statements(
1378        &mut self,
1379        unwind: Unwind,
1380        statements: Vec<Statement<'tcx>>,
1381        k: TerminatorKind<'tcx>,
1382    ) -> BasicBlock {
1383        self.elaborator.patch().new_block(BasicBlockData {
1384            statements,
1385            terminator: Some(Terminator { source_info: self.source_info, kind: k }),
1386            is_cleanup: unwind.is_cleanup(),
1387        })
1388    }
1389
1390    fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
1391        self.elaborator.patch().new_temp(ty, self.source_info.span)
1392    }
1393
1394    fn constant_usize(&self, val: u16) -> Operand<'tcx> {
1395        Operand::Constant(Box::new(ConstOperand {
1396            span: self.source_info.span,
1397            user_ty: None,
1398            const_: Const::from_usize(self.tcx(), val.into()),
1399        }))
1400    }
1401
1402    fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
1403        Statement {
1404            source_info: self.source_info,
1405            kind: StatementKind::Assign(Box::new((lhs, rhs))),
1406        }
1407    }
1408}