rustc_mir_transform/
remove_noop_landing_pads.rs

1use rustc_index::bit_set::DenseBitSet;
2use rustc_middle::mir::*;
3use rustc_middle::ty::TyCtxt;
4use tracing::{debug, instrument};
5
6use crate::patch::MirPatch;
7
8/// A pass that removes noop landing pads and replaces jumps to them with
9/// `UnwindAction::Continue`. This is important because otherwise LLVM generates
10/// terrible code for these.
11pub(super) struct RemoveNoopLandingPads;
12
13impl<'tcx> crate::MirPass<'tcx> for RemoveNoopLandingPads {
14    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
15        sess.panic_strategy().unwinds()
16    }
17
18    #[instrument(level = "debug", skip(self, _tcx, body))]
19    fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
20        let def_id = body.source.def_id();
21        debug!(?def_id);
22
23        // Skip the pass if there are no blocks with a resume terminator.
24        let has_resume = body
25            .basic_blocks
26            .iter_enumerated()
27            .any(|(_bb, block)| matches!(block.terminator().kind, TerminatorKind::UnwindResume));
28        if !has_resume {
29            debug!("no resume block in MIR");
30            return;
31        }
32
33        let mut nop_landing_pads = DenseBitSet::new_empty(body.basic_blocks.len());
34
35        // This is a post-order traversal, so that if A post-dominates B
36        // then A will be visited before B.
37        for (bb, bbdata) in traversal::postorder(body) {
38            let is_nop_landing_pad = self.is_nop_landing_pad(bbdata, &nop_landing_pads);
39            debug!("is_nop_landing_pad({bb:?}) = {is_nop_landing_pad}");
40            if is_nop_landing_pad {
41                nop_landing_pads.insert(bb);
42            }
43        }
44
45        if nop_landing_pads.is_empty() {
46            debug!("no nop landing pads in MIR");
47            return;
48        }
49
50        // make sure there's a resume block without any statements
51        let resume_block = {
52            let mut patch = MirPatch::new(body);
53            let resume_block = patch.resume_block();
54            patch.apply(body);
55            resume_block
56        };
57        debug!(?resume_block);
58
59        let basic_blocks = body.basic_blocks.as_mut();
60        for (bb, bbdata) in basic_blocks.iter_enumerated_mut() {
61            debug!("processing {:?}", bb);
62
63            if let Some(unwind) = bbdata.terminator_mut().unwind_mut()
64                && let UnwindAction::Cleanup(unwind_bb) = *unwind
65                && nop_landing_pads.contains(unwind_bb)
66            {
67                debug!("    removing noop landing pad");
68                *unwind = UnwindAction::Continue;
69            }
70
71            bbdata.terminator_mut().successors_mut(|target| {
72                if *target != resume_block && nop_landing_pads.contains(*target) {
73                    debug!("    folding noop jump to {:?} to resume block", target);
74                    *target = resume_block;
75                }
76            });
77        }
78    }
79
80    fn is_required(&self) -> bool {
81        true
82    }
83}
84
85impl RemoveNoopLandingPads {
86    fn is_nop_landing_pad(
87        &self,
88        bbdata: &BasicBlockData<'_>,
89        nop_landing_pads: &DenseBitSet<BasicBlock>,
90    ) -> bool {
91        for stmt in &bbdata.statements {
92            match &stmt.kind {
93                StatementKind::FakeRead(..)
94                | StatementKind::StorageLive(_)
95                | StatementKind::StorageDead(_)
96                | StatementKind::PlaceMention(..)
97                | StatementKind::AscribeUserType(..)
98                | StatementKind::Coverage(..)
99                | StatementKind::ConstEvalCounter
100                | StatementKind::BackwardIncompatibleDropHint { .. }
101                | StatementKind::Nop => {
102                    // These are all noops in a landing pad
103                }
104
105                StatementKind::Assign(box (place, Rvalue::Use(_) | Rvalue::Discriminant(_))) => {
106                    if place.as_local().is_some() {
107                        // Writing to a local (e.g., a drop flag) does not
108                        // turn a landing pad to a non-nop
109                    } else {
110                        return false;
111                    }
112                }
113
114                StatementKind::Assign { .. }
115                | StatementKind::SetDiscriminant { .. }
116                | StatementKind::Intrinsic(..)
117                | StatementKind::Retag { .. } => {
118                    return false;
119                }
120            }
121        }
122
123        let terminator = bbdata.terminator();
124        match terminator.kind {
125            TerminatorKind::Goto { .. }
126            | TerminatorKind::UnwindResume
127            | TerminatorKind::SwitchInt { .. }
128            | TerminatorKind::FalseEdge { .. }
129            | TerminatorKind::FalseUnwind { .. } => {
130                terminator.successors().all(|succ| nop_landing_pads.contains(succ))
131            }
132            TerminatorKind::CoroutineDrop
133            | TerminatorKind::Yield { .. }
134            | TerminatorKind::Return
135            | TerminatorKind::UnwindTerminate(_)
136            | TerminatorKind::Unreachable
137            | TerminatorKind::Call { .. }
138            | TerminatorKind::TailCall { .. }
139            | TerminatorKind::Assert { .. }
140            | TerminatorKind::Drop { .. }
141            | TerminatorKind::InlineAsm { .. } => false,
142        }
143    }
144}