rustc_mir_transform/
copy_prop.rs1use rustc_index::IndexSlice;
2use rustc_index::bit_set::DenseBitSet;
3use rustc_middle::mir::visit::*;
4use rustc_middle::mir::*;
5use rustc_middle::ty::TyCtxt;
6use tracing::{debug, instrument};
7
8use crate::ssa::SsaLocals;
9
10pub(super) struct CopyProp;
21
22impl<'tcx> crate::MirPass<'tcx> for CopyProp {
23 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
24 sess.mir_opt_level() >= 1
25 }
26
27 #[instrument(level = "trace", skip(self, tcx, body))]
28 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
29 debug!(def_id = ?body.source.def_id());
30
31 let typing_env = body.typing_env(tcx);
32 let ssa = SsaLocals::new(tcx, body, typing_env);
33 debug!(borrowed_locals = ?ssa.borrowed_locals());
34 debug!(copy_classes = ?ssa.copy_classes());
35
36 let mut any_replacement = false;
37 let mut unified = DenseBitSet::new_empty(body.local_decls.len());
39 for (local, &head) in ssa.copy_classes().iter_enumerated() {
40 if local != head {
41 any_replacement = true;
42 unified.insert(head);
43 unified.insert(local);
44 }
45 }
46
47 if !any_replacement {
48 return;
49 }
50
51 Replacer { tcx, copy_classes: ssa.copy_classes(), unified }.visit_body_preserves_cfg(body);
52
53 crate::simplify::remove_unused_definitions(body);
54 }
55
56 fn is_required(&self) -> bool {
57 false
58 }
59}
60
61struct Replacer<'a, 'tcx> {
64 tcx: TyCtxt<'tcx>,
65 unified: DenseBitSet<Local>,
66 copy_classes: &'a IndexSlice<Local, Local>,
67}
68
69impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
70 fn tcx(&self) -> TyCtxt<'tcx> {
71 self.tcx
72 }
73
74 #[tracing::instrument(level = "trace", skip(self))]
75 fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
76 *local = self.copy_classes[*local];
77 }
78
79 #[tracing::instrument(level = "trace", skip(self))]
80 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
81 if let Operand::Move(place) = *operand
82 && !place.is_indirect_first_projection()
85 && self.unified.contains(place.local)
86 {
87 *operand = Operand::Copy(place);
88 }
89 self.super_operand(operand, loc);
90 }
91
92 #[tracing::instrument(level = "trace", skip(self))]
93 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
94 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
96 && self.unified.contains(l)
97 {
98 stmt.make_nop(true);
99 }
100
101 self.super_statement(stmt, loc);
102
103 if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
105 && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) = *rhs
106 && lhs == rhs
107 {
108 stmt.make_nop(true);
109 }
110 }
111}