1 use bit_set::BitMatrix;
4 use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
5 use stable_hasher::{HashStable, StableHasher, StableHasherResult};
11 #[derive(Clone, Debug)]
12 pub struct TransitiveRelation<T: Clone + Debug + Eq + Hash> {
13 // List of elements. This is used to map from a T to a usize.
16 // Maps each element to an index.
17 map: FxHashMap<T, Index>,
19 // List of base edges in the graph. Require to compute transitive
23 // This is a cached transitive closure derived from the edges.
24 // Currently, we build it lazilly and just throw out any existing
25 // copy whenever a new edge is added. (The Lock is to permit
26 // the lazy computation.) This is kind of silly, except for the
27 // fact its size is tied to `self.elements.len()`, so I wanted to
28 // wait before building it up to avoid reallocating as new edges
29 // are added with new elements. Perhaps better would be to ask the
30 // user for a batch of edges to minimize this effect, but I
31 // already wrote the code this way. :P -nmatsakis
32 closure: Lock<Option<BitMatrix<usize, usize>>>,
35 // HACK(eddyb) manual impl avoids `Default` bound on `T`.
36 impl<T: Clone + Debug + Eq + Hash> Default for TransitiveRelation<T> {
37 fn default() -> Self {
39 elements: Default::default(),
40 map: Default::default(),
41 edges: Default::default(),
42 closure: Default::default(),
47 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
50 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
56 impl<T: Clone + Debug + Eq + Hash> TransitiveRelation<T> {
57 pub fn is_empty(&self) -> bool {
61 fn index(&self, a: &T) -> Option<Index> {
62 self.map.get(a).cloned()
65 fn add_index(&mut self, a: T) -> Index {
66 let &mut TransitiveRelation {
77 // if we changed the dimensions, clear the cache
78 *closure.get_mut() = None;
80 Index(elements.len() - 1)
84 /// Applies the (partial) function to each edge and returns a new
85 /// relation. If `f` returns `None` for any end-point, returns
87 pub fn maybe_map<F, U>(&self, mut f: F) -> Option<TransitiveRelation<U>>
88 where F: FnMut(&T) -> Option<U>,
89 U: Clone + Debug + Eq + Hash + Clone,
91 let mut result = TransitiveRelation::default();
92 for edge in &self.edges {
93 result.add(f(&self.elements[edge.source.0])?, f(&self.elements[edge.target.0])?);
98 /// Indicate that `a < b` (where `<` is this relation)
99 pub fn add(&mut self, a: T, b: T) {
100 let a = self.add_index(a);
101 let b = self.add_index(b);
106 if !self.edges.contains(&edge) {
107 self.edges.push(edge);
109 // added an edge, clear the cache
110 *self.closure.get_mut() = None;
114 /// Check whether `a < target` (transitively)
115 pub fn contains(&self, a: &T, b: &T) -> bool {
116 match (self.index(a), self.index(b)) {
117 (Some(a), Some(b)) => self.with_closure(|closure| closure.contains(a.0, b.0)),
118 (None, _) | (_, None) => false,
122 /// Thinking of `x R y` as an edge `x -> y` in a graph, this
123 /// returns all things reachable from `a`.
125 /// Really this probably ought to be `impl Iterator<Item=&T>`, but
126 /// I'm too lazy to make that work, and -- given the caching
127 /// strategy -- it'd be a touch tricky anyhow.
128 pub fn reachable_from(&self, a: &T) -> Vec<&T> {
129 match self.index(a) {
130 Some(a) => self.with_closure(|closure| {
131 closure.iter(a.0).map(|i| &self.elements[i]).collect()
137 /// Picks what I am referring to as the "postdominating"
138 /// upper-bound for `a` and `b`. This is usually the least upper
139 /// bound, but in cases where there is no single least upper
140 /// bound, it is the "mutual immediate postdominator", if you
141 /// imagine a graph where `a < b` means `a -> b`.
143 /// This function is needed because region inference currently
144 /// requires that we produce a single "UB", and there is no best
145 /// choice for the LUB. Rather than pick arbitrarily, I pick a
146 /// less good, but predictable choice. This should help ensure
147 /// that region inference yields predictable results (though it
148 /// itself is not fully sufficient).
150 /// Examples are probably clearer than any prose I could write
151 /// (there are corresponding tests below, btw). In each case,
152 /// the query is `postdom_upper_bound(a, b)`:
155 /// // returns Some(x), which is also LUB
161 /// // returns Some(x), which is not LUB (there is none)
162 /// // diagonal edges run left-to-right
172 pub fn postdom_upper_bound(&self, a: &T, b: &T) -> Option<&T> {
173 let mubs = self.minimal_upper_bounds(a, b);
174 self.mutual_immediate_postdominator(mubs)
177 /// Viewing the relation as a graph, computes the "mutual
178 /// immediate postdominator" of a set of points (if one
179 /// exists). See `postdom_upper_bound` for details.
180 pub fn mutual_immediate_postdominator<'a>(&'a self, mut mubs: Vec<&'a T>) -> Option<&'a T> {
184 1 => return Some(mubs[0]),
186 let m = mubs.pop().unwrap();
187 let n = mubs.pop().unwrap();
188 mubs.extend(self.minimal_upper_bounds(n, m));
194 /// Returns the set of bounds `X` such that:
196 /// - `a < X` and `b < X`
197 /// - there is no `Y != X` such that `a < Y` and `Y < X`
198 /// - except for the case where `X < a` (i.e., a strongly connected
199 /// component in the graph). In that case, the smallest
200 /// representative of the SCC is returned (as determined by the
201 /// internal indices).
203 /// Note that this set can, in principle, have any size.
204 pub fn minimal_upper_bounds(&self, a: &T, b: &T) -> Vec<&T> {
205 let (mut a, mut b) = match (self.index(a), self.index(b)) {
206 (Some(a), Some(b)) => (a, b),
207 (None, _) | (_, None) => {
212 // in some cases, there are some arbitrary choices to be made;
213 // it doesn't really matter what we pick, as long as we pick
214 // the same thing consistently when queried, so ensure that
215 // (a, b) are in a consistent relative order
217 mem::swap(&mut a, &mut b);
220 let lub_indices = self.with_closure(|closure| {
221 // Easy case is when either a < b or b < a:
222 if closure.contains(a.0, b.0) {
225 if closure.contains(b.0, a.0) {
229 // Otherwise, the tricky part is that there may be some c
230 // where a < c and b < c. In fact, there may be many such
231 // values. So here is what we do:
233 // 1. Find the vector `[X | a < X && b < X]` of all values
234 // `X` where `a < X` and `b < X`. In terms of the
235 // graph, this means all values reachable from both `a`
236 // and `b`. Note that this vector is also a set, but we
237 // use the term vector because the order matters
238 // to the steps below.
239 // - This vector contains upper bounds, but they are
240 // not minimal upper bounds. So you may have e.g.
241 // `[x, y, tcx, z]` where `x < tcx` and `y < tcx` and
242 // `z < x` and `z < y`:
244 // z --+---> x ----+----> tcx
249 // In this case, we really want to return just `[z]`.
250 // The following steps below achieve this by gradually
251 // reducing the list.
252 // 2. Pare down the vector using `pare_down`. This will
253 // remove elements from the vector that can be reached
254 // by an earlier element.
255 // - In the example above, this would convert `[x, y,
256 // tcx, z]` to `[x, y, z]`. Note that `x` and `y` are
257 // still in the vector; this is because while `z < x`
258 // (and `z < y`) holds, `z` comes after them in the
260 // 3. Reverse the vector and repeat the pare down process.
261 // - In the example above, we would reverse to
262 // `[z, y, x]` and then pare down to `[z]`.
263 // 4. Reverse once more just so that we yield a vector in
264 // increasing order of index. Not necessary, but why not.
266 // I believe this algorithm yields a minimal set. The
267 // argument is that, after step 2, we know that no element
268 // can reach its successors (in the vector, not the graph).
269 // After step 3, we know that no element can reach any of
270 // its predecesssors (because of step 2) nor successors
271 // (because we just called `pare_down`)
273 // This same algorithm is used in `parents` below.
275 let mut candidates = closure.intersect_rows(a.0, b.0); // (1)
276 pare_down(&mut candidates, closure); // (2)
277 candidates.reverse(); // (3a)
278 pare_down(&mut candidates, closure); // (3b)
282 lub_indices.into_iter()
284 .map(|i| &self.elements[i])
288 /// Given an element A, returns the maximal set {B} of elements B
293 /// - for each i, j: B[i] R B[j] does not hold
295 /// The intuition is that this moves "one step up" through a lattice
296 /// (where the relation is encoding the `<=` relation for the lattice).
297 /// So e.g., if the relation is `->` and we have
305 /// then `parents(a)` returns `[b, c]`. The `postdom_parent` function
306 /// would further reduce this to just `f`.
307 pub fn parents(&self, a: &T) -> Vec<&T> {
308 let a = match self.index(a) {
310 None => return vec![]
313 // Steal the algorithm for `minimal_upper_bounds` above, but
314 // with a slight tweak. In the case where `a R a`, we remove
315 // that from the set of candidates.
316 let ancestors = self.with_closure(|closure| {
317 let mut ancestors = closure.intersect_rows(a.0, a.0);
319 // Remove anything that can reach `a`. If this is a
320 // reflexive relation, this will include `a` itself.
321 ancestors.retain(|&e| !closure.contains(e, a.0));
323 pare_down(&mut ancestors, closure); // (2)
324 ancestors.reverse(); // (3a)
325 pare_down(&mut ancestors, closure); // (3b)
329 ancestors.into_iter()
331 .map(|i| &self.elements[i])
335 /// A "best" parent in some sense. See `parents` and
336 /// `postdom_upper_bound` for more details.
337 pub fn postdom_parent(&self, a: &T) -> Option<&T> {
338 self.mutual_immediate_postdominator(self.parents(a))
341 fn with_closure<OP, R>(&self, op: OP) -> R
342 where OP: FnOnce(&BitMatrix<usize, usize>) -> R
344 let mut closure_cell = self.closure.borrow_mut();
345 let mut closure = closure_cell.take();
346 if closure.is_none() {
347 closure = Some(self.compute_closure());
349 let result = op(closure.as_ref().unwrap());
350 *closure_cell = closure;
354 fn compute_closure(&self) -> BitMatrix<usize, usize> {
355 let mut matrix = BitMatrix::new(self.elements.len(),
356 self.elements.len());
357 let mut changed = true;
360 for edge in &self.edges {
361 // add an edge from S -> T
362 changed |= matrix.insert(edge.source.0, edge.target.0);
364 // add all outgoing edges from T into S
365 changed |= matrix.union_rows(edge.target.0, edge.source.0);
372 /// Pare down is used as a step in the LUB computation. It edits the
373 /// candidates array in place by removing any element j for which
374 /// there exists an earlier element i<j such that i -> j. That is,
375 /// after you run `pare_down`, you know that for all elements that
376 /// remain in candidates, they cannot reach any of the elements that
379 /// Examples follow. Assume that a -> b -> c and x -> y -> z.
381 /// - Input: `[a, b, x]`. Output: `[a, x]`.
382 /// - Input: `[b, a, x]`. Output: `[b, a, x]`.
383 /// - Input: `[a, x, b, y]`. Output: `[a, x]`.
384 fn pare_down(candidates: &mut Vec<usize>, closure: &BitMatrix<usize, usize>) {
386 while i < candidates.len() {
387 let candidate_i = candidates[i];
392 while j < candidates.len() {
393 let candidate_j = candidates[j];
394 if closure.contains(candidate_i, candidate_j) {
395 // If `i` can reach `j`, then we can remove `j`. So just
396 // mark it as dead and move on; subsequent indices will be
397 // shifted into its place.
400 candidates[j - dead] = candidate_j;
404 candidates.truncate(j - dead);
408 impl<T> Encodable for TransitiveRelation<T>
409 where T: Clone + Encodable + Debug + Eq + Hash + Clone
411 fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
412 s.emit_struct("TransitiveRelation", 2, |s| {
413 s.emit_struct_field("elements", 0, |s| self.elements.encode(s))?;
414 s.emit_struct_field("edges", 1, |s| self.edges.encode(s))?;
420 impl<T> Decodable for TransitiveRelation<T>
421 where T: Clone + Decodable + Debug + Eq + Hash + Clone
423 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
424 d.read_struct("TransitiveRelation", 2, |d| {
425 let elements: Vec<T> = d.read_struct_field("elements", 0, |d| Decodable::decode(d))?;
426 let edges = d.read_struct_field("edges", 1, |d| Decodable::decode(d))?;
427 let map = elements.iter()
429 .map(|(index, elem)| (elem.clone(), Index(index)))
431 Ok(TransitiveRelation { elements, edges, map, closure: Lock::new(None) })
436 impl<CTX, T> HashStable<CTX> for TransitiveRelation<T>
437 where T: HashStable<CTX> + Eq + Debug + Clone + Hash
439 fn hash_stable<W: StableHasherResult>(&self,
441 hasher: &mut StableHasher<W>) {
442 // We are assuming here that the relation graph has been built in a
443 // deterministic way and we can just hash it the way it is.
444 let TransitiveRelation {
447 // "map" is just a copy of elements vec
449 // "closure" is just a copy of the data above
453 elements.hash_stable(hcx, hasher);
454 edges.hash_stable(hcx, hasher);
458 impl<CTX> HashStable<CTX> for Edge {
459 fn hash_stable<W: StableHasherResult>(&self,
461 hasher: &mut StableHasher<W>) {
467 source.hash_stable(hcx, hasher);
468 target.hash_stable(hcx, hasher);
472 impl<CTX> HashStable<CTX> for Index {
473 fn hash_stable<W: StableHasherResult>(&self,
475 hasher: &mut StableHasher<W>) {
476 let Index(idx) = *self;
477 idx.hash_stable(hcx, hasher);
483 let mut relation = TransitiveRelation::default();
484 relation.add("a", "b");
485 relation.add("a", "c");
486 assert!(relation.contains(&"a", &"c"));
487 assert!(relation.contains(&"a", &"b"));
488 assert!(!relation.contains(&"b", &"a"));
489 assert!(!relation.contains(&"a", &"d"));
493 fn test_many_steps() {
494 let mut relation = TransitiveRelation::default();
495 relation.add("a", "b");
496 relation.add("a", "c");
497 relation.add("a", "f");
499 relation.add("b", "c");
500 relation.add("b", "d");
501 relation.add("b", "e");
503 relation.add("e", "g");
505 assert!(relation.contains(&"a", &"b"));
506 assert!(relation.contains(&"a", &"c"));
507 assert!(relation.contains(&"a", &"d"));
508 assert!(relation.contains(&"a", &"e"));
509 assert!(relation.contains(&"a", &"f"));
510 assert!(relation.contains(&"a", &"g"));
512 assert!(relation.contains(&"b", &"g"));
514 assert!(!relation.contains(&"a", &"x"));
515 assert!(!relation.contains(&"b", &"f"));
524 let mut relation = TransitiveRelation::default();
525 relation.add("a", "tcx");
526 relation.add("b", "tcx");
527 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"tcx"]);
528 assert_eq!(relation.parents(&"a"), vec![&"tcx"]);
529 assert_eq!(relation.parents(&"b"), vec![&"tcx"]);
533 fn mubs_best_choice1() {
541 // This tests a particular state in the algorithm, in which we
542 // need the second pare down call to get the right result (after
543 // intersection, we have [1, 2], but 2 -> 1).
545 let mut relation = TransitiveRelation::default();
546 relation.add("0", "1");
547 relation.add("0", "2");
549 relation.add("2", "1");
551 relation.add("3", "1");
552 relation.add("3", "2");
554 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"2"]);
555 assert_eq!(relation.parents(&"0"), vec![&"2"]);
556 assert_eq!(relation.parents(&"2"), vec![&"1"]);
557 assert!(relation.parents(&"1").is_empty());
561 fn mubs_best_choice2() {
569 // Like the precedecing test, but in this case intersection is [2,
570 // 1], and hence we rely on the first pare down call.
572 let mut relation = TransitiveRelation::default();
573 relation.add("0", "1");
574 relation.add("0", "2");
576 relation.add("1", "2");
578 relation.add("3", "1");
579 relation.add("3", "2");
581 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1"]);
582 assert_eq!(relation.parents(&"0"), vec![&"1"]);
583 assert_eq!(relation.parents(&"1"), vec![&"2"]);
584 assert!(relation.parents(&"2").is_empty());
588 fn mubs_no_best_choice() {
589 // in this case, the intersection yields [1, 2], and the "pare
590 // down" calls find nothing to remove.
591 let mut relation = TransitiveRelation::default();
592 relation.add("0", "1");
593 relation.add("0", "2");
595 relation.add("3", "1");
596 relation.add("3", "2");
598 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1", &"2"]);
599 assert_eq!(relation.parents(&"0"), vec![&"1", &"2"]);
600 assert_eq!(relation.parents(&"3"), vec![&"1", &"2"]);
604 fn mubs_best_choice_scc() {
605 // in this case, 1 and 2 form a cycle; we pick arbitrarily (but
608 let mut relation = TransitiveRelation::default();
609 relation.add("0", "1");
610 relation.add("0", "2");
612 relation.add("1", "2");
613 relation.add("2", "1");
615 relation.add("3", "1");
616 relation.add("3", "2");
618 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1"]);
619 assert_eq!(relation.parents(&"0"), vec![&"1"]);
623 fn pdub_crisscross() {
624 // diagonal edges run left-to-right
630 let mut relation = TransitiveRelation::default();
631 relation.add("a", "a1");
632 relation.add("a", "b1");
633 relation.add("b", "a1");
634 relation.add("b", "b1");
635 relation.add("a1", "x");
636 relation.add("b1", "x");
638 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"),
640 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
641 assert_eq!(relation.postdom_parent(&"a"), Some(&"x"));
642 assert_eq!(relation.postdom_parent(&"b"), Some(&"x"));
646 fn pdub_crisscross_more() {
647 // diagonal edges run left-to-right
648 // a -> a1 -> a2 -> a3 -> x
651 // b -> b1 -> b2 ---------+
653 let mut relation = TransitiveRelation::default();
654 relation.add("a", "a1");
655 relation.add("a", "b1");
656 relation.add("b", "a1");
657 relation.add("b", "b1");
659 relation.add("a1", "a2");
660 relation.add("a1", "b2");
661 relation.add("b1", "a2");
662 relation.add("b1", "b2");
664 relation.add("a2", "a3");
666 relation.add("a3", "x");
667 relation.add("b2", "x");
669 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"),
671 assert_eq!(relation.minimal_upper_bounds(&"a1", &"b1"),
673 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
675 assert_eq!(relation.postdom_parent(&"a"), Some(&"x"));
676 assert_eq!(relation.postdom_parent(&"b"), Some(&"x"));
686 let mut relation = TransitiveRelation::default();
687 relation.add("a", "a1");
688 relation.add("b", "b1");
689 relation.add("a1", "x");
690 relation.add("b1", "x");
692 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"x"]);
693 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
695 assert_eq!(relation.postdom_parent(&"a"), Some(&"a1"));
696 assert_eq!(relation.postdom_parent(&"b"), Some(&"b1"));
697 assert_eq!(relation.postdom_parent(&"a1"), Some(&"x"));
698 assert_eq!(relation.postdom_parent(&"b1"), Some(&"x"));
702 fn mubs_intermediate_node_on_one_side_only() {
708 // "digraph { a -> c -> d; b -> d; }",
709 let mut relation = TransitiveRelation::default();
710 relation.add("a", "c");
711 relation.add("c", "d");
712 relation.add("b", "d");
714 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"d"]);
727 // "digraph { a -> c -> d; d -> c; a -> d; b -> d; }",
728 let mut relation = TransitiveRelation::default();
729 relation.add("a", "c");
730 relation.add("c", "d");
731 relation.add("d", "c");
732 relation.add("a", "d");
733 relation.add("b", "d");
735 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
747 // "digraph { a -> c -> d; d -> c; b -> d; b -> c; }",
748 let mut relation = TransitiveRelation::default();
749 relation.add("a", "c");
750 relation.add("c", "d");
751 relation.add("d", "c");
752 relation.add("b", "d");
753 relation.add("b", "c");
755 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
767 // "digraph { a -> c -> d -> e -> c; b -> d; b -> e; }",
768 let mut relation = TransitiveRelation::default();
769 relation.add("a", "c");
770 relation.add("c", "d");
771 relation.add("d", "e");
772 relation.add("e", "c");
773 relation.add("b", "d");
774 relation.add("b", "e");
776 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
789 // "digraph { a -> c -> d -> e -> c; a -> d; b -> e; }"
790 let mut relation = TransitiveRelation::default();
791 relation.add("a", "c");
792 relation.add("c", "d");
793 relation.add("d", "e");
794 relation.add("e", "c");
795 relation.add("a", "d");
796 relation.add("b", "e");
798 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
803 // An example that was misbehaving in the compiler.
810 // plus a bunch of self-loops
812 // Here `->` represents `<=` and `0` is `'static`.
828 let mut relation = TransitiveRelation::default();
829 for (a, b) in pairs {
833 let p = relation.postdom_parent(&3);
834 assert_eq!(p, Some(&0));