Add ADT/IntEqClasses.h as a light-weight implementation of EquivalenceClasses.h.
[oota-llvm.git] / lib / Support / IntEqClasses.cpp
1 //===-- llvm/ADT/IntEqClasses.cpp - Equivalence Classes of Integers -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Equivalence classes for small integers. This is a mapping of the integers
11 // 0 .. N-1 into M equivalence classes numbered 0 .. M-1.
12 //
13 // Initially each integer has its own equivalence class. Classes are joined by
14 // passing a representative member of each class to join().
15 //
16 // Once the classes are built, compress() will number them 0 .. M-1 and prevent
17 // further changes.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/ADT/IntEqClasses.h"
22
23 using namespace llvm;
24
25 void IntEqClasses::grow(unsigned N) {
26   assert(NumClasses == 0 && "grow() called after compress().");
27   while (EC.size() < N)
28     EC.push_back(EC.size());
29 }
30
31 void IntEqClasses::join(unsigned a, unsigned b) {
32   assert(NumClasses == 0 && "join() called after compress().");
33   unsigned eca = EC[a];
34   unsigned ecb = EC[b];
35   // Update pointers while searching for the leaders, compressing the paths
36   // incrementally. The larger leader will eventually be updated, joining the
37   // classes.
38   while (eca != ecb)
39     if (eca < ecb)
40       EC[b] = eca, b = ecb, ecb = EC[b];
41     else
42       EC[a] = ecb, a = eca, eca = EC[a];
43 }
44
45 unsigned IntEqClasses::findLeader(unsigned a) const {
46   assert(NumClasses == 0 && "findLeader() called after compress().");
47   while (a != EC[a])
48     a = EC[a];
49   return a;
50 }
51
52 void IntEqClasses::compress() {
53   if (NumClasses)
54     return;
55   for (unsigned i = 0, e = EC.size(); i != e; ++i)
56     EC[i] = (EC[i] == i) ? NumClasses++ : EC[EC[i]];
57 }
58
59 void IntEqClasses::uncompress() {
60   if (!NumClasses)
61     return;
62   SmallVector<unsigned, 8> Leader;
63   for (unsigned i = 0, e = EC.size(); i != e; ++i)
64     if (EC[i] < Leader.size())
65       EC[i] = Leader[EC[i]];
66     else
67       Leader.push_back(EC[i] = i);
68   NumClasses = 0;
69 }