]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir_transform/src/copy_prop.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_mir_transform / src / copy_prop.rs
CommitLineData
9ffffee4 1use rustc_index::bit_set::BitSet;
49aad941 2use rustc_index::IndexSlice;
9ffffee4
FG
3use rustc_middle::mir::visit::*;
4use rustc_middle::mir::*;
5use rustc_middle::ty::TyCtxt;
6use rustc_mir_dataflow::impls::borrowed_locals;
7
8use crate::ssa::SsaLocals;
9use crate::MirPass;
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`, either copied or moved.
21pub struct CopyProp;
22
23impl<'tcx> 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 propagate_ssa(tcx, body);
32 }
33}
34
35fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
9ffffee4 36 let borrowed_locals = borrowed_locals(body);
49aad941 37 let ssa = SsaLocals::new(body);
9ffffee4
FG
38
39 let fully_moved = fully_moved_locals(&ssa, body);
40 debug!(?fully_moved);
41
42 let mut storage_to_remove = BitSet::new_empty(fully_moved.domain_size());
43 for (local, &head) in ssa.copy_classes().iter_enumerated() {
44 if local != head {
45 storage_to_remove.insert(head);
46 }
47 }
48
49 let any_replacement = ssa.copy_classes().iter_enumerated().any(|(l, &h)| l != h);
50
51 Replacer {
52 tcx,
53 copy_classes: &ssa.copy_classes(),
54 fully_moved,
55 borrowed_locals,
56 storage_to_remove,
57 }
58 .visit_body_preserves_cfg(body);
59
60 if any_replacement {
61 crate::simplify::remove_unused_definitions(body);
62 }
63}
64
65/// `SsaLocals` computed equivalence classes between locals considering copy/move assignments.
66///
67/// This function also returns whether all the `move?` in the pattern are `move` and not copies.
68/// A local which is in the bitset can be replaced by `move _a`. Otherwise, it must be
69/// replaced by `copy _a`, as we cannot move multiple times from `_a`.
70///
71/// If an operand copies `_c`, it must happen before the assignment `_d = _c`, otherwise it is UB.
72/// This means that replacing it by a copy of `_a` if ok, since this copy happens before `_c` is
73/// moved, and therefore that `_d` is moved.
74#[instrument(level = "trace", skip(ssa, body))]
75fn fully_moved_locals(ssa: &SsaLocals, body: &Body<'_>) -> BitSet<Local> {
76 let mut fully_moved = BitSet::new_filled(body.local_decls.len());
77
49aad941 78 for (_, rvalue, _) in ssa.assignments(body) {
9ffffee4
FG
79 let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place))
80 = rvalue
81 else { continue };
82
83 let Some(rhs) = place.as_local() else { continue };
84 if !ssa.is_ssa(rhs) {
85 continue;
86 }
87
88 if let Rvalue::Use(Operand::Copy(_)) | Rvalue::CopyForDeref(_) = rvalue {
89 fully_moved.remove(rhs);
90 }
91 }
92
93 ssa.meet_copy_equivalence(&mut fully_moved);
94
95 fully_moved
96}
97
98/// Utility to help performing substitution of `*pattern` by `target`.
99struct Replacer<'a, 'tcx> {
100 tcx: TyCtxt<'tcx>,
101 fully_moved: BitSet<Local>,
102 storage_to_remove: BitSet<Local>,
103 borrowed_locals: BitSet<Local>,
353b0b11 104 copy_classes: &'a IndexSlice<Local, Local>,
9ffffee4
FG
105}
106
107impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
108 fn tcx(&self) -> TyCtxt<'tcx> {
109 self.tcx
110 }
111
112 fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
113 let new_local = self.copy_classes[*local];
114 match ctxt {
115 // Do not modify the local in storage statements.
116 PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead) => {}
117 // The local should have been marked as non-SSA.
118 PlaceContext::MutatingUse(_) => assert_eq!(*local, new_local),
119 // We access the value.
120 _ => *local = new_local,
121 }
122 }
123
124 fn visit_place(&mut self, place: &mut Place<'tcx>, ctxt: PlaceContext, loc: Location) {
125 if let Some(new_projection) = self.process_projection(&place.projection, loc) {
126 place.projection = self.tcx().mk_place_elems(&new_projection);
127 }
128
129 let observes_address = match ctxt {
130 PlaceContext::NonMutatingUse(
131 NonMutatingUseContext::SharedBorrow
132 | NonMutatingUseContext::ShallowBorrow
9ffffee4
FG
133 | NonMutatingUseContext::AddressOf,
134 ) => true,
135 // For debuginfo, merging locals is ok.
136 PlaceContext::NonUse(NonUseContext::VarDebugInfo) => {
137 self.borrowed_locals.contains(place.local)
138 }
139 _ => false,
140 };
141 if observes_address && !place.is_indirect() {
142 // We observe the address of `place.local`. Do not replace it.
143 } else {
144 self.visit_local(
145 &mut place.local,
146 PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
147 loc,
148 )
149 }
150 }
151
152 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
153 if let Operand::Move(place) = *operand
154 // A move out of a projection of a copy is equivalent to a copy of the original projection.
155 && !place.has_deref()
156 && !self.fully_moved.contains(place.local)
157 {
158 *operand = Operand::Copy(place);
159 }
160 self.super_operand(operand, loc);
161 }
162
163 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
49aad941
FG
164 // When removing storage statements, we need to remove both (#107511).
165 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
166 && self.storage_to_remove.contains(l)
167 {
168 stmt.make_nop();
169 return
170 }
171
172 self.super_statement(stmt, loc);
173
174 // Do not leave tautological assignments around.
175 if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
176 && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) | Rvalue::CopyForDeref(rhs) = *rhs
177 && lhs == rhs
178 {
179 stmt.make_nop();
9ffffee4
FG
180 }
181 }
182}