42fa74c3762647e2aae4546c7cc366397dc76ad8
[oota-llvm.git] / lib / Transforms / Instrumentation / ProfilePaths / CombineBranch.cpp
1 //===-- CombineBranch.cpp -------------------------------------------------===//
2 //
3 // Pass to instrument loops
4 //
5 // At every backedge, insert a counter for that backedge and a call function
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Analysis/Dominators.h"
10 #include "llvm/Support/CFG.h"
11 #include "llvm/Constants.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/GlobalVariable.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/iOther.h"
16 #include "llvm/iOperators.h"
17 #include "llvm/iTerminators.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/Module.h"
20 #include "llvm/Function.h"
21 #include "llvm/Pass.h"
22
23 //this is used to color vertices
24 //during DFS
25
26 enum Color{
27   WHITE,
28   GREY,
29   BLACK
30 };
31
32 namespace{
33   struct CombineBranches : public FunctionPass {
34   private:
35     //DominatorSet *DS;
36     void getBackEdgesVisit(BasicBlock *u,
37                            std::map<BasicBlock *, Color > &color,
38                            std::map<BasicBlock *, int > &d, 
39                            int &time,
40                            std::map<BasicBlock *, BasicBlock *> &be);
41     void removeRedundant(std::map<BasicBlock *, BasicBlock *> &be);
42     void getBackEdges(Function &F);
43   public:
44     bool runOnFunction(Function &F);
45   };
46   
47   RegisterOpt<CombineBranches> X("branch-combine", "Multiple backedges going to same target are merged");
48 }
49
50 //helper function to get back edges: it is called by 
51 //the "getBackEdges" function below
52 void CombineBranches::getBackEdgesVisit(BasicBlock *u,
53                        std::map<BasicBlock *, Color > &color,
54                        std::map<BasicBlock *, int > &d, 
55                        int &time,
56                        std::map<BasicBlock *, BasicBlock *> &be) {
57   
58   color[u]=GREY;
59   time++;
60   d[u]=time;
61
62   for (succ_iterator vl = succ_begin(u), ve = succ_end(u); vl != ve; ++vl){
63     
64     BasicBlock *BB = *vl;
65
66     if(color[BB]!=GREY && color[BB]!=BLACK){
67       getBackEdgesVisit(BB, color, d, time, be);
68     }
69     
70     //now checking for d and f vals
71     else if(color[BB]==GREY){
72       //so v is ancestor of u if time of u > time of v
73       if(d[u] >= d[BB]){
74         //u->BB is a backedge
75         be[u] = BB;
76       }
77     }
78   }
79   color[u]=BLACK;//done with visiting the node and its neighbors
80 }
81
82 //look at all BEs, and remove all BEs that are dominated by other BE's in the
83 //set
84 void CombineBranches::removeRedundant(std::map<BasicBlock *, BasicBlock *> &be){
85   std::vector<BasicBlock *> toDelete;
86   std::map<BasicBlock *, int> seenBB;
87   
88   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(), 
89         ME = be.end(); MI != ME; ++MI){
90     
91     if(seenBB[MI->second])
92       continue;
93     
94     seenBB[MI->second] = 1;
95
96     std::vector<BasicBlock *> sameTarget;
97     sameTarget.clear();
98     
99     for(std::map<BasicBlock *, BasicBlock *>::iterator MMI = be.begin(), 
100           MME = be.end(); MMI != MME; ++MMI){
101       
102       if(MMI->first == MI->first)
103         continue;
104       
105       if(MMI->second == MI->second)
106         sameTarget.push_back(MMI->first);
107       
108     }
109     
110     //so more than one branch to same target
111     if(sameTarget.size()){
112
113       sameTarget.push_back(MI->first);
114
115       BasicBlock *newBB = new BasicBlock("newCommon", MI->first->getParent());
116       BranchInst *newBranch = new BranchInst(MI->second);
117
118       newBB->getInstList().push_back(newBranch);
119
120       std::map<PHINode *, std::vector<unsigned int> > phiMap;
121
122       
123       for(std::vector<BasicBlock *>::iterator VBI = sameTarget.begin(),
124             VBE = sameTarget.end(); VBI != VBE; ++VBI){
125
126         //std::cerr<<(*VBI)->getName()<<"\n";
127
128         BranchInst *ti = cast<BranchInst>((*VBI)->getTerminator());
129         unsigned char index = 1;
130         if(ti->getSuccessor(0) == MI->second){
131           index = 0;
132         }
133
134         ti->setSuccessor(index, newBB);
135
136         for(BasicBlock::iterator BB2Inst = MI->second->begin(), 
137               BBend = MI->second->end(); BB2Inst != BBend; ++BB2Inst){
138           
139           if (PHINode *phiInst = dyn_cast<PHINode>(BB2Inst)){
140             int bbIndex;
141             bbIndex = phiInst->getBasicBlockIndex(*VBI);
142             if(bbIndex>=0){
143               phiMap[phiInst].push_back(bbIndex);
144               //phiInst->setIncomingBlock(bbIndex, newBB); 
145             }
146           }
147         }
148       }
149
150       for(std::map<PHINode *, std::vector<unsigned int> >::iterator
151             PI = phiMap.begin(), PE = phiMap.end(); PI != PE; ++PI){
152         
153         PHINode *phiNode = new PHINode(PI->first->getType(), "phi", newBranch);
154         for(std::vector<unsigned int>::iterator II = PI->second.begin(),
155               IE = PI->second.end(); II != IE; ++II){
156           phiNode->addIncoming(PI->first->getIncomingValue(*II),
157                                PI->first->getIncomingBlock(*II));
158         }
159
160         std::vector<BasicBlock *> tempBB;
161         for(std::vector<unsigned int>::iterator II = PI->second.begin(),
162               IE = PI->second.end(); II != IE; ++II){
163           tempBB.push_back(PI->first->getIncomingBlock(*II));
164         }
165
166         for(std::vector<BasicBlock *>::iterator II = tempBB.begin(),
167               IE = tempBB.end(); II != IE; ++II){
168           PI->first->removeIncomingValue(*II);
169         }
170
171         PI->first->addIncoming(phiNode, newBB);
172       }
173       //std::cerr<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
174       //std::cerr<<MI->second;
175       //std::cerr<<"-----------------------------------\n";
176       //std::cerr<<newBB;
177       //std::cerr<<"END%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
178       
179     }
180   }
181 }
182
183 //getting the backedges in a graph
184 //Its a variation of DFS to get the backedges in the graph
185 //We get back edges by associating a time
186 //and a color with each vertex.
187 //The time of a vertex is the time when it was first visited
188 //The color of a vertex is initially WHITE,
189 //Changes to GREY when it is first visited,
190 //and changes to BLACK when ALL its neighbors
191 //have been visited
192 //So we have a back edge when we meet a successor of
193 //a node with smaller time, and GREY color
194 void CombineBranches::getBackEdges(Function &F){
195   std::map<BasicBlock *, Color > color;
196   std::map<BasicBlock *, int> d;
197   std::map<BasicBlock *, BasicBlock *> be;
198   int time=0;
199   getBackEdgesVisit(F.begin(), color, d, time, be);
200
201   removeRedundant(be);
202 }
203
204 //Per function pass for inserting counters and call function
205 bool CombineBranches::runOnFunction(Function &F){
206   
207   if(F.isExternal()) {
208     return false;
209   }
210
211   //if(F.getName() == "main"){
212    // F.setName("llvm_gprof_main");
213   //}
214   
215   //std::cerr<<F;
216   //std::cerr<<"///////////////////////////////////////////////\n";
217   getBackEdges(F);
218   
219   return true;
220 }