rustc_mir_transform/
elaborate_drops.rs

1use std::fmt;
2
3use rustc_abi::{FieldIdx, VariantIdx};
4use rustc_index::IndexVec;
5use rustc_index::bit_set::DenseBitSet;
6use rustc_middle::mir::*;
7use rustc_middle::ty::{self, TyCtxt};
8use rustc_mir_dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
9use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
10use rustc_mir_dataflow::{
11    Analysis, DropFlagState, MoveDataTypingEnv, ResultsCursor, on_all_children_bits,
12    on_lookup_result_bits,
13};
14use rustc_span::Span;
15use tracing::{debug, instrument};
16
17use crate::deref_separator::deref_finder;
18use crate::elaborate_drop::{DropElaborator, DropFlagMode, DropStyle, Unwind, elaborate_drop};
19use crate::patch::MirPatch;
20
21/// During MIR building, Drop terminators are inserted in every place where a drop may occur.
22/// However, in this phase, the presence of these terminators does not guarantee that a destructor
23/// will run, as the target of the drop may be uninitialized.
24/// In general, the compiler cannot determine at compile time whether a destructor will run or not.
25///
26/// At a high level, this pass refines Drop to only run the destructor if the
27/// target is initialized. The way this is achieved is by inserting drop flags for every variable
28/// that may be dropped, and then using those flags to determine whether a destructor should run.
29/// Once this is complete, Drop terminators in the MIR correspond to a call to the "drop glue" or
30/// "drop shim" for the type of the dropped place.
31///
32/// This pass relies on dropped places having an associated move path, which is then used to
33/// determine the initialization status of the place and its descendants.
34/// It's worth noting that a MIR containing a Drop without an associated move path is probably ill
35/// formed, as it would allow running a destructor on a place behind a reference:
36///
37/// ```text
38/// fn drop_term<T>(t: &mut T) {
39///     mir! {
40///         {
41///             Drop(*t, exit)
42///         }
43///         exit = {
44///             Return()
45///         }
46///     }
47/// }
48/// ```
49pub(super) struct ElaborateDrops;
50
51impl<'tcx> crate::MirPass<'tcx> for ElaborateDrops {
52    #[instrument(level = "trace", skip(self, tcx, body))]
53    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
54        debug!("elaborate_drops({:?} @ {:?})", body.source, body.span);
55        // FIXME(#132279): This is used during the phase transition from analysis
56        // to runtime, so we have to manually specify the correct typing mode.
57        let typing_env = ty::TypingEnv::post_analysis(tcx, body.source.def_id());
58        // For types that do not need dropping, the behaviour is trivial. So we only need to track
59        // init/uninit for types that do need dropping.
60        let move_data = MoveData::gather_moves(body, tcx, |ty| ty.needs_drop(tcx, typing_env));
61        let elaborate_patch = {
62            let env = MoveDataTypingEnv { move_data, typing_env };
63
64            let mut inits = MaybeInitializedPlaces::new(tcx, body, &env.move_data)
65                .skipping_unreachable_unwind()
66                .iterate_to_fixpoint(tcx, body, Some("elaborate_drops"))
67                .into_results_cursor(body);
68            let dead_unwinds = compute_dead_unwinds(body, &mut inits);
69
70            let uninits = MaybeUninitializedPlaces::new(tcx, body, &env.move_data)
71                .mark_inactive_variants_as_uninit()
72                .skipping_unreachable_unwind(dead_unwinds)
73                .iterate_to_fixpoint(tcx, body, Some("elaborate_drops"))
74                .into_results_cursor(body);
75
76            let drop_flags = IndexVec::from_elem(None, &env.move_data.move_paths);
77            ElaborateDropsCtxt {
78                tcx,
79                body,
80                env: &env,
81                init_data: InitializationData { inits, uninits },
82                drop_flags,
83                patch: MirPatch::new(body),
84            }
85            .elaborate()
86        };
87        elaborate_patch.apply(body);
88        deref_finder(tcx, body);
89    }
90
91    fn is_required(&self) -> bool {
92        true
93    }
94}
95
96/// Records unwind edges which are known to be unreachable, because they are in `drop` terminators
97/// that can't drop anything.
98#[instrument(level = "trace", skip(body, flow_inits), ret)]
99fn compute_dead_unwinds<'a, 'tcx>(
100    body: &'a Body<'tcx>,
101    flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
102) -> DenseBitSet<BasicBlock> {
103    // We only need to do this pass once, because unwind edges can only
104    // reach cleanup blocks, which can't have unwind edges themselves.
105    let mut dead_unwinds = DenseBitSet::new_empty(body.basic_blocks.len());
106    for (bb, bb_data) in body.basic_blocks.iter_enumerated() {
107        let TerminatorKind::Drop { place, unwind: UnwindAction::Cleanup(_), .. } =
108            bb_data.terminator().kind
109        else {
110            continue;
111        };
112
113        flow_inits.seek_before_primary_effect(body.terminator_loc(bb));
114        if flow_inits.analysis().is_unwind_dead(place, flow_inits.get()) {
115            dead_unwinds.insert(bb);
116        }
117    }
118
119    dead_unwinds
120}
121
122struct InitializationData<'a, 'tcx> {
123    inits: ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
124    uninits: ResultsCursor<'a, 'tcx, MaybeUninitializedPlaces<'a, 'tcx>>,
125}
126
127impl InitializationData<'_, '_> {
128    fn seek_before(&mut self, loc: Location) {
129        self.inits.seek_before_primary_effect(loc);
130        self.uninits.seek_before_primary_effect(loc);
131    }
132
133    fn maybe_init_uninit(&self, path: MovePathIndex) -> (bool, bool) {
134        (self.inits.get().contains(path), self.uninits.get().contains(path))
135    }
136}
137
138impl<'a, 'tcx> DropElaborator<'a, 'tcx> for ElaborateDropsCtxt<'a, 'tcx> {
139    type Path = MovePathIndex;
140
141    fn patch_ref(&self) -> &MirPatch<'tcx> {
142        &self.patch
143    }
144
145    fn patch(&mut self) -> &mut MirPatch<'tcx> {
146        &mut self.patch
147    }
148
149    fn body(&self) -> &'a Body<'tcx> {
150        self.body
151    }
152
153    fn tcx(&self) -> TyCtxt<'tcx> {
154        self.tcx
155    }
156
157    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
158        self.env.typing_env
159    }
160
161    fn allow_async_drops(&self) -> bool {
162        true
163    }
164
165    fn terminator_loc(&self, bb: BasicBlock) -> Location {
166        self.patch.terminator_loc(self.body, bb)
167    }
168
169    #[instrument(level = "debug", skip(self), ret)]
170    fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle {
171        let ((maybe_init, maybe_uninit), multipart) = match mode {
172            DropFlagMode::Shallow => (self.init_data.maybe_init_uninit(path), false),
173            DropFlagMode::Deep => {
174                let mut some_maybe_init = false;
175                let mut some_maybe_uninit = false;
176                let mut children_count = 0;
177                on_all_children_bits(self.move_data(), path, |child| {
178                    let (maybe_init, maybe_uninit) = self.init_data.maybe_init_uninit(child);
179                    debug!("elaborate_drop: state({:?}) = {:?}", child, (maybe_init, maybe_uninit));
180                    some_maybe_init |= maybe_init;
181                    some_maybe_uninit |= maybe_uninit;
182                    children_count += 1;
183                });
184                ((some_maybe_init, some_maybe_uninit), children_count != 1)
185            }
186        };
187        match (maybe_init, maybe_uninit, multipart) {
188            (false, _, _) => DropStyle::Dead,
189            (true, false, _) => DropStyle::Static,
190            (true, true, false) => DropStyle::Conditional,
191            (true, true, true) => DropStyle::Open,
192        }
193    }
194
195    fn clear_drop_flag(&mut self, loc: Location, path: Self::Path, mode: DropFlagMode) {
196        match mode {
197            DropFlagMode::Shallow => {
198                self.set_drop_flag(loc, path, DropFlagState::Absent);
199            }
200            DropFlagMode::Deep => {
201                on_all_children_bits(self.move_data(), path, |child| {
202                    self.set_drop_flag(loc, child, DropFlagState::Absent)
203                });
204            }
205        }
206    }
207
208    fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path> {
209        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| match e {
210            ProjectionElem::Field(idx, _) => idx == field,
211            _ => false,
212        })
213    }
214
215    fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path> {
216        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| match e {
217            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
218                debug_assert!(size == min_length, "min_length should be exact for arrays");
219                assert!(!from_end, "from_end should not be used for array element ConstantIndex");
220                offset == index
221            }
222            _ => false,
223        })
224    }
225
226    fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path> {
227        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| {
228            e == ProjectionElem::Deref
229        })
230    }
231
232    fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path> {
233        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| match e {
234            ProjectionElem::Downcast(_, idx) => idx == variant,
235            _ => false,
236        })
237    }
238
239    fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>> {
240        self.drop_flag(path).map(Operand::Copy)
241    }
242}
243
244struct ElaborateDropsCtxt<'a, 'tcx> {
245    tcx: TyCtxt<'tcx>,
246    body: &'a Body<'tcx>,
247    env: &'a MoveDataTypingEnv<'tcx>,
248    init_data: InitializationData<'a, 'tcx>,
249    drop_flags: IndexVec<MovePathIndex, Option<Local>>,
250    patch: MirPatch<'tcx>,
251}
252
253impl fmt::Debug for ElaborateDropsCtxt<'_, '_> {
254    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        Ok(())
256    }
257}
258
259impl<'a, 'tcx> ElaborateDropsCtxt<'a, 'tcx> {
260    fn move_data(&self) -> &'a MoveData<'tcx> {
261        &self.env.move_data
262    }
263
264    fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) {
265        let patch = &mut self.patch;
266        debug!("create_drop_flag({:?})", self.body.span);
267        self.drop_flags[index].get_or_insert_with(|| patch.new_temp(self.tcx.types.bool, span));
268    }
269
270    fn drop_flag(&mut self, index: MovePathIndex) -> Option<Place<'tcx>> {
271        self.drop_flags[index].map(Place::from)
272    }
273
274    /// create a patch that elaborates all drops in the input
275    /// MIR.
276    fn elaborate(mut self) -> MirPatch<'tcx> {
277        self.collect_drop_flags();
278
279        self.elaborate_drops();
280
281        self.drop_flags_on_init();
282        self.drop_flags_for_fn_rets();
283        self.drop_flags_for_args();
284        self.drop_flags_for_locs();
285
286        self.patch
287    }
288
289    fn collect_drop_flags(&mut self) {
290        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
291            let terminator = data.terminator();
292            let TerminatorKind::Drop { ref place, .. } = terminator.kind else { continue };
293
294            let path = self.move_data().rev_lookup.find(place.as_ref());
295            debug!("collect_drop_flags: {:?}, place {:?} ({:?})", bb, place, path);
296
297            match path {
298                LookupResult::Exact(path) => {
299                    self.init_data.seek_before(self.body.terminator_loc(bb));
300                    on_all_children_bits(self.move_data(), path, |child| {
301                        let (maybe_init, maybe_uninit) = self.init_data.maybe_init_uninit(child);
302                        debug!(
303                            "collect_drop_flags: collecting {:?} from {:?}@{:?} - {:?}",
304                            child,
305                            place,
306                            path,
307                            (maybe_init, maybe_uninit)
308                        );
309                        if maybe_init && maybe_uninit {
310                            self.create_drop_flag(child, terminator.source_info.span)
311                        }
312                    });
313                }
314                LookupResult::Parent(None) => {}
315                LookupResult::Parent(Some(parent)) => {
316                    if self.body.local_decls[place.local].is_deref_temp() {
317                        continue;
318                    }
319
320                    self.init_data.seek_before(self.body.terminator_loc(bb));
321                    let (_maybe_init, maybe_uninit) = self.init_data.maybe_init_uninit(parent);
322                    if maybe_uninit {
323                        self.tcx.dcx().span_delayed_bug(
324                            terminator.source_info.span,
325                            format!(
326                                "drop of untracked, uninitialized value {bb:?}, place {place:?} ({path:?})"
327                            ),
328                        );
329                    }
330                }
331            };
332        }
333    }
334
335    fn elaborate_drops(&mut self) {
336        // This function should mirror what `collect_drop_flags` does.
337        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
338            let terminator = data.terminator();
339            let TerminatorKind::Drop { place, target, unwind, replace, drop, async_fut: _ } =
340                terminator.kind
341            else {
342                continue;
343            };
344
345            // This place does not need dropping. It does not have an associated move-path, so the
346            // match below will conservatively keep an unconditional drop. As that drop is useless,
347            // just remove it here and now.
348            if !place
349                .ty(&self.body.local_decls, self.tcx)
350                .ty
351                .needs_drop(self.tcx, self.typing_env())
352            {
353                self.patch.patch_terminator(bb, TerminatorKind::Goto { target });
354                continue;
355            }
356
357            let path = self.move_data().rev_lookup.find(place.as_ref());
358            match path {
359                LookupResult::Exact(path) => {
360                    let unwind = match unwind {
361                        _ if data.is_cleanup => Unwind::InCleanup,
362                        UnwindAction::Cleanup(cleanup) => Unwind::To(cleanup),
363                        UnwindAction::Continue => Unwind::To(self.patch.resume_block()),
364                        UnwindAction::Unreachable => {
365                            Unwind::To(self.patch.unreachable_cleanup_block())
366                        }
367                        UnwindAction::Terminate(reason) => {
368                            debug_assert_ne!(
369                                reason,
370                                UnwindTerminateReason::InCleanup,
371                                "we are not in a cleanup block, InCleanup reason should be impossible"
372                            );
373                            Unwind::To(self.patch.terminate_block(reason))
374                        }
375                    };
376                    self.init_data.seek_before(self.body.terminator_loc(bb));
377                    elaborate_drop(
378                        self,
379                        terminator.source_info,
380                        place,
381                        path,
382                        target,
383                        unwind,
384                        bb,
385                        drop,
386                    )
387                }
388                LookupResult::Parent(None) => {}
389                LookupResult::Parent(Some(_)) => {
390                    if !replace {
391                        self.tcx.dcx().span_bug(
392                            terminator.source_info.span,
393                            format!("drop of untracked value {bb:?}"),
394                        );
395                    }
396                    // A drop and replace behind a pointer/array/whatever.
397                    // The borrow checker requires that these locations are initialized before the
398                    // assignment, so we just leave an unconditional drop.
399                    assert!(!data.is_cleanup);
400                }
401            }
402        }
403    }
404
405    fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> {
406        Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
407            span,
408            user_ty: None,
409            const_: Const::from_bool(self.tcx, val),
410        })))
411    }
412
413    fn set_drop_flag(&mut self, loc: Location, path: MovePathIndex, val: DropFlagState) {
414        if let Some(flag) = self.drop_flags[path] {
415            let span = self.patch.source_info_for_location(self.body, loc).span;
416            let val = self.constant_bool(span, val.value());
417            self.patch.add_assign(loc, Place::from(flag), val);
418        }
419    }
420
421    fn drop_flags_on_init(&mut self) {
422        let loc = Location::START;
423        let span = self.patch.source_info_for_location(self.body, loc).span;
424        let false_ = self.constant_bool(span, false);
425        for flag in self.drop_flags.iter().flatten() {
426            self.patch.add_assign(loc, Place::from(*flag), false_.clone());
427        }
428    }
429
430    fn drop_flags_for_fn_rets(&mut self) {
431        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
432            if let TerminatorKind::Call {
433                destination,
434                target: Some(tgt),
435                unwind: UnwindAction::Cleanup(_),
436                ..
437            } = data.terminator().kind
438            {
439                assert!(!self.patch.is_term_patched(bb));
440
441                let loc = Location { block: tgt, statement_index: 0 };
442                let path = self.move_data().rev_lookup.find(destination.as_ref());
443                on_lookup_result_bits(self.move_data(), path, |child| {
444                    self.set_drop_flag(loc, child, DropFlagState::Present)
445                });
446            }
447        }
448    }
449
450    fn drop_flags_for_args(&mut self) {
451        let loc = Location::START;
452        rustc_mir_dataflow::drop_flag_effects_for_function_entry(
453            self.body,
454            &self.env.move_data,
455            |path, ds| {
456                self.set_drop_flag(loc, path, ds);
457            },
458        )
459    }
460
461    fn drop_flags_for_locs(&mut self) {
462        // We intentionally iterate only over the *old* basic blocks.
463        //
464        // Basic blocks created by drop elaboration update their
465        // drop flags by themselves, to avoid the drop flags being
466        // clobbered before they are read.
467
468        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
469            debug!("drop_flags_for_locs({:?})", data);
470            for i in 0..(data.statements.len() + 1) {
471                debug!("drop_flag_for_locs: stmt {}", i);
472                if i == data.statements.len() {
473                    match data.terminator().kind {
474                        TerminatorKind::Drop { .. } => {
475                            // drop elaboration should handle that by itself
476                            continue;
477                        }
478                        TerminatorKind::UnwindResume => {
479                            // It is possible for `Resume` to be patched
480                            // (in particular it can be patched to be replaced with
481                            // a Goto; see `MirPatch::new`).
482                        }
483                        _ => {
484                            assert!(!self.patch.is_term_patched(bb));
485                        }
486                    }
487                }
488                let loc = Location { block: bb, statement_index: i };
489                rustc_mir_dataflow::drop_flag_effects_for_location(
490                    self.body,
491                    &self.env.move_data,
492                    loc,
493                    |path, ds| self.set_drop_flag(loc, path, ds),
494                )
495            }
496
497            // There may be a critical edge after this call,
498            // so mark the return as initialized *before* the
499            // call.
500            if let TerminatorKind::Call {
501                destination,
502                target: Some(_),
503                unwind:
504                    UnwindAction::Continue | UnwindAction::Unreachable | UnwindAction::Terminate(_),
505                ..
506            } = data.terminator().kind
507            {
508                assert!(!self.patch.is_term_patched(bb));
509
510                let loc = Location { block: bb, statement_index: data.statements.len() };
511                let path = self.move_data().rev_lookup.find(destination.as_ref());
512                on_lookup_result_bits(self.move_data(), path, |child| {
513                    self.set_drop_flag(loc, child, DropFlagState::Present)
514                });
515            }
516        }
517    }
518}