mirsa-relations 0.3.0

Relation domains for mirsa analyses
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use mirsa_framework::access_path::AccessPath;
use mirsa_framework::eq_domain::{EqDomain, join_eq};
use rustc_hir::def_id::DefId;
use rustc_middle::mir::{
    BinOp, CastKind, LocalDecls, Operand, Place, Rvalue, Statement, StatementKind, Terminator,
    TerminatorKind,
};
use rustc_middle::ty::{TyCtxt, TyKind};
use std::collections::{HashMap, HashSet};
use std::fmt;

#[derive(Clone, Debug, PartialEq)]
pub enum SymbolicExpr<'tcx> {
    Cmp {
        op: BinOp,
        left: Operand<'tcx>,
        right: Operand<'tcx>,
    },
    Call {
        callee: DefId,
        args: Vec<Operand<'tcx>>,
    },
}

impl<'tcx> Eq for SymbolicExpr<'tcx> {}

#[derive(Clone, Debug, PartialEq)]
pub enum SymbolicFact<'tcx> {
    EqConst { expr: Operand<'tcx>, value: u128 },
    NeConst { expr: Operand<'tcx>, value: u128 },
}

impl<'tcx> Eq for SymbolicFact<'tcx> {}

#[derive(Clone, Debug, PartialEq)]
pub struct SymbolicState<'tcx> {
    pub eq: EqDomain<'tcx, AccessPath>,
    display_places: HashMap<AccessPath, Place<'tcx>>,
    exprs: HashMap<AccessPath, SymbolicExpr<'tcx>>,
    facts: Vec<SymbolicFact<'tcx>>,
    points_to: HashMap<AccessPath, AccessPath>,
    debug: bool,
}

impl<'tcx> Eq for SymbolicState<'tcx> {}

impl<'tcx> SymbolicState<'tcx> {
    pub fn new() -> Self {
        Self {
            eq: EqDomain::new(),
            display_places: HashMap::new(),
            exprs: HashMap::new(),
            facts: Vec::new(),
            points_to: HashMap::new(),
            debug: false,
        }
    }

    pub fn new_with_debug(debug: bool) -> Self {
        let mut out = Self::new();
        out.debug = debug;
        out
    }

    pub fn debug(&self, args: fmt::Arguments<'_>) {
        if self.debug {
            eprintln!("[symbolic] {args}");
        }
    }

    pub fn remember_place(&mut self, path: AccessPath, place: Place<'tcx>) {
        self.display_places.insert(path, place);
    }

