clippy_utils/mir/
possible_origin.rs

1use super::transitive_relation::TransitiveRelation;
2use crate::ty::is_copy;
3use rustc_data_structures::fx::FxHashMap;
4use rustc_index::bit_set::DenseBitSet;
5use rustc_lint::LateContext;
6use rustc_middle::mir;
7
8/// Collect possible borrowed for every `&mut` local.
9/// For example, `_1 = &mut _2` generate _1: {_2,...}
10/// Known Problems: not sure all borrowed are tracked
11pub(super) struct PossibleOriginVisitor<'a, 'tcx> {
12    possible_origin: TransitiveRelation,
13    body: &'a mir::Body<'tcx>,
14}
15
16impl<'a, 'tcx> PossibleOriginVisitor<'a, 'tcx> {
17    pub fn new(body: &'a mir::Body<'tcx>) -> Self {
18        Self {
19            possible_origin: TransitiveRelation::default(),
20            body,
21        }
22    }
23
24    pub fn into_map(self, cx: &LateContext<'tcx>) -> FxHashMap<mir::Local, DenseBitSet<mir::Local>> {
25        let mut map = FxHashMap::default();
26        for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
27            if is_copy(cx, self.body.local_decls[row].ty) {
28                continue;
29            }
30
31            let mut borrowers = self.possible_origin.reachable_from(row, self.body.local_decls.len());
32            borrowers.remove(mir::Local::from_usize(0));
33            if !borrowers.is_empty() {
34                map.insert(row, borrowers);
35            }
36        }
37        map
38    }
39}
40
41impl<'tcx> mir::visit::Visitor<'tcx> for PossibleOriginVisitor<'_, 'tcx> {
42    fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
43        let lhs = place.local;
44        match rvalue {
45            // Only consider `&mut`, which can modify origin place
46            mir::Rvalue::Ref(_, mir::BorrowKind::Mut { .. }, borrowed) |
47            // _2: &mut _;
48            // _3 = move _2
49            mir::Rvalue::Use(mir::Operand::Move(borrowed))  |
50            // _3 = move _2 as &mut _;
51            mir::Rvalue::Cast(_, mir::Operand::Move(borrowed), _)
52                => {
53                self.possible_origin.add(lhs, borrowed.local);
54            },
55            _ => {},
56        }
57    }
58}