rustc_mir_dataflow/framework/lattice.rs
1//! Traits used to represent [lattices] for use as the domain of a dataflow analysis.
2//!
3//! # Overview
4//!
5//! The most common lattice is a powerset of some set `S`, ordered by [set inclusion]. The [Hasse
6//! diagram] for the powerset of a set with two elements (`X` and `Y`) is shown below. Note that
7//! distinct elements at the same height in a Hasse diagram (e.g. `{X}` and `{Y}`) are
8//! *incomparable*, not equal.
9//!
10//! ```text
11//! {X, Y} <- top
12//! / \
13//! {X} {Y}
14//! \ /
15//! {} <- bottom
16//!
17//! ```
18//!
19//! The defining characteristic of a lattice—the one that differentiates it from a [partially
20//! ordered set][poset]—is the existence of a *unique* least upper and greatest lower bound for
21//! every pair of elements. The lattice join operator (`∨`) returns the least upper bound, and the
22//! lattice meet operator (`∧`) returns the greatest lower bound. Types that implement one operator
23//! but not the other are known as semilattices. Dataflow analysis only uses the join operator and
24//! will work with any join-semilattice, but both should be specified when possible.
25//!
26//! ## `PartialOrd`
27//!
28//! Given that it represents a partially ordered set, you may be surprised that [`JoinSemiLattice`]
29//! does not have [`PartialOrd`] as a supertrait. This
30//! is because most standard library types use lexicographic ordering instead of set inclusion for
31//! their `PartialOrd` impl. Since we do not actually need to compare lattice elements to run a
32//! dataflow analysis, there's no need for a newtype wrapper with a custom `PartialOrd` impl. The
33//! only benefit would be the ability to check that the least upper (or greatest lower) bound
34//! returned by the lattice join (or meet) operator was in fact greater (or lower) than the inputs.
35//!
36//! [lattices]: https://en.wikipedia.org/wiki/Lattice_(order)
37//! [set inclusion]: https://en.wikipedia.org/wiki/Subset
38//! [Hasse diagram]: https://en.wikipedia.org/wiki/Hasse_diagram
39//! [poset]: https://en.wikipedia.org/wiki/Partially_ordered_set
40
41use rustc_index::Idx;
42use rustc_index::bit_set::{DenseBitSet, MixedBitSet};
43
44use crate::framework::BitSetExt;
45
46/// A [partially ordered set][poset] that has a [least upper bound][lub] for any pair of elements
47/// in the set.
48///
49/// [lub]: https://en.wikipedia.org/wiki/Infimum_and_supremum
50/// [poset]: https://en.wikipedia.org/wiki/Partially_ordered_set
51pub trait JoinSemiLattice: Eq {
52 /// Computes the least upper bound of two elements, storing the result in `self` and returning
53 /// `true` if `self` has changed.
54 ///
55 /// The lattice join operator is abbreviated as `∨`.
56 fn join(&mut self, other: &Self) -> bool;
57}
58
59/// A set that has a "bottom" element, which is less than or equal to any other element.
60pub trait HasBottom {
61 const BOTTOM: Self;
62
63 fn is_bottom(&self) -> bool;
64}
65
66/// A set that has a "top" element, which is greater than or equal to any other element.
67pub trait HasTop {
68 const TOP: Self;
69}
70
71/// A `DenseBitSet` represents the lattice formed by the powerset of all possible values of the
72/// index type `T` ordered by inclusion. Equivalently, it is a tuple of "two-point" lattices, one
73/// for each possible value of `T`.
74impl<T: Idx> JoinSemiLattice for DenseBitSet<T> {
75 fn join(&mut self, other: &Self) -> bool {
76 self.union(other)
77 }
78}
79
80impl<T: Idx> JoinSemiLattice for MixedBitSet<T> {
81 fn join(&mut self, other: &Self) -> bool {
82 self.union(other)
83 }
84}
85
86/// Extends a type `T` with top and bottom elements to make it a partially ordered set in which no
87/// value of `T` is comparable with any other.
88///
89/// A flat set has the following [Hasse diagram]:
90///
91/// ```text
92/// top
93/// / ... / / \ \ ... \
94/// all possible values of `T`
95/// \ ... \ \ / / ... /
96/// bottom
97/// ```
98///
99/// [Hasse diagram]: https://en.wikipedia.org/wiki/Hasse_diagram
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum FlatSet<T> {
102 Bottom,
103 Elem(T),
104 Top,
105}
106
107impl<T: Clone + Eq> JoinSemiLattice for FlatSet<T> {
108 fn join(&mut self, other: &Self) -> bool {
109 let result = match (&*self, other) {
110 (Self::Top, _) | (_, Self::Bottom) => return false,
111 (Self::Elem(a), Self::Elem(b)) if a == b => return false,
112
113 (Self::Bottom, Self::Elem(x)) => Self::Elem(x.clone()),
114
115 _ => Self::Top,
116 };
117
118 *self = result;
119 true
120 }
121}
122
123impl<T> HasBottom for FlatSet<T> {
124 const BOTTOM: Self = Self::Bottom;
125
126 fn is_bottom(&self) -> bool {
127 matches!(self, Self::Bottom)
128 }
129}
130
131impl<T> HasTop for FlatSet<T> {
132 const TOP: Self = Self::Top;
133}
134
135/// Extend a lattice with a bottom value to represent an unreachable execution.
136///
137/// The only useful action on an unreachable state is joining it with a reachable one to make it
138/// reachable. All other actions, gen/kill for instance, are no-ops.
139#[derive(PartialEq, Eq, Debug)]
140pub enum MaybeReachable<T> {
141 Unreachable,
142 Reachable(T),
143}
144
145impl<T> MaybeReachable<T> {
146 pub fn is_reachable(&self) -> bool {
147 matches!(self, MaybeReachable::Reachable(_))
148 }
149}
150
151impl<S> MaybeReachable<S> {
152 /// Return whether the current state contains the given element. If the state is unreachable,
153 /// it does no contain anything.
154 pub fn contains<T>(&self, elem: T) -> bool
155 where
156 S: BitSetExt<T>,
157 {
158 match self {
159 MaybeReachable::Unreachable => false,
160 MaybeReachable::Reachable(set) => set.contains(elem),
161 }
162 }
163}
164
165impl<T, S: BitSetExt<T>> BitSetExt<T> for MaybeReachable<S> {
166 fn contains(&self, elem: T) -> bool {
167 self.contains(elem)
168 }
169}
170
171impl<V: Clone> Clone for MaybeReachable<V> {
172 fn clone(&self) -> Self {
173 match self {
174 MaybeReachable::Reachable(x) => MaybeReachable::Reachable(x.clone()),
175 MaybeReachable::Unreachable => MaybeReachable::Unreachable,
176 }
177 }
178
179 fn clone_from(&mut self, source: &Self) {
180 match (&mut *self, source) {
181 (MaybeReachable::Reachable(x), MaybeReachable::Reachable(y)) => {
182 x.clone_from(y);
183 }
184 _ => *self = source.clone(),
185 }
186 }
187}
188
189impl<T: JoinSemiLattice + Clone> JoinSemiLattice for MaybeReachable<T> {
190 fn join(&mut self, other: &Self) -> bool {
191 // Unreachable acts as a bottom.
192 match (&mut *self, &other) {
193 (_, MaybeReachable::Unreachable) => false,
194 (MaybeReachable::Unreachable, _) => {
195 *self = other.clone();
196 true
197 }
198 (MaybeReachable::Reachable(this), MaybeReachable::Reachable(other)) => this.join(other),
199 }
200 }
201}