    pub fn remember_places(&mut self, places: impl IntoIterator<Item = (AccessPath, Place<'tcx>)>) {
        for (path, place) in places {
            self.remember_place(path, place);
        }
    }

    pub fn kill_place(&mut self, place: Place<'tcx>) {
        if let Some(path) = AccessPath::from_place(place) {
            self.eq.kill(path.clone());
            self.exprs.remove(&path);
            self.points_to.remove(&path);
        }
    }

    pub fn kill_place_tree(&mut self, place: Place<'tcx>) {
        let Some(path) = AccessPath::from_place(place) else {
            return;
        };
        self.kill_path_tree(&path);
    }

    pub fn kill_path_tree(&mut self, path: &AccessPath) {
        let mut affected: HashSet<AccessPath> = HashSet::from([path.clone()]);
        for candidate in self.display_places.keys() {
            if candidate.strip_pattern_prefix(path).is_some() {
                affected.insert(candidate.clone());
            }
        }
        for affected_path in affected {
            self.eq.kill(affected_path.clone());
            self.exprs.remove(&affected_path);
            self.points_to.remove(&affected_path);
            self.debug(format_args!("kill {affected_path}"));
        }
        self.exprs
            .retain(|_, expr| !expr_mentions_path_tree(expr, path));
        self.facts
            .retain(|fact| !fact_mentions_path_tree(fact, path));
    }

    pub fn set_points_to(&mut self, pointer: AccessPath, pointee: AccessPath) {
        self.debug(format_args!("points_to {pointer} -> {pointee}"));
        self.points_to.insert(pointer, pointee);
    }

    pub fn copy_points_to(&mut self, dst: AccessPath, src: &AccessPath) {
        if let Some(pointee) = self.points_to.get(src).cloned() {
            self.debug(format_args!("points_to {dst} -> {pointee}"));
            self.points_to.insert(dst, pointee);
        }
    }

    pub fn normalize_path(&self, path: &AccessPath) -> AccessPath {
        let mut out = AccessPath::from_local(path.root);
        for elem in &path.elems {
            match elem {
                mirsa_framework::access_path::AccessPathElem::Deref => {
                    if let Some(target) = self.points_to.get(&out) {
                        out = target.clone();
                    } else {
                        out = out.deref();
                    }
                }
                _ => out = out.join_suffix(std::slice::from_ref(elem)),
            }
        }
        out
    }

    pub fn normalize_place(&self, place: Place<'tcx>) -> Option<AccessPath> {
        let path = AccessPath::from_place(place)?;
        Some(self.normalize_path(&path))
    }

    pub fn union_places(&mut self, left: Place<'tcx>, right: Place<'tcx>) {
        let (Some(left_path), Some(right_path)) =
            (AccessPath::from_place(left), AccessPath::from_place(right))
        else {
            return;
        };
        let left_path = self.normalize_path(&left_path);
        let right_path = self.normalize_path(&right_path);
        self.debug(format_args!("eq {left_path} == {right_path}"));
        self.eq.union(left_path, right_path);
    }

    pub fn equiv_places_readonly(&self, left: Place<'tcx>, right: Place<'tcx>) -> bool {
        let (Some(left_path), Some(right_path)) =
            (AccessPath::from_place(left), AccessPath::from_place(right))
        else {
            return false;
        };
        self.eq.equiv_readonly(
            self.normalize_path(&left_path),
            self.normalize_path(&right_path),
        )
    }

    pub fn merge_display_places_from(&mut self, other: &Self) {
        for (path, place) in &other.display_places {
            self.display_places.entry(path.clone()).or_insert(*place);
        }
    }

    pub fn assume_eq_const(&mut self, expr: Operand<'tcx>, value: u128) {
        self.push_fact(SymbolicFact::EqConst { expr, value });
    }

    pub fn assume_ne_const(&mut self, expr: Operand<'tcx>, value: u128) {
        self.push_fact(SymbolicFact::NeConst { expr, value });
    }

    pub fn facts(&self) -> &[SymbolicFact<'tcx>] {
        &self.facts
    }

    pub fn set_place_expr(&mut self, place: Place<'tcx>, expr: SymbolicExpr<'tcx>) {
        let Some(path) = AccessPath::from_place(place) else {
            return;
        };
        let path = self.normalize_path(&path);
        self.debug(format_args!("expr {path} ({place:?}) := {expr:?}"));
        self.exprs.insert(path.clone(), expr);
        self.display_places.insert(path, place);
    }

    pub fn expr_for_place(&self, place: Place<'tcx>) -> Option<&SymbolicExpr<'tcx>> {
        let path = self.normalize_path(&AccessPath::from_place(place)?);
        if let Some(expr) = self.exprs.get(&path) {
            return Some(expr);
        }
        self.exprs
            .iter()
            .find(|(expr_path, _)| self.eq.equiv_readonly(path.clone(), (*expr_path).clone()))
            .map(|(_, expr)| expr)
    }

    fn push_fact(&mut self, fact: SymbolicFact<'tcx>) {
        if !self.facts.contains(&fact) {
            self.debug(format_args!("fact {fact:?}"));
            self.facts.push(fact);
        }
    }

    pub fn join(left: &Self, right: &Self) -> Self {
        let mut out = Self {
            eq: join_eq(&left.eq, &right.eq),
            display_places: HashMap::new(),
            exprs: left
                .exprs
                .iter()
                .filter_map(|(path, expr)| {
                    if right.exprs.get(path) == Some(expr) {
                        Some((path.clone(), expr.clone()))
                    } else {
                        None
                    }
                })
                .collect(),
            facts: left
                .facts
                .iter()
                .filter(|fact| right.facts.contains(fact))
                .cloned()
                .collect(),
            points_to: left
                .points_to
                .iter()
                .filter_map(|(path, pointee)| {
                    if right.points_to.get(path) == Some(pointee) {
                        Some((path.clone(), pointee.clone()))
                    } else {
                        None
                    }
                })
                .collect(),
            debug: left.debug || right.debug,
        };
        out.merge_display_places_from(left);
        out.merge_display_places_from(right);
        out
    }
}

fn operand_mentions_path_tree<'tcx>(operand: &Operand<'tcx>, path: &AccessPath) -> bool {
    let (Operand::Copy(place) | Operand::Move(place)) = operand else {
        return false;
    };
    AccessPath::from_place(*place).is_some_and(|operand_path| {
        operand_path.strip_pattern_prefix(path).is_some()
            || path.strip_pattern_prefix(&operand_path).is_some()
    })
}

fn expr_mentions_path_tree<'tcx>(expr: &SymbolicExpr<'tcx>, path: &AccessPath) -> bool {
    match expr {
        SymbolicExpr::Cmp { left, right, .. } => {
            operand_mentions_path_tree(left, path) || operand_mentions_path_tree(right, path)
        }
        SymbolicExpr::Call { args, .. } => args
            .iter()
            .any(|operand| operand_mentions_path_tree(operand, path)),
    }
}

fn fact_mentions_path_tree<'tcx>(fact: &SymbolicFact<'tcx>, path: &AccessPath) -> bool {
    match fact {
        SymbolicFact::EqConst { expr, .. } | SymbolicFact::NeConst { expr, .. } => {
            operand_mentions_path_tree(expr, path)
        }
    }
}

