Clean up this pass somewhat:
[oota-llvm.git] / lib / Transforms / Instrumentation / ProfilePaths / InstLoops.cpp
1 //===-- InstLoops.cpp -----------------------------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the first-level instrumentation pass for the Reoptimizer. It
11 // instrument the back-edges of loops by inserting a basic block
12 // containing a call to llvm_first_trigger (the first-level trigger function),
13 // and inserts an initialization call to the main() function.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Type.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "Support/Debug.h"
26 #include "../ProfilingUtils.h"
27
28 namespace llvm {
29
30 //this is used to color vertices
31 //during DFS
32
33 enum Color{
34   WHITE,
35   GREY,
36   BLACK
37 };
38
39 namespace {
40   typedef std::map<BasicBlock *, BasicBlock *> BBMap;
41   struct InstLoops : public FunctionPass {
42     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43       AU.addRequired<DominatorSet>();
44     }
45   private:
46     Function *inCountMth;
47     DominatorSet *DS;
48     void getBackEdgesVisit(BasicBlock *u,
49                            std::map<BasicBlock *, Color > &color,
50                            std::map<BasicBlock *, int > &d, 
51                            int &time, BBMap &be);
52     void removeRedundant(BBMap &be);
53     void findAndInstrumentBackEdges(Function &F);
54   public:
55     bool doInitialization(Module &M);
56     bool runOnFunction(Function &F);
57   };
58   
59   RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");
60 }
61
62 //helper function to get back edges: it is called by 
63 //the "getBackEdges" function below
64 void InstLoops::getBackEdgesVisit(BasicBlock *u,
65                        std::map<BasicBlock *, Color > &color,
66                        std::map<BasicBlock *, int > &d, 
67                        int &time, BBMap &be) {
68   color[u]=GREY;
69   time++;
70   d[u]=time;
71
72   for(succ_iterator vl = succ_begin(u), ve = succ_end(u); vl != ve; ++vl){
73     BasicBlock *BB = *vl;
74
75     if(color[BB]!=GREY && color[BB]!=BLACK){
76       getBackEdgesVisit(BB, color, d, time, be);
77     }
78     
79     //now checking for d and f vals
80     else if(color[BB]==GREY){
81       //so v is ancestor of u if time of u > time of v
82       if(d[u] >= d[BB]){
83         //u->BB is a backedge
84         be[u] = BB;
85       }
86     }
87   }
88   color[u]=BLACK;//done with visiting the node and its neighbors
89 }
90
91 //look at all BEs, and remove all BEs that are dominated by other BE's in the
92 //set
93 void InstLoops::removeRedundant(BBMap &be) {
94   std::vector<BasicBlock *> toDelete;
95   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(), 
96         ME = be.end(); MI != ME; ++MI)
97     for(BBMap::iterator MMI = be.begin(), MME = be.end(); MMI != MME; ++MMI)
98       if(DS->properlyDominates(MI->first, MMI->first))
99         toDelete.push_back(MMI->first);
100   // Remove all the back-edges we found from be.
101   for(std::vector<BasicBlock *>::iterator VI = toDelete.begin(), 
102         VE = toDelete.end(); VI != VE; ++VI)
103     be.erase(*VI);
104 }
105
106 //getting the backedges in a graph
107 //Its a variation of DFS to get the backedges in the graph
108 //We get back edges by associating a time
109 //and a color with each vertex.
110 //The time of a vertex is the time when it was first visited
111 //The color of a vertex is initially WHITE,
112 //Changes to GREY when it is first visited,
113 //and changes to BLACK when ALL its neighbors
114 //have been visited
115 //So we have a back edge when we meet a successor of
116 //a node with smaller time, and GREY color
117 void InstLoops::findAndInstrumentBackEdges(Function &F){
118   std::map<BasicBlock *, Color > color;
119   std::map<BasicBlock *, int> d;
120   BBMap be;
121   int time=0;
122   getBackEdgesVisit(F.begin(), color, d, time, be);
123
124   removeRedundant(be);
125
126   for(std::map<BasicBlock *, BasicBlock *>::iterator MI = be.begin(),
127         ME = be.end(); MI != ME; ++MI){
128     BasicBlock *u = MI->first;
129     BasicBlock *BB = MI->second;
130     // We have a back-edge from BB --> u.
131     DEBUG (std::cerr << "Instrumenting back-edge from " << BB->getName ()
132                      << "-->" << u->getName () << "\n");
133     // Split the back-edge, inserting a new basic block on it, and modify the
134     // source BB's terminator accordingly.
135     BasicBlock *newBB = new BasicBlock("backEdgeInst", u->getParent());
136     BranchInst *ti = cast<BranchInst>(u->getTerminator());
137     unsigned char index = ((ti->getSuccessor(0) == BB) ? 0 : 1);
138
139     assert(ti->getNumSuccessors() > index && "Not enough successors!");
140     ti->setSuccessor(index, newBB);
141         
142     BasicBlock::InstListType &lt = newBB->getInstList();
143     lt.push_back(new CallInst(inCountMth));
144     new BranchInst(BB, newBB);
145       
146     // Now, set the sources of Phi nodes corresponding to the back-edge
147     // in BB to come from the instrumentation block instead.
148     for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end(); 
149         BB2Inst != BBend; ++BB2Inst) {
150       if (PHINode *phiInst = dyn_cast<PHINode>(BB2Inst)) {
151         int bbIndex = phiInst->getBasicBlockIndex(u);
152         if (bbIndex>=0)
153           phiInst->setIncomingBlock(bbIndex, newBB);
154       }
155     }
156   }
157 }
158
159 bool InstLoops::doInitialization (Module &M) {
160   inCountMth = M.getOrInsertFunction("llvm_first_trigger", Type::VoidTy, 0);
161   return true;  // Module was modified.
162 }
163
164 /// runOnFunction - Entry point for FunctionPass that inserts calls to
165 /// trigger function.
166 ///
167 bool InstLoops::runOnFunction(Function &F){
168   if (F.isExternal ())
169     return false;
170
171   DS = &getAnalysis<DominatorSet> ();
172
173   // Add a call to reoptimizerInitialize() to beginning of function named main.
174   if (F.getName() == "main")
175     InsertProfilingInitCall (&F, "reoptimizerInitialize");
176
177   findAndInstrumentBackEdges(F);
178   return true;  // Function was modified.
179 }
180
181 } // End llvm namespace