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