rustc_mir_dataflow/framework/
mod.rs

1//! A framework that can express both [gen-kill] and generic dataflow problems.
2//!
3//! To use this framework, implement the [`Analysis`] trait. There used to be a `GenKillAnalysis`
4//! alternative trait for gen-kill analyses that would pre-compute the transfer function for each
5//! block. It was intended as an optimization, but it ended up not being any faster than
6//! `Analysis`.
7//!
8//! The `impls` module contains several examples of dataflow analyses.
9//!
10//! Then call `iterate_to_fixpoint` on your type that impls `Analysis` to get a `Results`. From
11//! there, you can use a `ResultsCursor` to inspect the fixpoint solution to your dataflow problem
12//! (good for inspecting a small number of locations), or implement the `ResultsVisitor` interface
13//! and use `visit_results` (good for inspecting many or all locations). The following example uses
14//! the `ResultsCursor` approach.
15//!
16//! ```ignore (cross-crate-imports)
17//! use rustc_const_eval::dataflow::Analysis; // Makes `iterate_to_fixpoint` available.
18//!
19//! fn do_my_analysis(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) {
20//!     let analysis = MyAnalysis::new()
21//!         .iterate_to_fixpoint(tcx, body, None)
22//!         .into_results_cursor(body);
23//!
24//!     // Print the dataflow state *after* each statement in the start block.
25//!     for (_, statement_index) in body.block_data[START_BLOCK].statements.iter_enumerated() {
26//!         cursor.seek_after(Location { block: START_BLOCK, statement_index });
27//!         let state = cursor.get();
28//!         println!("{:?}", state);
29//!     }
30//! }
31//! ```
32//!
33//! [gen-kill]: https://en.wikipedia.org/wiki/Data-flow_analysis#Bit_vector_problems
34
35use std::cmp::Ordering;
36
37use rustc_data_structures::work_queue::WorkQueue;
38use rustc_index::bit_set::{DenseBitSet, MixedBitSet};
39use rustc_index::{Idx, IndexVec};
40use rustc_middle::bug;
41use rustc_middle::mir::{
42    self, BasicBlock, CallReturnPlaces, Location, SwitchTargetValue, TerminatorEdges, traversal,
43};
44use rustc_middle::ty::TyCtxt;
45use tracing::error;
46
47use self::graphviz::write_graphviz_results;
48use super::fmt::DebugWithContext;
49
50mod cursor;
51mod direction;
52pub mod fmt;
53pub mod graphviz;
54pub mod lattice;
55mod results;
56mod visitor;
57
58pub use self::cursor::ResultsCursor;
59pub use self::direction::{Backward, Direction, Forward};
60pub use self::lattice::{JoinSemiLattice, MaybeReachable};
61pub use self::results::{EntryStates, Results};
62pub use self::visitor::{ResultsVisitor, visit_results};
63
64/// Analysis domains are all bitsets of various kinds. This trait holds
65/// operations needed by all of them.
66pub trait BitSetExt<T> {
67    fn contains(&self, elem: T) -> bool;
68}
69
70impl<T: Idx> BitSetExt<T> for DenseBitSet<T> {
71    fn contains(&self, elem: T) -> bool {
72        self.contains(elem)
73    }
74}
75
76impl<T: Idx> BitSetExt<T> for MixedBitSet<T> {
77    fn contains(&self, elem: T) -> bool {
78        self.contains(elem)
79    }
80}
81
82/// A dataflow problem with an arbitrarily complex transfer function.
83///
84/// This trait specifies the lattice on which this analysis operates (the domain), its
85/// initial value at the entry point of each basic block, and various operations.
86///
87/// # Convergence
88///
89/// When implementing this trait it's possible to choose a transfer function such that the analysis
90/// does not reach fixpoint. To guarantee convergence, your transfer functions must maintain the
91/// following invariant:
92///
93/// > If the dataflow state **before** some point in the program changes to be greater
94/// than the prior state **before** that point, the dataflow state **after** that point must
95/// also change to be greater than the prior state **after** that point.
96///
97/// This invariant guarantees that the dataflow state at a given point in the program increases
98/// monotonically until fixpoint is reached. Note that this monotonicity requirement only applies
99/// to the same point in the program at different points in time. The dataflow state at a given
100/// point in the program may or may not be greater than the state at any preceding point.
101pub trait Analysis<'tcx> {
102    /// The type that holds the dataflow state at any given point in the program.
103    type Domain: Clone + JoinSemiLattice;
104
105    /// The direction of this analysis. Either `Forward` or `Backward`.
106    type Direction: Direction = Forward;
107
108    /// Auxiliary data used for analyzing `SwitchInt` terminators, if necessary.
109    type SwitchIntData = !;
110
111    /// A descriptive name for this analysis. Used only for debugging.
112    ///
113    /// This name should be brief and contain no spaces, periods or other characters that are not
114    /// suitable as part of a filename.
115    const NAME: &'static str;
116
117    /// Returns the initial value of the dataflow state upon entry to each basic block.
118    fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain;
119
120    /// Mutates the initial value of the dataflow state upon entry to the `START_BLOCK`.
121    ///
122    /// For backward analyses, initial state (besides the bottom value) is not yet supported. Trying
123    /// to mutate the initial state will result in a panic.
124    //
125    // FIXME: For backward dataflow analyses, the initial state should be applied to every basic
126    // block where control flow could exit the MIR body (e.g., those terminated with `return` or
127    // `resume`). It's not obvious how to handle `yield` points in coroutines, however.
128    fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain);
129
130    /// Updates the current dataflow state with an "early" effect, i.e. one
131    /// that occurs immediately before the given statement.
132    ///
133    /// This method is useful if the consumer of the results of this analysis only needs to observe
134    /// *part* of the effect of a statement (e.g. for two-phase borrows). As a general rule,
135    /// analyses should not implement this without also implementing
136    /// `apply_primary_statement_effect`.
137    fn apply_early_statement_effect(
138        &mut self,
139        _state: &mut Self::Domain,
140        _statement: &mir::Statement<'tcx>,
141        _location: Location,
142    ) {
143    }
144
145    /// Updates the current dataflow state with the effect of evaluating a statement.
146    fn apply_primary_statement_effect(
147        &mut self,
148        state: &mut Self::Domain,
149        statement: &mir::Statement<'tcx>,
150        location: Location,
151    );
152
153    /// Updates the current dataflow state with an effect that occurs immediately *before* the
154    /// given terminator.
155    ///
156    /// This method is useful if the consumer of the results of this analysis needs only to observe
157    /// *part* of the effect of a terminator (e.g. for two-phase borrows). As a general rule,
158    /// analyses should not implement this without also implementing
159    /// `apply_primary_terminator_effect`.
160    fn apply_early_terminator_effect(
161        &mut self,
162        _state: &mut Self::Domain,
163        _terminator: &mir::Terminator<'tcx>,
164        _location: Location,
165    ) {
166    }
167
168    /// Updates the current dataflow state with the effect of evaluating a terminator.
169    ///
170    /// The effect of a successful return from a `Call` terminator should **not** be accounted for
171    /// in this function. That should go in `apply_call_return_effect`. For example, in the
172    /// `InitializedPlaces` analyses, the return place for a function call is not marked as
173    /// initialized here.
174    fn apply_primary_terminator_effect<'mir>(
175        &mut self,
176        _state: &mut Self::Domain,
177        terminator: &'mir mir::Terminator<'tcx>,
178        _location: Location,
179    ) -> TerminatorEdges<'mir, 'tcx> {
180        terminator.edges()
181    }
182
183    /* Edge-specific effects */
184
185    /// Updates the current dataflow state with the effect of a successful return from a `Call`
186    /// terminator.
187    ///
188    /// This is separate from `apply_primary_terminator_effect` to properly track state across
189    /// unwind edges.
190    fn apply_call_return_effect(
191        &mut self,
192        _state: &mut Self::Domain,
193        _block: BasicBlock,
194        _return_places: CallReturnPlaces<'_, 'tcx>,
195    ) {
196    }
197
198    /// Used to update the current dataflow state with the effect of taking a particular branch in
199    /// a `SwitchInt` terminator.
200    ///
201    /// Unlike the other edge-specific effects, which are allowed to mutate `Self::Domain`
202    /// directly, overriders of this method must return a `Self::SwitchIntData` value (wrapped in
203    /// `Some`). The `apply_switch_int_edge_effect` method will then be called once for each
204    /// outgoing edge and will have access to the dataflow state that will be propagated along that
205    /// edge, and also the `Self::SwitchIntData` value.
206    ///
207    /// This interface is somewhat more complex than the other visitor-like "effect" methods.
208    /// However, it is both more ergonomic—callers don't need to recompute or cache information
209    /// about a given `SwitchInt` terminator for each one of its edges—and more efficient—the
210    /// engine doesn't need to clone the exit state for a block unless
211    /// `get_switch_int_data` is actually called.
212    fn get_switch_int_data(
213        &mut self,
214        _block: mir::BasicBlock,
215        _discr: &mir::Operand<'tcx>,
216    ) -> Option<Self::SwitchIntData> {
217        None
218    }
219
220    /// See comments on `get_switch_int_data`.
221    fn apply_switch_int_edge_effect(
222        &mut self,
223        _data: &mut Self::SwitchIntData,
224        _state: &mut Self::Domain,
225        _value: SwitchTargetValue,
226    ) {
227        unreachable!();
228    }
229
230    /* Extension methods */
231
232    /// Finds the fixpoint for this dataflow problem.
233    ///
234    /// You shouldn't need to override this. Its purpose is to enable method chaining like so:
235    ///
236    /// ```ignore (cross-crate-imports)
237    /// let results = MyAnalysis::new(tcx, body)
238    ///     .iterate_to_fixpoint(tcx, body, None)
239    ///     .into_results_cursor(body);
240    /// ```
241    /// You can optionally add a `pass_name` to the graphviz output for this particular run of a
242    /// dataflow analysis. Some analyses are run multiple times in the compilation pipeline.
243    /// Without a `pass_name` to differentiates them, only the results for the latest run will be
244    /// saved.
245    fn iterate_to_fixpoint<'mir>(
246        mut self,
247        tcx: TyCtxt<'tcx>,
248        body: &'mir mir::Body<'tcx>,
249        pass_name: Option<&'static str>,
250    ) -> Results<'tcx, Self>
251    where
252        Self: Sized,
253        Self::Domain: DebugWithContext<Self>,
254    {
255        let mut entry_states =
256            IndexVec::from_fn_n(|_| self.bottom_value(body), body.basic_blocks.len());
257        self.initialize_start_block(body, &mut entry_states[mir::START_BLOCK]);
258
259        if Self::Direction::IS_BACKWARD && entry_states[mir::START_BLOCK] != self.bottom_value(body)
260        {
261            bug!("`initialize_start_block` is not yet supported for backward dataflow analyses");
262        }
263
264        let mut dirty_queue: WorkQueue<BasicBlock> = WorkQueue::with_none(body.basic_blocks.len());
265
266        if Self::Direction::IS_FORWARD {
267            for (bb, _) in traversal::reverse_postorder(body) {
268                dirty_queue.insert(bb);
269            }
270        } else {
271            // Reverse post-order on the reverse CFG may generate a better iteration order for
272            // backward dataflow analyses, but probably not enough to matter.
273            for (bb, _) in traversal::postorder(body) {
274                dirty_queue.insert(bb);
275            }
276        }
277
278        // `state` is not actually used between iterations;
279        // this is just an optimization to avoid reallocating
280        // every iteration.
281        let mut state = self.bottom_value(body);
282        while let Some(bb) = dirty_queue.pop() {
283            // Set the state to the entry state of the block.
284            // This is equivalent to `state = entry_states[bb].clone()`,
285            // but it saves an allocation, thus improving compile times.
286            state.clone_from(&entry_states[bb]);
287
288            Self::Direction::apply_effects_in_block(
289                &mut self,
290                body,
291                &mut state,
292                bb,
293                &body[bb],
294                |target: BasicBlock, state: &Self::Domain| {
295                    let set_changed = entry_states[target].join(state);
296                    if set_changed {
297                        dirty_queue.insert(target);
298                    }
299                },
300            );
301        }
302
303        let mut results = Results { analysis: self, entry_states };
304
305        if tcx.sess.opts.unstable_opts.dump_mir_dataflow {
306            let res = write_graphviz_results(tcx, body, &mut results, pass_name);
307            if let Err(e) = res {
308                error!("Failed to write graphviz dataflow results: {}", e);
309            }
310        }
311
312        results
313    }
314}
315
316/// The legal operations for a transfer function in a gen/kill problem.
317pub trait GenKill<T> {
318    /// Inserts `elem` into the state vector.
319    fn gen_(&mut self, elem: T);
320
321    /// Removes `elem` from the state vector.
322    fn kill(&mut self, elem: T);
323
324    /// Calls `gen` for each element in `elems`.
325    fn gen_all(&mut self, elems: impl IntoIterator<Item = T>) {
326        for elem in elems {
327            self.gen_(elem);
328        }
329    }
330
331    /// Calls `kill` for each element in `elems`.
332    fn kill_all(&mut self, elems: impl IntoIterator<Item = T>) {
333        for elem in elems {
334            self.kill(elem);
335        }
336    }
337}
338
339impl<T: Idx> GenKill<T> for DenseBitSet<T> {
340    fn gen_(&mut self, elem: T) {
341        self.insert(elem);
342    }
343
344    fn kill(&mut self, elem: T) {
345        self.remove(elem);
346    }
347}
348
349impl<T: Idx> GenKill<T> for MixedBitSet<T> {
350    fn gen_(&mut self, elem: T) {
351        self.insert(elem);
352    }
353
354    fn kill(&mut self, elem: T) {
355        self.remove(elem);
356    }
357}
358
359impl<T, S: GenKill<T>> GenKill<T> for MaybeReachable<S> {
360    fn gen_(&mut self, elem: T) {
361        match self {
362            // If the state is not reachable, adding an element does nothing.
363            MaybeReachable::Unreachable => {}
364            MaybeReachable::Reachable(set) => set.gen_(elem),
365        }
366    }
367
368    fn kill(&mut self, elem: T) {
369        match self {
370            // If the state is not reachable, killing an element does nothing.
371            MaybeReachable::Unreachable => {}
372            MaybeReachable::Reachable(set) => set.kill(elem),
373        }
374    }
375}
376
377// NOTE: DO NOT CHANGE VARIANT ORDER. The derived `Ord` impls rely on the current order.
378#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
379enum Effect {
380    /// The "early" effect (e.g., `apply_early_statement_effect`) for a statement/terminator.
381    Early,
382
383    /// The "primary" effect (e.g., `apply_primary_statement_effect`) for a statement/terminator.
384    Primary,
385}
386
387impl Effect {
388    const fn at_index(self, statement_index: usize) -> EffectIndex {
389        EffectIndex { effect: self, statement_index }
390    }
391}
392
393#[derive(Clone, Copy, Debug, PartialEq, Eq)]
394pub struct EffectIndex {
395    statement_index: usize,
396    effect: Effect,
397}
398
399impl EffectIndex {
400    fn next_in_forward_order(self) -> Self {
401        match self.effect {
402            Effect::Early => Effect::Primary.at_index(self.statement_index),
403            Effect::Primary => Effect::Early.at_index(self.statement_index + 1),
404        }
405    }
406
407    fn next_in_backward_order(self) -> Self {
408        match self.effect {
409            Effect::Early => Effect::Primary.at_index(self.statement_index),
410            Effect::Primary => Effect::Early.at_index(self.statement_index - 1),
411        }
412    }
413
414    /// Returns `true` if the effect at `self` should be applied earlier than the effect at `other`
415    /// in forward order.
416    fn precedes_in_forward_order(self, other: Self) -> bool {
417        let ord = self
418            .statement_index
419            .cmp(&other.statement_index)
420            .then_with(|| self.effect.cmp(&other.effect));
421        ord == Ordering::Less
422    }
423
424    /// Returns `true` if the effect at `self` should be applied earlier than the effect at `other`
425    /// in backward order.
426    fn precedes_in_backward_order(self, other: Self) -> bool {
427        let ord = other
428            .statement_index
429            .cmp(&self.statement_index)
430            .then_with(|| self.effect.cmp(&other.effect));
431        ord == Ordering::Less
432    }
433}
434
435#[cfg(test)]
436mod tests;