Skip to main content

rapx/vm/mir_rules/
dispatch.rs

1use rustc_middle::mir::{
2    BasicBlock, Local, NonDivergingIntrinsic, Place, Rvalue, Statement, StatementKind, Terminator,
3    TerminatorKind,
4};
5
6use super::super::state::{VmExecutor, VmValue};
7use super::{RuleFlow, call, rvalue, statement, terminator};
8
9fn mir_variant(rendered: &str) -> &str {
10    let name = rendered.split(['(', '{', ' ']).next().unwrap_or("Unknown");
11    if name == "asm!" { "InlineAsm" } else { name }
12}
13
14struct RvalueEntry {
15    name: &'static str,
16    eval: for<'z3, 'tcx> fn(
17        &mut VmExecutor<'z3, 'tcx>,
18        &Place<'tcx>,
19        &Rvalue<'tcx>,
20    ) -> Option<VmValue<'z3, 'tcx>>,
21}
22
23macro_rules! rvalue_registry {
24    ($state:ident, $place:ident, $rv:ident;
25        $( $(#[$meta:meta])* $handler:ident: $variant:ident $args:tt => $eval:expr, )*
26    ) => {
27        $(
28            $(#[$meta])*
29            #[allow(unused_variables)]
30            fn $handler<'z3, 'tcx>(
31                $state: &mut VmExecutor<'z3, 'tcx>,
32                $place: &Place<'tcx>,
33                $rv: &Rvalue<'tcx>,
34            ) -> Option<VmValue<'z3, 'tcx>> {
35                if let Rvalue::$variant $args = $rv {
36                    Some($eval)
37                } else {
38                    None
39                }
40            }
41        )*
42        static RVALUE_REGISTRY: &[RvalueEntry] = &[
43            $( $(#[$meta])* RvalueEntry { name: stringify!($variant), eval: $handler }, )*
44        ];
45    };
46}
47
48rvalue_registry!(state, place, rv;
49    rule_use: Use(operand, ..) => rvalue::eval_use(state, place, operand),
50    rule_ref: Ref(_, _, source) => rvalue::eval_ref(state, place, source),
51    rule_raw_ptr: RawPtr(_, source) => rvalue::eval_raw_ptr(state, place, source),
52    rule_binary_op: BinaryOp(op, pair) => rvalue::eval_binary_op(state, place, *op, pair),
53    rule_unary_op: UnaryOp(op, operand) => rvalue::eval_unary_op(state, place, *op, operand),
54    rule_cast: Cast(kind, operand, ty) => rvalue::eval_cast(state, *kind, operand, *ty),
55    rule_aggregate: Aggregate(kind, operands) => rvalue::eval_aggregate(state, place, kind, operands),
56    rule_discriminant: Discriminant(source) => rvalue::eval_discriminant(state, place, source),
57    rule_copy_for_deref: CopyForDeref(source) => rvalue::eval_copy_for_deref(state, place, source),
58    rule_repeat: Repeat(operand, _) => rvalue::eval_repeat(state, place, operand),
59    rule_thread_local_ref: ThreadLocalRef(def_id) => rvalue::eval_thread_local_ref(state, place, *def_id),
60    rule_wrap_unsafe_binder: WrapUnsafeBinder(operand, _) => rvalue::eval_wrap_unsafe_binder(state, place, operand),
61    rule_reborrow: Reborrow(_, mutability, source) => rvalue::eval_reborrow(state, place, source, *mutability),
62);
63
64fn unsupported_statement<'z3, 'tcx>(
65    state: &mut VmExecutor<'z3, 'tcx>,
66    stmt: &Statement<'tcx>,
67) -> &'static str {
68    let rendered = format!("{:?}", stmt.kind);
69    state.record_unsupported(&format!(
70        "StatementKind::{}: {rendered}",
71        mir_variant(&rendered)
72    ));
73    "Unsupported"
74}
75
76struct StatementEntry {
77    name: &'static str,
78    apply: for<'z3, 'tcx> fn(&mut VmExecutor<'z3, 'tcx>, &Statement<'tcx>) -> bool,
79}
80
81macro_rules! statement_registry {
82    ($state:ident, $stmt:ident;
83        $( $handler:ident: $variant:ident $args:tt => $exec:expr, )*
84        ; Intrinsic($intrinsic:ident) {
85            $( $inner_handler:ident: $inner_variant:ident($inner_arg:ident) => $inner_exec:expr, )*
86        }
87        ; NoOp => $noop:ident
88    ) => {
89        $(
90            fn $handler<'z3, 'tcx>($state: &mut VmExecutor<'z3, 'tcx>, $stmt: &Statement<'tcx>) -> bool {
91                if let StatementKind::$variant $args = &$stmt.kind {
92                    $exec;
93                    true
94                } else {
95                    false
96                }
97            }
98        )*
99        $(
100            fn $inner_handler<'z3, 'tcx>($state: &mut VmExecutor<'z3, 'tcx>, $stmt: &Statement<'tcx>) -> bool {
101                if let StatementKind::Intrinsic($intrinsic) = &$stmt.kind
102                    && let NonDivergingIntrinsic::$inner_variant($inner_arg) = &**$intrinsic
103                {
104                    $inner_exec;
105                    true
106                } else {
107                    false
108                }
109            }
110        )*
111        static STATEMENT_REGISTRY: &[StatementEntry] = &[
112            $( StatementEntry { name: stringify!($variant), apply: $handler }, )*
113            $( StatementEntry { name: stringify!($inner_variant), apply: $inner_handler }, )*
114            StatementEntry { name: "NoOp", apply: $noop },
115        ];
116    };
117}
118
119fn noop_statement_rule<'z3, 'tcx>(_state: &mut VmExecutor<'z3, 'tcx>, stmt: &Statement<'tcx>) -> bool {
120    matches!(
121        stmt.kind,
122        StatementKind::FakeRead(..)
123            | StatementKind::AscribeUserType(..)
124            | StatementKind::Coverage(..)
125            | StatementKind::PlaceMention(..)
126            | StatementKind::ConstEvalCounter
127            | StatementKind::Nop
128            | StatementKind::BackwardIncompatibleDropHint { .. }
129    )
130}
131
132statement_registry!(state, stmt;
133    rule_assign: Assign(assign) => { let (place, value) = &**assign; statement::exec_assign(state, place, value); },
134    rule_set_discriminant: SetDiscriminant { place, variant_index } => statement::exec_set_discriminant(state, place, *variant_index),
135    rule_storage_live: StorageLive(local) => statement::exec_storage_live(state, *local),
136    rule_storage_dead: StorageDead(local) => statement::exec_storage_dead(state, *local),
137    ; Intrinsic(intrinsic) {
138        rule_assume: Assume(operand) => statement::exec_assume(state, operand),
139        rule_copy_nonoverlapping: CopyNonOverlapping(copy) => statement::exec_copy_nonoverlapping(state, copy),
140    }
141    ; NoOp => noop_statement_rule
142);
143
144fn unsupported_terminator<'z3, 'tcx>(
145    state: &mut VmExecutor<'z3, 'tcx>,
146    term: &Terminator<'tcx>,
147) -> &'static str {
148    let rendered = format!("{:?}", term.kind);
149    state.record_unsupported(&format!(
150        "TerminatorKind::{}: {rendered}",
151        mir_variant(&rendered)
152    ));
153    "Unsupported"
154}
155
156struct TerminatorEntry {
157    name: &'static str,
158    apply: for<'z3, 'tcx> fn(
159        &mut VmExecutor<'z3, 'tcx>,
160        &Terminator<'tcx>,
161        Option<BasicBlock>,
162    ) -> Option<RuleFlow>,
163}
164
165macro_rules! terminator_registry {
166    ($state:ident, $term:ident, $successor:ident;
167        $( $handler:ident: $variant:ident $args:tt => $exec:expr, )*
168    ) => {
169        $(
170            #[allow(unused_variables)]
171            fn $handler<'z3, 'tcx>(
172                $state: &mut VmExecutor<'z3, 'tcx>,
173                $term: &Terminator<'tcx>,
174                $successor: Option<BasicBlock>,
175            ) -> Option<RuleFlow> {
176                if let TerminatorKind::$variant $args = &$term.kind {
177                    Some($exec)
178                } else {
179                    None
180                }
181            }
182        )*
183        static TERMINATOR_REGISTRY: &[TerminatorEntry] = &[
184            $( TerminatorEntry { name: stringify!($variant), apply: $handler }, )*
185            TerminatorEntry { name: "ControlOnly", apply: control_only_terminator_rule },
186        ];
187    };
188}
189
190fn control_only_terminator_rule<'z3, 'tcx>(
191    _state: &mut VmExecutor<'z3, 'tcx>,
192    term: &Terminator<'tcx>,
193    _successor: Option<BasicBlock>,
194) -> Option<RuleFlow> {
195    matches!(
196        term.kind,
197        TerminatorKind::Goto { .. }
198            | TerminatorKind::Return
199            | TerminatorKind::Unreachable
200            | TerminatorKind::UnwindResume
201            | TerminatorKind::UnwindTerminate(_)
202            | TerminatorKind::FalseEdge { .. }
203            | TerminatorKind::FalseUnwind { .. }
204    )
205    .then_some(RuleFlow::Continue)
206}
207
208terminator_registry!(state, term, successor;
209    rule_call: Call { func, args, destination, .. } => {
210        let caller_id = state.path_state.current_frame.current_def_id;
211        call::exec_call(state, func, args, destination.local, caller_id)
212    },
213    rule_tail_call: TailCall { func, args, .. } => {
214        let caller_id = state.path_state.current_frame.current_def_id;
215        call::exec_call(state, func, args, Local::from_usize(0), caller_id)
216    },
217    rule_switch_int: SwitchInt { discr, targets } => terminator::exec_switch_int(state, discr, targets, successor),
218    rule_assert: Assert { cond, expected, .. } => {
219        terminator::exec_assert(state, cond, *expected);
220        RuleFlow::Continue
221    },
222    rule_drop: Drop { place, .. } => {
223        terminator::exec_drop(state, place);
224        RuleFlow::Continue
225    },
226);
227
228pub(super) fn exec_statement<'z3, 'tcx>(state: &mut VmExecutor<'z3, 'tcx>, stmt: &Statement<'tcx>) {
229    let was_unsupported = state.path_state.diagnostics.is_unsupported();
230    let name = STATEMENT_REGISTRY
231        .iter()
232        .find(|rule| (rule.apply)(state, stmt))
233        .map(|rule| rule.name)
234        .unwrap_or_else(|| unsupported_statement(state, stmt));
235    if state.path_state.diagnostics.needs_statement_fallback(was_unsupported) {
236        state.record_unsupported(&format!(
237            "StatementKind::{name} (model incomplete): {:?}",
238            stmt.kind
239        ));
240    }
241    log::trace!("vm statement rule: {name}");
242}
243
244pub(super) fn exec_terminator<'z3, 'tcx>(
245    state: &mut VmExecutor<'z3, 'tcx>,
246    term: &Terminator<'tcx>,
247    successor: Option<BasicBlock>,
248) -> RuleFlow {
249    let was_unsupported = state.path_state.diagnostics.is_unsupported();
250    let previous_missing_mir = state.path_state.diagnostics.missing_mir_count();
251    let (name, flow) = TERMINATOR_REGISTRY
252        .iter()
253        .find_map(|rule| (rule.apply)(state, term, successor).map(|flow| (rule.name, flow)))
254        .unwrap_or_else(|| (unsupported_terminator(state, term), RuleFlow::Continue));
255    if flow == RuleFlow::Pruned {
256        return flow;
257    }
258    if state.path_state
259        .diagnostics
260        .needs_terminator_fallback(was_unsupported, previous_missing_mir)
261    {
262        state.record_unsupported(&format!(
263            "TerminatorKind::{name} (model incomplete): {:?}",
264            term.kind
265        ));
266    }
267    log::trace!("vm terminator rule: {name}");
268    RuleFlow::Continue
269}
270
271pub(super) fn eval_rvalue<'z3, 'tcx>(
272    state: &mut VmExecutor<'z3, 'tcx>,
273    place: &Place<'tcx>,
274    rv: &Rvalue<'tcx>,
275) -> VmValue<'z3, 'tcx> {
276    let was_unsupported = state.path_state.diagnostics.is_unsupported();
277    let (name, value) = RVALUE_REGISTRY
278        .iter()
279        .find_map(|rule| (rule.eval)(state, place, rv).map(|value| (rule.name, value)))
280        .unwrap_or_else(|| {
281            let rendered = format!("{rv:?}");
282            state.record_unsupported(&format!("Rvalue::{}: {rendered}", mir_variant(&rendered)));
283            (
284                "Unsupported",
285                rvalue::eval_fresh_value(state, place, "unsupported_rvalue"),
286            )
287        });
288    if state.path_state.diagnostics.needs_statement_fallback(was_unsupported) {
289        state.record_unsupported(&format!("Rvalue::{name} (model incomplete): {rv:?}"));
290    }
291    log::trace!("vm rvalue rule: {name}");
292    value
293}