1 use crate::fx::FxIndexSet;
3 use rustc_index::bit_set::BitMatrix;
11 #[derive(Clone, Debug)]
12 pub struct TransitiveRelation<T> {
13 // List of elements. This is used to map from a T to a usize.
14 elements: FxIndexSet<T>,
16 // List of base edges in the graph. Require to compute transitive
20 // This is a cached transitive closure derived from the edges.
21 // Currently, we build it lazily and just throw out any existing
22 // copy whenever a new edge is added. (The Lock is to permit
23 // the lazy computation.) This is kind of silly, except for the
24 // fact its size is tied to `self.elements.len()`, so I wanted to
25 // wait before building it up to avoid reallocating as new edges
26 // are added with new elements. Perhaps better would be to ask the
27 // user for a batch of edges to minimize this effect, but I
28 // already wrote the code this way. :P -nmatsakis
29 closure: Lock<Option<BitMatrix<usize, usize>>>,
32 // HACK(eddyb) manual impl avoids `Default` bound on `T`.
33 impl<T: Eq + Hash> Default for TransitiveRelation<T> {
34 fn default() -> Self {
36 elements: Default::default(),
37 edges: Default::default(),
38 closure: Default::default(),
43 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Debug)]
46 #[derive(Clone, PartialEq, Eq, Debug)]
52 impl<T: Eq + Hash + Copy> TransitiveRelation<T> {
53 pub fn is_empty(&self) -> bool {
57 pub fn elements(&self) -> impl Iterator<Item = &T> {
61 fn index(&self, a: T) -> Option<Index> {
62 self.elements.get_index_of(&a).map(Index)
65 fn add_index(&mut self, a: T) -> Index {
66 let (index, added) = self.elements.insert_full(a);
68 // if we changed the dimensions, clear the cache
69 *self.closure.get_mut() = None;
74 /// Applies the (partial) function to each edge and returns a new
75 /// relation. If `f` returns `None` for any end-point, returns
77 pub fn maybe_map<F, U>(&self, mut f: F) -> Option<TransitiveRelation<U>>
79 F: FnMut(T) -> Option<U>,
80 U: Clone + Debug + Eq + Hash + Copy,
82 let mut result = TransitiveRelation::default();
83 for edge in &self.edges {
84 result.add(f(self.elements[edge.source.0])?, f(self.elements[edge.target.0])?);
89 /// Indicate that `a < b` (where `<` is this relation)
90 pub fn add(&mut self, a: T, b: T) {
91 let a = self.add_index(a);
92 let b = self.add_index(b);
93 let edge = Edge { source: a, target: b };
94 if !self.edges.contains(&edge) {
95 self.edges.push(edge);
97 // added an edge, clear the cache
98 *self.closure.get_mut() = None;
102 /// Checks whether `a < target` (transitively)
103 pub fn contains(&self, a: T, b: T) -> bool {
104 match (self.index(a), self.index(b)) {
105 (Some(a), Some(b)) => self.with_closure(|closure| closure.contains(a.0, b.0)),
106 (None, _) | (_, None) => false,
110 /// Thinking of `x R y` as an edge `x -> y` in a graph, this
111 /// returns all things reachable from `a`.
113 /// Really this probably ought to be `impl Iterator<Item = &T>`, but
114 /// I'm too lazy to make that work, and -- given the caching
115 /// strategy -- it'd be a touch tricky anyhow.
116 pub fn reachable_from(&self, a: T) -> Vec<T> {
117 match self.index(a) {
119 self.with_closure(|closure| closure.iter(a.0).map(|i| self.elements[i]).collect())
125 /// Picks what I am referring to as the "postdominating"
126 /// upper-bound for `a` and `b`. This is usually the least upper
127 /// bound, but in cases where there is no single least upper
128 /// bound, it is the "mutual immediate postdominator", if you
129 /// imagine a graph where `a < b` means `a -> b`.
131 /// This function is needed because region inference currently
132 /// requires that we produce a single "UB", and there is no best
133 /// choice for the LUB. Rather than pick arbitrarily, I pick a
134 /// less good, but predictable choice. This should help ensure
135 /// that region inference yields predictable results (though it
136 /// itself is not fully sufficient).
138 /// Examples are probably clearer than any prose I could write
139 /// (there are corresponding tests below, btw). In each case,
140 /// the query is `postdom_upper_bound(a, b)`:
143 /// // Returns Some(x), which is also LUB.
149 /// // Returns `Some(x)`, which is not LUB (there is none)
150 /// // diagonal edges run left-to-right.
156 /// // Returns `None`.
160 pub fn postdom_upper_bound(&self, a: T, b: T) -> Option<T> {
161 let mubs = self.minimal_upper_bounds(a, b);
162 self.mutual_immediate_postdominator(mubs)
165 /// Viewing the relation as a graph, computes the "mutual
166 /// immediate postdominator" of a set of points (if one
167 /// exists). See `postdom_upper_bound` for details.
168 pub fn mutual_immediate_postdominator<'a>(&'a self, mut mubs: Vec<T>) -> Option<T> {
172 1 => return Some(mubs[0]),
174 let m = mubs.pop().unwrap();
175 let n = mubs.pop().unwrap();
176 mubs.extend(self.minimal_upper_bounds(n, m));
182 /// Returns the set of bounds `X` such that:
184 /// - `a < X` and `b < X`
185 /// - there is no `Y != X` such that `a < Y` and `Y < X`
186 /// - except for the case where `X < a` (i.e., a strongly connected
187 /// component in the graph). In that case, the smallest
188 /// representative of the SCC is returned (as determined by the
189 /// internal indices).
191 /// Note that this set can, in principle, have any size.
192 pub fn minimal_upper_bounds(&self, a: T, b: T) -> Vec<T> {
193 let (Some(mut a), Some(mut b)) = (self.index(a), self.index(b)) else {
197 // in some cases, there are some arbitrary choices to be made;
198 // it doesn't really matter what we pick, as long as we pick
199 // the same thing consistently when queried, so ensure that
200 // (a, b) are in a consistent relative order
202 mem::swap(&mut a, &mut b);
205 let lub_indices = self.with_closure(|closure| {
206 // Easy case is when either a < b or b < a:
207 if closure.contains(a.0, b.0) {
210 if closure.contains(b.0, a.0) {
214 // Otherwise, the tricky part is that there may be some c
215 // where a < c and b < c. In fact, there may be many such
216 // values. So here is what we do:
218 // 1. Find the vector `[X | a < X && b < X]` of all values
219 // `X` where `a < X` and `b < X`. In terms of the
220 // graph, this means all values reachable from both `a`
221 // and `b`. Note that this vector is also a set, but we
222 // use the term vector because the order matters
223 // to the steps below.
224 // - This vector contains upper bounds, but they are
225 // not minimal upper bounds. So you may have e.g.
226 // `[x, y, tcx, z]` where `x < tcx` and `y < tcx` and
227 // `z < x` and `z < y`:
229 // z --+---> x ----+----> tcx
234 // In this case, we really want to return just `[z]`.
235 // The following steps below achieve this by gradually
236 // reducing the list.
237 // 2. Pare down the vector using `pare_down`. This will
238 // remove elements from the vector that can be reached
239 // by an earlier element.
240 // - In the example above, this would convert `[x, y,
241 // tcx, z]` to `[x, y, z]`. Note that `x` and `y` are
242 // still in the vector; this is because while `z < x`
243 // (and `z < y`) holds, `z` comes after them in the
245 // 3. Reverse the vector and repeat the pare down process.
246 // - In the example above, we would reverse to
247 // `[z, y, x]` and then pare down to `[z]`.
248 // 4. Reverse once more just so that we yield a vector in
249 // increasing order of index. Not necessary, but why not.
251 // I believe this algorithm yields a minimal set. The
252 // argument is that, after step 2, we know that no element
253 // can reach its successors (in the vector, not the graph).
254 // After step 3, we know that no element can reach any of
255 // its predecessors (because of step 2) nor successors
256 // (because we just called `pare_down`)
258 // This same algorithm is used in `parents` below.
260 let mut candidates = closure.intersect_rows(a.0, b.0); // (1)
261 pare_down(&mut candidates, closure); // (2)
262 candidates.reverse(); // (3a)
263 pare_down(&mut candidates, closure); // (3b)
270 .map(|i| self.elements[i])
274 /// Given an element A, returns the maximal set {B} of elements B
279 /// - for each i, j: `B[i]` R `B[j]` does not hold
281 /// The intuition is that this moves "one step up" through a lattice
282 /// (where the relation is encoding the `<=` relation for the lattice).
283 /// So e.g., if the relation is `->` and we have
291 /// then `parents(a)` returns `[b, c]`. The `postdom_parent` function
292 /// would further reduce this to just `f`.
293 pub fn parents(&self, a: T) -> Vec<T> {
294 let Some(a) = self.index(a) else {
298 // Steal the algorithm for `minimal_upper_bounds` above, but
299 // with a slight tweak. In the case where `a R a`, we remove
300 // that from the set of candidates.
301 let ancestors = self.with_closure(|closure| {
302 let mut ancestors = closure.intersect_rows(a.0, a.0);
304 // Remove anything that can reach `a`. If this is a
305 // reflexive relation, this will include `a` itself.
306 ancestors.retain(|&e| !closure.contains(e, a.0));
308 pare_down(&mut ancestors, closure); // (2)
309 ancestors.reverse(); // (3a)
310 pare_down(&mut ancestors, closure); // (3b)
317 .map(|i| self.elements[i])
321 fn with_closure<OP, R>(&self, op: OP) -> R
323 OP: FnOnce(&BitMatrix<usize, usize>) -> R,
325 let mut closure_cell = self.closure.borrow_mut();
326 let mut closure = closure_cell.take();
327 if closure.is_none() {
328 closure = Some(self.compute_closure());
330 let result = op(closure.as_ref().unwrap());
331 *closure_cell = closure;
335 fn compute_closure(&self) -> BitMatrix<usize, usize> {
336 let mut matrix = BitMatrix::new(self.elements.len(), self.elements.len());
337 let mut changed = true;
340 for edge in &self.edges {
341 // add an edge from S -> T
342 changed |= matrix.insert(edge.source.0, edge.target.0);
344 // add all outgoing edges from T into S
345 changed |= matrix.union_rows(edge.target.0, edge.source.0);
351 /// Lists all the base edges in the graph: the initial _non-transitive_ set of element
352 /// relations, which will be later used as the basis for the transitive closure computation.
353 pub fn base_edges(&self) -> impl Iterator<Item = (T, T)> + '_ {
356 .map(move |edge| (self.elements[edge.source.0], self.elements[edge.target.0]))
360 /// Pare down is used as a step in the LUB computation. It edits the
361 /// candidates array in place by removing any element j for which
362 /// there exists an earlier element i<j such that i -> j. That is,
363 /// after you run `pare_down`, you know that for all elements that
364 /// remain in candidates, they cannot reach any of the elements that
367 /// Examples follow. Assume that a -> b -> c and x -> y -> z.
369 /// - Input: `[a, b, x]`. Output: `[a, x]`.
370 /// - Input: `[b, a, x]`. Output: `[b, a, x]`.
371 /// - Input: `[a, x, b, y]`. Output: `[a, x]`.
372 fn pare_down(candidates: &mut Vec<usize>, closure: &BitMatrix<usize, usize>) {
374 while let Some(&candidate_i) = candidates.get(i) {
379 while let Some(&candidate_j) = candidates.get(j) {
380 if closure.contains(candidate_i, candidate_j) {
381 // If `i` can reach `j`, then we can remove `j`. So just
382 // mark it as dead and move on; subsequent indices will be
383 // shifted into its place.
386 candidates[j - dead] = candidate_j;
390 candidates.truncate(j - dead);