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