fn is_cmp_op(op: BinOp) -> bool {
    matches!(
        op,
        BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge | BinOp::Eq | BinOp::Ne
    )
}

fn has_runtime_index<'tcx>(place: Place<'tcx>) -> bool {
    place
        .projection
        .iter()
        .any(|elem| matches!(elem, rustc_middle::mir::ProjectionElem::Index(_)))
}

pub fn transfer_stmt<'tcx>(
    _tcx: TyCtxt<'tcx>,
    symbolic: &mut SymbolicState<'tcx>,
    stmt: &Statement<'tcx>,
    _local_decls: &LocalDecls<'tcx>,
) {
    let StatementKind::Assign(assign) = &stmt.kind else {
        return;
    };
    let (dst, rvalue) = &**assign;
    if let Some(dst_path) = AccessPath::from_place(*dst) {
        let normalized = symbolic.normalize_path(&dst_path);
        symbolic.kill_path_tree(&normalized);
        if normalized != dst_path {
            symbolic.exprs.remove(&dst_path);
        }
    }
    match rvalue {
        Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) => {
            if has_runtime_index(*src) && !has_runtime_index(*dst) {
                return;
            }
            let expr = symbolic.expr_for_place(*src).cloned();
            symbolic.union_places(*dst, *src);
            if let (Some(dst_path), Some(src_path)) =
                (AccessPath::from_place(*dst), AccessPath::from_place(*src))
            {
                let dst_path = symbolic.normalize_path(&dst_path);
                let src_path = symbolic.normalize_path(&src_path);
                symbolic.copy_points_to(dst_path, &src_path);
            }
            if let Some(expr) = expr {
                symbolic.set_place_expr(*dst, expr);
            }
        }
        Rvalue::BinaryOp(op, ops) if is_cmp_op(*op) => {
            let (left, right) = &**ops;
            symbolic.set_place_expr(
                *dst,
                SymbolicExpr::Cmp {
                    op: *op,
                    left: left.clone(),
                    right: right.clone(),
                },
            );
        }
        Rvalue::Cast(
            CastKind::PointerCoercion(_, _),
            Operand::Copy(src) | Operand::Move(src),
            _,
        ) => {
            if let (Some(dst_path), Some(src_path)) =
                (AccessPath::from_place(*dst), AccessPath::from_place(*src))
            {
                let dst_path = symbolic.normalize_path(&dst_path);
                let src_path = symbolic.normalize_path(&src_path);
                symbolic.copy_points_to(dst_path, &src_path);
            }
        }
        Rvalue::Ref(_, _, borrowed_place) => {
            if let (Some(dst_path), Some(src_path)) = (
                AccessPath::from_place(*dst),
                AccessPath::from_place(*borrowed_place),
            ) {
                let dst_path = symbolic.normalize_path(&dst_path);
                symbolic.set_points_to(dst_path, symbolic.normalize_path(&src_path));
            }
        }
        Rvalue::RawPtr(_, borrowed_place) => {
            if let (Some(dst_path), Some(src_path)) = (
                AccessPath::from_place(*dst),
                AccessPath::from_place(*borrowed_place),
            ) {
                let dst_path = symbolic.normalize_path(&dst_path);
                symbolic.set_points_to(dst_path, symbolic.normalize_path(&src_path));
            }
        }
        _ => {}
    }
}

pub fn transfer_terminator<'tcx>(
    tcx: TyCtxt<'tcx>,
    symbolic: &mut SymbolicState<'tcx>,
    term: &Terminator<'tcx>,
    local_decls: &LocalDecls<'tcx>,
) {
    let TerminatorKind::Call {
        func,
        args,
        destination,
        ..
    } = &term.kind
    else {
        return;
    };
    symbolic.kill_place_tree(*destination);

    let TyKind::FnDef(def_id, _) = func.ty(local_decls, tcx).kind() else {
        return;
    };
    if matches!(destination.ty(local_decls, tcx).ty.kind(), TyKind::Bool) {
        symbolic.set_place_expr(
            *destination,
            SymbolicExpr::Call {
                callee: *def_id,
                args: args.iter().map(|arg| arg.node.clone()).collect(),
            },
        );
    }
}

pub fn join_display_places<'tcx>(
    left: &HashMap<AccessPath, Place<'tcx>>,
    right: &HashMap<AccessPath, Place<'tcx>>,
) -> HashMap<AccessPath, Place<'tcx>> {
    let mut out = HashMap::new();
    for key in left.keys().chain(right.keys()) {
        if let Some(place) = left.get(key).or_else(|| right.get(key)) {
            out.insert(key.clone(), *place);
        }
    }
    out
}

impl<'tcx> Default for SymbolicState<'tcx> {
    fn default() -> Self {
        Self::new()
    }
}