Skip to main content

rustc_mir_transform/
copy_prop.rs

1use rustc_index::IndexSlice;
2use rustc_index::bit_set::DenseBitSet;
3use rustc_middle::mir::visit::*;
4use rustc_middle::mir::*;
5use rustc_middle::ty::TyCtxt;
6use rustc_mir_dataflow::{Analysis, ResultsCursor};
7use tracing::{debug, instrument};
8
9use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
10
11/// Unify locals that copy each other.
12///
13/// We consider patterns of the form
14///   _a = rvalue
15///   _b = move? _a
16///   _c = move? _a
17///   _d = move? _c
18/// where each of the locals is only assigned once.
19///
20/// We want to replace all those locals by `_a` (the "head"), either copied or moved.
21pub(super) struct CopyProp;
22
23impl<'tcx> crate::MirPass<'tcx> for CopyProp {
24    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
25        sess.mir_opt_level() >= 1
26    }
27
28    #[instrument(level = "trace", skip(self, tcx, body))]
29    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
30        debug!(def_id = ?body.source.def_id());
31
32        let typing_env = body.typing_env(tcx);
33        let ssa = SsaLocals::new(tcx, body, typing_env);
34
35        debug!(borrowed_locals = ?ssa.borrowed_locals());
36        debug!(copy_classes = ?ssa.copy_classes());
37
38        let mut any_replacement = false;
39        // Locals that participate in copy propagation either as a source or a destination.
40        let mut unified = DenseBitSet::new_empty(body.local_decls.len());
41        let mut storage_to_remove = DenseBitSet::new_empty(body.local_decls.len());
42
43        for (local, &head) in ssa.copy_classes().iter_enumerated() {
44            if local != head {
45                any_replacement = true;
46                storage_to_remove.insert(head);
47                unified.insert(head);
48                unified.insert(local);
49            }
50        }
51
52        if !any_replacement {
53            return;
54        }
55
56        // When emitting storage statements, we want to retain the head locals' storage statements,
57        // as this enables better optimizations. For each local use location, we mark the head for storage removal
58        // only if the head might be uninitialized at that point, or if the local is borrowed
59        // (since we cannot easily determine when it's used).
60        let storage_to_remove = if tcx.sess.emit_lifetime_markers() {
61            storage_to_remove.clear();
62
63            // If the local is borrowed, we cannot easily determine if it is used, so we have to remove the storage statements.
64            let borrowed_locals = ssa.borrowed_locals();
65
66            for (local, &head) in ssa.copy_classes().iter_enumerated() {
67                if local != head && borrowed_locals.contains(local) {
68                    storage_to_remove.insert(head);
69                }
70            }
71
72            let maybe_uninit = MaybeUninitializedLocals
73                .iterate_to_fixpoint(tcx, body, Some("mir_opt::copy_prop"))
74                .into_results_cursor(body);
75
76            let mut storage_checker = StorageChecker {
77                maybe_uninit,
78                copy_classes: ssa.copy_classes(),
79                storage_to_remove,
80            };
81
82            for (bb, data) in traversal::reachable(body) {
83                storage_checker.visit_basic_block_data(bb, data);
84            }
85
86            storage_checker.storage_to_remove
87        } else {
88            // Remove the storage statements of all the head locals.
89            storage_to_remove
90        };
91
92        debug!(?storage_to_remove);
93
94        Replacer { tcx, copy_classes: ssa.copy_classes(), unified, storage_to_remove }
95            .visit_body_preserves_cfg(body);
96
97        crate::simplify::remove_unused_definitions(body);
98    }
99
100    fn is_required(&self) -> bool {
101        false
102    }
103}
104
105/// Utility to help performing substitution: for all key-value pairs in `copy_classes`,
106/// all occurrences of the key get replaced by the value.
107struct Replacer<'a, 'tcx> {
108    tcx: TyCtxt<'tcx>,
109    unified: DenseBitSet<Local>,
110    storage_to_remove: DenseBitSet<Local>,
111    copy_classes: &'a IndexSlice<Local, Local>,
112}
113
114impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
115    fn tcx(&self) -> TyCtxt<'tcx> {
116        self.tcx
117    }
118
119    #[tracing::instrument(level = "trace", skip(self))]
120    fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
121        let new_local = self.copy_classes[*local];
122        match ctxt {
123            // Do not modify the local in storage statements.
124            PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead) => {}
125            // We access the value.
126            _ => *local = new_local,
127        }
128    }
129
130    #[tracing::instrument(level = "trace", skip(self))]
131    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
132        if let Operand::Move(place) = *operand
133            // A move out of a projection of a copy is equivalent to a copy of the original
134            // projection.
135            && !place.is_indirect_first_projection()
136            && self.unified.contains(place.local)
137        {
138            *operand = Operand::Copy(place);
139        }
140        self.super_operand(operand, loc);
141    }
142
143    #[tracing::instrument(level = "trace", skip(self))]
144    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
145        // When removing storage statements, we need to remove both (#107511).
146        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
147            && self.storage_to_remove.contains(l)
148        {
149            stmt.make_nop(true);
150        }
151
152        self.super_statement(stmt, loc);
153
154        // Do not leave tautological assignments around.
155        if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
156            && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) = *rhs
157            && lhs == rhs
158        {
159            stmt.make_nop(true);
160        }
161    }
162}
163
164// Marks heads of copy classes that are maybe uninitialized at the location of a local
165// as needing storage statement removal.
166struct StorageChecker<'a, 'tcx> {
167    maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
168    copy_classes: &'a IndexSlice<Local, Local>,
169    storage_to_remove: DenseBitSet<Local>,
170}
171
172impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
173    fn visit_local(&mut self, local: Local, context: PlaceContext, loc: Location) {
174        if !context.is_use() {
175            return;
176        }
177
178        let head = self.copy_classes[local];
179
180        // If the local is the head, or if we already marked it for deletion, we do not need to check it.
181        if head == local || self.storage_to_remove.contains(head) {
182            return;
183        }
184
185        self.maybe_uninit.seek_before_primary_effect(loc);
186
187        if self.maybe_uninit.get().contains(head) {
188            debug!(
189                ?loc,
190                ?context,
191                ?local,
192                ?head,
193                "local's head is maybe uninit at this location, marking head for storage statement removal"
194            );
195            self.storage_to_remove.insert(head);
196        }
197    }
198}