1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use bitvec::BitMatrix;
14 use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
15 use stable_hasher::{HashStable, StableHasher, StableHasherResult};
21 #[derive(Clone, Debug)]
22 pub struct TransitiveRelation<T: Clone + Debug + Eq + Hash> {
23 // List of elements. This is used to map from a T to a usize.
26 // Maps each element to an index.
27 map: FxHashMap<T, Index>,
29 // List of base edges in the graph. Require to compute transitive
33 // This is a cached transitive closure derived from the edges.
34 // Currently, we build it lazilly and just throw out any existing
35 // copy whenever a new edge is added. (The Lock is to permit
36 // the lazy computation.) This is kind of silly, except for the
37 // fact its size is tied to `self.elements.len()`, so I wanted to
38 // wait before building it up to avoid reallocating as new edges
39 // are added with new elements. Perhaps better would be to ask the
40 // user for a batch of edges to minimize this effect, but I
41 // already wrote the code this way. :P -nmatsakis
42 closure: Lock<Option<BitMatrix<usize, usize>>>,
45 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)]
48 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
54 impl<T: Clone + Debug + Eq + Hash> TransitiveRelation<T> {
55 pub fn new() -> TransitiveRelation<T> {
60 closure: Lock::new(None),
64 pub fn is_empty(&self) -> bool {
68 fn index(&self, a: &T) -> Option<Index> {
69 self.map.get(a).cloned()
72 fn add_index(&mut self, a: T) -> Index {
73 let &mut TransitiveRelation {
84 // if we changed the dimensions, clear the cache
85 *closure.get_mut() = None;
87 Index(elements.len() - 1)
91 /// Applies the (partial) function to each edge and returns a new
92 /// relation. If `f` returns `None` for any end-point, returns
94 pub fn maybe_map<F, U>(&self, mut f: F) -> Option<TransitiveRelation<U>>
95 where F: FnMut(&T) -> Option<U>,
96 U: Clone + Debug + Eq + Hash + Clone,
98 let mut result = TransitiveRelation::new();
99 for edge in &self.edges {
100 result.add(f(&self.elements[edge.source.0])?, f(&self.elements[edge.target.0])?);
105 /// Indicate that `a < b` (where `<` is this relation)
106 pub fn add(&mut self, a: T, b: T) {
107 let a = self.add_index(a);
108 let b = self.add_index(b);
113 if !self.edges.contains(&edge) {
114 self.edges.push(edge);
116 // added an edge, clear the cache
117 *self.closure.get_mut() = None;
121 /// Check whether `a < target` (transitively)
122 pub fn contains(&self, a: &T, b: &T) -> bool {
123 match (self.index(a), self.index(b)) {
124 (Some(a), Some(b)) => self.with_closure(|closure| closure.contains(a.0, b.0)),
125 (None, _) | (_, None) => false,
129 /// Thinking of `x R y` as an edge `x -> y` in a graph, this
130 /// returns all things reachable from `a`.
132 /// Really this probably ought to be `impl Iterator<Item=&T>`, but
133 /// I'm too lazy to make that work, and -- given the caching
134 /// strategy -- it'd be a touch tricky anyhow.
135 pub fn reachable_from(&self, a: &T) -> Vec<&T> {
136 match self.index(a) {
137 Some(a) => self.with_closure(|closure| {
138 closure.iter(a.0).map(|i| &self.elements[i]).collect()
144 /// Picks what I am referring to as the "postdominating"
145 /// upper-bound for `a` and `b`. This is usually the least upper
146 /// bound, but in cases where there is no single least upper
147 /// bound, it is the "mutual immediate postdominator", if you
148 /// imagine a graph where `a < b` means `a -> b`.
150 /// This function is needed because region inference currently
151 /// requires that we produce a single "UB", and there is no best
152 /// choice for the LUB. Rather than pick arbitrarily, I pick a
153 /// less good, but predictable choice. This should help ensure
154 /// that region inference yields predictable results (though it
155 /// itself is not fully sufficient).
157 /// Examples are probably clearer than any prose I could write
158 /// (there are corresponding tests below, btw). In each case,
159 /// the query is `postdom_upper_bound(a, b)`:
162 /// // returns Some(x), which is also LUB
168 /// // returns Some(x), which is not LUB (there is none)
169 /// // diagonal edges run left-to-right
179 pub fn postdom_upper_bound(&self, a: &T, b: &T) -> Option<&T> {
180 let mubs = self.minimal_upper_bounds(a, b);
181 self.mutual_immediate_postdominator(mubs)
184 /// Viewing the relation as a graph, computes the "mutual
185 /// immediate postdominator" of a set of points (if one
186 /// exists). See `postdom_upper_bound` for details.
187 pub fn mutual_immediate_postdominator<'a>(&'a self, mut mubs: Vec<&'a T>) -> Option<&'a T> {
191 1 => return Some(mubs[0]),
193 let m = mubs.pop().unwrap();
194 let n = mubs.pop().unwrap();
195 mubs.extend(self.minimal_upper_bounds(n, m));
201 /// Returns the set of bounds `X` such that:
203 /// - `a < X` and `b < X`
204 /// - there is no `Y != X` such that `a < Y` and `Y < X`
205 /// - except for the case where `X < a` (i.e., a strongly connected
206 /// component in the graph). In that case, the smallest
207 /// representative of the SCC is returned (as determined by the
208 /// internal indices).
210 /// Note that this set can, in principle, have any size.
211 pub fn minimal_upper_bounds(&self, a: &T, b: &T) -> Vec<&T> {
212 let (mut a, mut b) = match (self.index(a), self.index(b)) {
213 (Some(a), Some(b)) => (a, b),
214 (None, _) | (_, None) => {
219 // in some cases, there are some arbitrary choices to be made;
220 // it doesn't really matter what we pick, as long as we pick
221 // the same thing consistently when queried, so ensure that
222 // (a, b) are in a consistent relative order
224 mem::swap(&mut a, &mut b);
227 let lub_indices = self.with_closure(|closure| {
228 // Easy case is when either a < b or b < a:
229 if closure.contains(a.0, b.0) {
232 if closure.contains(b.0, a.0) {
236 // Otherwise, the tricky part is that there may be some c
237 // where a < c and b < c. In fact, there may be many such
238 // values. So here is what we do:
240 // 1. Find the vector `[X | a < X && b < X]` of all values
241 // `X` where `a < X` and `b < X`. In terms of the
242 // graph, this means all values reachable from both `a`
243 // and `b`. Note that this vector is also a set, but we
244 // use the term vector because the order matters
245 // to the steps below.
246 // - This vector contains upper bounds, but they are
247 // not minimal upper bounds. So you may have e.g.
248 // `[x, y, tcx, z]` where `x < tcx` and `y < tcx` and
249 // `z < x` and `z < y`:
251 // z --+---> x ----+----> tcx
256 // In this case, we really want to return just `[z]`.
257 // The following steps below achieve this by gradually
258 // reducing the list.
259 // 2. Pare down the vector using `pare_down`. This will
260 // remove elements from the vector that can be reached
261 // by an earlier element.
262 // - In the example above, this would convert `[x, y,
263 // tcx, z]` to `[x, y, z]`. Note that `x` and `y` are
264 // still in the vector; this is because while `z < x`
265 // (and `z < y`) holds, `z` comes after them in the
267 // 3. Reverse the vector and repeat the pare down process.
268 // - In the example above, we would reverse to
269 // `[z, y, x]` and then pare down to `[z]`.
270 // 4. Reverse once more just so that we yield a vector in
271 // increasing order of index. Not necessary, but why not.
273 // I believe this algorithm yields a minimal set. The
274 // argument is that, after step 2, we know that no element
275 // can reach its successors (in the vector, not the graph).
276 // After step 3, we know that no element can reach any of
277 // its predecesssors (because of step 2) nor successors
278 // (because we just called `pare_down`)
280 // This same algorithm is used in `parents` below.
282 let mut candidates = closure.intersection(a.0, b.0); // (1)
283 pare_down(&mut candidates, closure); // (2)
284 candidates.reverse(); // (3a)
285 pare_down(&mut candidates, closure); // (3b)
289 lub_indices.into_iter()
291 .map(|i| &self.elements[i])
295 /// Given an element A, returns the maximal set {B} of elements B
300 /// - for each i, j: B[i] R B[j] does not hold
302 /// The intuition is that this moves "one step up" through a lattice
303 /// (where the relation is encoding the `<=` relation for the lattice).
304 /// So e.g. if the relation is `->` and we have
312 /// then `parents(a)` returns `[b, c]`. The `postdom_parent` function
313 /// would further reduce this to just `f`.
314 pub fn parents(&self, a: &T) -> Vec<&T> {
315 let a = match self.index(a) {
317 None => return vec![]
320 // Steal the algorithm for `minimal_upper_bounds` above, but
321 // with a slight tweak. In the case where `a R a`, we remove
322 // that from the set of candidates.
323 let ancestors = self.with_closure(|closure| {
324 let mut ancestors = closure.intersection(a.0, a.0);
326 // Remove anything that can reach `a`. If this is a
327 // reflexive relation, this will include `a` itself.
328 ancestors.retain(|&e| !closure.contains(e, a.0));
330 pare_down(&mut ancestors, closure); // (2)
331 ancestors.reverse(); // (3a)
332 pare_down(&mut ancestors, closure); // (3b)
336 ancestors.into_iter()
338 .map(|i| &self.elements[i])
342 /// A "best" parent in some sense. See `parents` and
343 /// `postdom_upper_bound` for more details.
344 pub fn postdom_parent(&self, a: &T) -> Option<&T> {
345 self.mutual_immediate_postdominator(self.parents(a))
348 fn with_closure<OP, R>(&self, op: OP) -> R
349 where OP: FnOnce(&BitMatrix<usize, usize>) -> R
351 let mut closure_cell = self.closure.borrow_mut();
352 let mut closure = closure_cell.take();
353 if closure.is_none() {
354 closure = Some(self.compute_closure());
356 let result = op(closure.as_ref().unwrap());
357 *closure_cell = closure;
361 fn compute_closure(&self) -> BitMatrix<usize, usize> {
362 let mut matrix = BitMatrix::new(self.elements.len(),
363 self.elements.len());
364 let mut changed = true;
367 for edge in &self.edges {
368 // add an edge from S -> T
369 changed |= matrix.add(edge.source.0, edge.target.0);
371 // add all outgoing edges from T into S
372 changed |= matrix.merge(edge.target.0, edge.source.0);
379 /// Pare down is used as a step in the LUB computation. It edits the
380 /// candidates array in place by removing any element j for which
381 /// there exists an earlier element i<j such that i -> j. That is,
382 /// after you run `pare_down`, you know that for all elements that
383 /// remain in candidates, they cannot reach any of the elements that
386 /// Examples follow. Assume that a -> b -> c and x -> y -> z.
388 /// - Input: `[a, b, x]`. Output: `[a, x]`.
389 /// - Input: `[b, a, x]`. Output: `[b, a, x]`.
390 /// - Input: `[a, x, b, y]`. Output: `[a, x]`.
391 fn pare_down(candidates: &mut Vec<usize>, closure: &BitMatrix<usize, usize>) {
393 while i < candidates.len() {
394 let candidate_i = candidates[i];
399 while j < candidates.len() {
400 let candidate_j = candidates[j];
401 if closure.contains(candidate_i, candidate_j) {
402 // If `i` can reach `j`, then we can remove `j`. So just
403 // mark it as dead and move on; subsequent indices will be
404 // shifted into its place.
407 candidates[j - dead] = candidate_j;
411 candidates.truncate(j - dead);
415 impl<T> Encodable for TransitiveRelation<T>
416 where T: Clone + Encodable + Debug + Eq + Hash + Clone
418 fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
419 s.emit_struct("TransitiveRelation", 2, |s| {
420 s.emit_struct_field("elements", 0, |s| self.elements.encode(s))?;
421 s.emit_struct_field("edges", 1, |s| self.edges.encode(s))?;
427 impl<T> Decodable for TransitiveRelation<T>
428 where T: Clone + Decodable + Debug + Eq + Hash + Clone
430 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
431 d.read_struct("TransitiveRelation", 2, |d| {
432 let elements: Vec<T> = d.read_struct_field("elements", 0, |d| Decodable::decode(d))?;
433 let edges = d.read_struct_field("edges", 1, |d| Decodable::decode(d))?;
434 let map = elements.iter()
436 .map(|(index, elem)| (elem.clone(), Index(index)))
438 Ok(TransitiveRelation { elements, edges, map, closure: Lock::new(None) })
443 impl<CTX, T> HashStable<CTX> for TransitiveRelation<T>
444 where T: HashStable<CTX> + Eq + Debug + Clone + Hash
446 fn hash_stable<W: StableHasherResult>(&self,
448 hasher: &mut StableHasher<W>) {
449 // We are assuming here that the relation graph has been built in a
450 // deterministic way and we can just hash it the way it is.
451 let TransitiveRelation {
454 // "map" is just a copy of elements vec
456 // "closure" is just a copy of the data above
460 elements.hash_stable(hcx, hasher);
461 edges.hash_stable(hcx, hasher);
465 impl<CTX> HashStable<CTX> for Edge {
466 fn hash_stable<W: StableHasherResult>(&self,
468 hasher: &mut StableHasher<W>) {
474 source.hash_stable(hcx, hasher);
475 target.hash_stable(hcx, hasher);
479 impl<CTX> HashStable<CTX> for Index {
480 fn hash_stable<W: StableHasherResult>(&self,
482 hasher: &mut StableHasher<W>) {
483 let Index(idx) = *self;
484 idx.hash_stable(hcx, hasher);
490 let mut relation = TransitiveRelation::new();
491 relation.add("a", "b");
492 relation.add("a", "c");
493 assert!(relation.contains(&"a", &"c"));
494 assert!(relation.contains(&"a", &"b"));
495 assert!(!relation.contains(&"b", &"a"));
496 assert!(!relation.contains(&"a", &"d"));
500 fn test_many_steps() {
501 let mut relation = TransitiveRelation::new();
502 relation.add("a", "b");
503 relation.add("a", "c");
504 relation.add("a", "f");
506 relation.add("b", "c");
507 relation.add("b", "d");
508 relation.add("b", "e");
510 relation.add("e", "g");
512 assert!(relation.contains(&"a", &"b"));
513 assert!(relation.contains(&"a", &"c"));
514 assert!(relation.contains(&"a", &"d"));
515 assert!(relation.contains(&"a", &"e"));
516 assert!(relation.contains(&"a", &"f"));
517 assert!(relation.contains(&"a", &"g"));
519 assert!(relation.contains(&"b", &"g"));
521 assert!(!relation.contains(&"a", &"x"));
522 assert!(!relation.contains(&"b", &"f"));
531 let mut relation = TransitiveRelation::new();
532 relation.add("a", "tcx");
533 relation.add("b", "tcx");
534 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"tcx"]);
535 assert_eq!(relation.parents(&"a"), vec![&"tcx"]);
536 assert_eq!(relation.parents(&"b"), vec![&"tcx"]);
540 fn mubs_best_choice1() {
548 // This tests a particular state in the algorithm, in which we
549 // need the second pare down call to get the right result (after
550 // intersection, we have [1, 2], but 2 -> 1).
552 let mut relation = TransitiveRelation::new();
553 relation.add("0", "1");
554 relation.add("0", "2");
556 relation.add("2", "1");
558 relation.add("3", "1");
559 relation.add("3", "2");
561 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"2"]);
562 assert_eq!(relation.parents(&"0"), vec![&"2"]);
563 assert_eq!(relation.parents(&"2"), vec![&"1"]);
564 assert!(relation.parents(&"1").is_empty());
568 fn mubs_best_choice2() {
576 // Like the precedecing test, but in this case intersection is [2,
577 // 1], and hence we rely on the first pare down call.
579 let mut relation = TransitiveRelation::new();
580 relation.add("0", "1");
581 relation.add("0", "2");
583 relation.add("1", "2");
585 relation.add("3", "1");
586 relation.add("3", "2");
588 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1"]);
589 assert_eq!(relation.parents(&"0"), vec![&"1"]);
590 assert_eq!(relation.parents(&"1"), vec![&"2"]);
591 assert!(relation.parents(&"2").is_empty());
595 fn mubs_no_best_choice() {
596 // in this case, the intersection yields [1, 2], and the "pare
597 // down" calls find nothing to remove.
598 let mut relation = TransitiveRelation::new();
599 relation.add("0", "1");
600 relation.add("0", "2");
602 relation.add("3", "1");
603 relation.add("3", "2");
605 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1", &"2"]);
606 assert_eq!(relation.parents(&"0"), vec![&"1", &"2"]);
607 assert_eq!(relation.parents(&"3"), vec![&"1", &"2"]);
611 fn mubs_best_choice_scc() {
612 // in this case, 1 and 2 form a cycle; we pick arbitrarily (but
615 let mut relation = TransitiveRelation::new();
616 relation.add("0", "1");
617 relation.add("0", "2");
619 relation.add("1", "2");
620 relation.add("2", "1");
622 relation.add("3", "1");
623 relation.add("3", "2");
625 assert_eq!(relation.minimal_upper_bounds(&"0", &"3"), vec![&"1"]);
626 assert_eq!(relation.parents(&"0"), vec![&"1"]);
630 fn pdub_crisscross() {
631 // diagonal edges run left-to-right
637 let mut relation = TransitiveRelation::new();
638 relation.add("a", "a1");
639 relation.add("a", "b1");
640 relation.add("b", "a1");
641 relation.add("b", "b1");
642 relation.add("a1", "x");
643 relation.add("b1", "x");
645 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"),
647 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
648 assert_eq!(relation.postdom_parent(&"a"), Some(&"x"));
649 assert_eq!(relation.postdom_parent(&"b"), Some(&"x"));
653 fn pdub_crisscross_more() {
654 // diagonal edges run left-to-right
655 // a -> a1 -> a2 -> a3 -> x
658 // b -> b1 -> b2 ---------+
660 let mut relation = TransitiveRelation::new();
661 relation.add("a", "a1");
662 relation.add("a", "b1");
663 relation.add("b", "a1");
664 relation.add("b", "b1");
666 relation.add("a1", "a2");
667 relation.add("a1", "b2");
668 relation.add("b1", "a2");
669 relation.add("b1", "b2");
671 relation.add("a2", "a3");
673 relation.add("a3", "x");
674 relation.add("b2", "x");
676 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"),
678 assert_eq!(relation.minimal_upper_bounds(&"a1", &"b1"),
680 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
682 assert_eq!(relation.postdom_parent(&"a"), Some(&"x"));
683 assert_eq!(relation.postdom_parent(&"b"), Some(&"x"));
693 let mut relation = TransitiveRelation::new();
694 relation.add("a", "a1");
695 relation.add("b", "b1");
696 relation.add("a1", "x");
697 relation.add("b1", "x");
699 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"x"]);
700 assert_eq!(relation.postdom_upper_bound(&"a", &"b"), Some(&"x"));
702 assert_eq!(relation.postdom_parent(&"a"), Some(&"a1"));
703 assert_eq!(relation.postdom_parent(&"b"), Some(&"b1"));
704 assert_eq!(relation.postdom_parent(&"a1"), Some(&"x"));
705 assert_eq!(relation.postdom_parent(&"b1"), Some(&"x"));
709 fn mubs_intermediate_node_on_one_side_only() {
715 // "digraph { a -> c -> d; b -> d; }",
716 let mut relation = TransitiveRelation::new();
717 relation.add("a", "c");
718 relation.add("c", "d");
719 relation.add("b", "d");
721 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"d"]);
734 // "digraph { a -> c -> d; d -> c; a -> d; b -> d; }",
735 let mut relation = TransitiveRelation::new();
736 relation.add("a", "c");
737 relation.add("c", "d");
738 relation.add("d", "c");
739 relation.add("a", "d");
740 relation.add("b", "d");
742 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
754 // "digraph { a -> c -> d; d -> c; b -> d; b -> c; }",
755 let mut relation = TransitiveRelation::new();
756 relation.add("a", "c");
757 relation.add("c", "d");
758 relation.add("d", "c");
759 relation.add("b", "d");
760 relation.add("b", "c");
762 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
774 // "digraph { a -> c -> d -> e -> c; b -> d; b -> e; }",
775 let mut relation = TransitiveRelation::new();
776 relation.add("a", "c");
777 relation.add("c", "d");
778 relation.add("d", "e");
779 relation.add("e", "c");
780 relation.add("b", "d");
781 relation.add("b", "e");
783 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
796 // "digraph { a -> c -> d -> e -> c; a -> d; b -> e; }"
797 let mut relation = TransitiveRelation::new();
798 relation.add("a", "c");
799 relation.add("c", "d");
800 relation.add("d", "e");
801 relation.add("e", "c");
802 relation.add("a", "d");
803 relation.add("b", "e");
805 assert_eq!(relation.minimal_upper_bounds(&"a", &"b"), vec![&"c"]);
810 // An example that was misbehaving in the compiler.
817 // plus a bunch of self-loops
819 // Here `->` represents `<=` and `0` is `'static`.
835 let mut relation = TransitiveRelation::new();
836 for (a, b) in pairs {
840 let p = relation.postdom_parent(&3);
841 assert_eq!(p, Some(&0));