d81097b447a31a875890fad5f5e8e986d1896b18
[oota-llvm.git] / lib / Transforms / Instrumentation / RSProfiling.cpp
1 //===- RSProfiling.cpp - Various profiling using random sampling ----------===//
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 // These passes implement a random sampling based profiling.  Different methods
11 // of choosing when to sample are supported, as well as different types of
12 // profiling.  This is done as two passes.  The first is a sequence of profiling
13 // passes which insert profiling into the program, and remember what they 
14 // inserted.
15 //
16 // The second stage duplicates all instructions in a function, ignoring the 
17 // profiling code, then connects the two versions togeather at the entry and at
18 // backedges.  At each connection point a choice is made as to whether to jump
19 // to the profiled code (take a sample) or execute the unprofiled code.
20 //
21 // It is highly recommended that after this pass one runs mem2reg and adce
22 // (instcombine load-vn gdce dse also are good to run afterwards)
23 //
24 // This design is intended to make the profiling passes independent of the RS
25 // framework, but any profiling pass that implements the RSProfiling interface
26 // is compatible with the rs framework (and thus can be sampled)
27 //
28 // TODO: obviously the block and function profiling are almost identical to the
29 // existing ones, so they can be unified (esp since these passes are valid
30 // without the rs framework).
31 // TODO: Fix choice code so that frequency is not hard coded
32 //
33 //===----------------------------------------------------------------------===//
34
35 #include "llvm/Pass.h"
36 #include "llvm/Module.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Constants.h"
39 #include "llvm/DerivedTypes.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Transforms/Instrumentation.h"
46 #include "RSProfiling.h"
47 #include <set>
48 #include <map>
49 #include <queue>
50 #include <list>
51 using namespace llvm;
52
53 namespace {
54   enum RandomMeth {
55     GBV, GBVO, HOSTCC
56   };
57
58   cl::opt<RandomMeth> RandomMethod("profile-randomness",
59       cl::desc("How to randomly choose to profile:"),
60       cl::values(
61                  clEnumValN(GBV, "global", "global counter"),
62                  clEnumValN(GBVO, "ra_global", 
63                             "register allocated global counter"),
64                  clEnumValN(HOSTCC, "rdcc", "cycle counter"),
65                  clEnumValEnd));
66   
67   /// NullProfilerRS - The basic profiler that does nothing.  It is the default
68   /// profiler and thus terminates RSProfiler chains.  It is useful for 
69   /// measuring framework overhead
70   class VISIBILITY_HIDDEN NullProfilerRS : public RSProfilers {
71   public:
72     static char ID; // Pass identification, replacement for typeid
73     bool isProfiling(Value* v) {
74       return false;
75     }
76     bool runOnModule(Module &M) {
77       return false;
78     }
79     void getAnalysisUsage(AnalysisUsage &AU) const {
80       AU.setPreservesAll();
81     }
82   };
83
84   static RegisterAnalysisGroup<RSProfilers> A("Profiling passes");
85   static RegisterPass<NullProfilerRS> NP("insert-null-profiling-rs",
86                                          "Measure profiling framework overhead");
87   static RegisterAnalysisGroup<RSProfilers, true> NPT(NP);
88
89   /// Chooser - Something that chooses when to make a sample of the profiled code
90   class VISIBILITY_HIDDEN Chooser {
91   public:
92     /// ProcessChoicePoint - is called for each basic block inserted to choose 
93     /// between normal and sample code
94     virtual void ProcessChoicePoint(BasicBlock*) = 0;
95     /// PrepFunction - is called once per function before other work is done.
96     /// This gives the opertunity to insert new allocas and such.
97     virtual void PrepFunction(Function*) = 0;
98     virtual ~Chooser() {}
99   };
100
101   //Things that implement sampling policies
102   //A global value that is read-mod-stored to choose when to sample.
103   //A sample is taken when the global counter hits 0
104   class VISIBILITY_HIDDEN GlobalRandomCounter : public Chooser {
105     GlobalVariable* Counter;
106     Value* ResetValue;
107     const Type* T;
108   public:
109     GlobalRandomCounter(Module& M, const Type* t, uint64_t resetval);
110     virtual ~GlobalRandomCounter();
111     virtual void PrepFunction(Function* F);
112     virtual void ProcessChoicePoint(BasicBlock* bb);
113   };
114
115   //Same is GRC, but allow register allocation of the global counter
116   class VISIBILITY_HIDDEN GlobalRandomCounterOpt : public Chooser {
117     GlobalVariable* Counter;
118     Value* ResetValue;
119     AllocaInst* AI;
120     const Type* T;
121   public:
122     GlobalRandomCounterOpt(Module& M, const Type* t, uint64_t resetval);
123     virtual ~GlobalRandomCounterOpt();
124     virtual void PrepFunction(Function* F);
125     virtual void ProcessChoicePoint(BasicBlock* bb);
126   };
127
128   //Use the cycle counter intrinsic as a source of pseudo randomness when
129   //deciding when to sample.
130   class VISIBILITY_HIDDEN CycleCounter : public Chooser {
131     uint64_t rm;
132     Constant *F;
133   public:
134     CycleCounter(Module& m, uint64_t resetmask);
135     virtual ~CycleCounter();
136     virtual void PrepFunction(Function* F);
137     virtual void ProcessChoicePoint(BasicBlock* bb);
138   };
139
140   /// ProfilerRS - Insert the random sampling framework
141   struct VISIBILITY_HIDDEN ProfilerRS : public FunctionPass {
142     static char ID; // Pass identification, replacement for typeid
143     ProfilerRS() : FunctionPass((intptr_t)&ID) {}
144
145     std::map<Value*, Value*> TransCache;
146     std::set<BasicBlock*> ChoicePoints;
147     Chooser* c;
148
149     //Translate and duplicate values for the new profile free version of stuff
150     Value* Translate(Value* v);
151     //Duplicate an entire function (with out profiling)
152     void Duplicate(Function& F, RSProfilers& LI);
153     //Called once for each backedge, handle the insertion of choice points and
154     //the interconection of the two versions of the code
155     void ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F);
156     bool runOnFunction(Function& F);
157     bool doInitialization(Module &M);
158     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
159   };
160
161   RegisterPass<ProfilerRS> X("insert-rs-profiling-framework",
162                              "Insert random sampling instrumentation framework");
163 }
164
165 char RSProfilers::ID = 0;
166 char NullProfilerRS::ID = 0;
167 char ProfilerRS::ID = 0;
168
169 //Local utilities
170 static void ReplacePhiPred(BasicBlock* btarget, 
171                            BasicBlock* bold, BasicBlock* bnew);
172
173 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc);
174
175 template<class T>
176 static void recBackEdge(BasicBlock* bb, T& BackEdges, 
177                         std::map<BasicBlock*, int>& color,
178                         std::map<BasicBlock*, int>& depth,
179                         std::map<BasicBlock*, int>& finish,
180                         int& time);
181
182 //find the back edges and where they go to
183 template<class T>
184 static void getBackEdges(Function& F, T& BackEdges);
185
186
187 ///////////////////////////////////////
188 // Methods of choosing when to profile
189 ///////////////////////////////////////
190   
191 GlobalRandomCounter::GlobalRandomCounter(Module& M, const Type* t, 
192                                          uint64_t resetval) : T(t) {
193   ConstantInt* Init = ConstantInt::get(T, resetval); 
194   ResetValue = Init;
195   Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
196                                Init, "RandomSteeringCounter", &M);
197 }
198
199 GlobalRandomCounter::~GlobalRandomCounter() {}
200
201 void GlobalRandomCounter::PrepFunction(Function* F) {}
202
203 void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) {
204   BranchInst* t = cast<BranchInst>(bb->getTerminator());
205   
206   //decrement counter
207   LoadInst* l = new LoadInst(Counter, "counter", t);
208   
209   ICmpInst* s = new ICmpInst(ICmpInst::ICMP_EQ, l, ConstantInt::get(T, 0), 
210                              "countercc", t);
211
212   Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
213                                         "counternew", t);
214   new StoreInst(nv, Counter, t);
215   t->setCondition(s);
216   
217   //reset counter
218   BasicBlock* oldnext = t->getSuccessor(0);
219   BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(), 
220                                           oldnext);
221   TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
222   t->setSuccessor(0, resetblock);
223   new StoreInst(ResetValue, Counter, t2);
224   ReplacePhiPred(oldnext, bb, resetblock);
225 }
226
227 GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const Type* t, 
228                                                uint64_t resetval) 
229   : AI(0), T(t) {
230   ConstantInt* Init = ConstantInt::get(T, resetval);
231   ResetValue  = Init;
232   Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
233                                Init, "RandomSteeringCounter", &M);
234 }
235
236 GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {}
237
238 void GlobalRandomCounterOpt::PrepFunction(Function* F) {
239   //make a local temporary to cache the global
240   BasicBlock& bb = F->getEntryBlock();
241   BasicBlock::iterator InsertPt = bb.begin();
242   AI = new AllocaInst(T, 0, "localcounter", InsertPt);
243   LoadInst* l = new LoadInst(Counter, "counterload", InsertPt);
244   new StoreInst(l, AI, InsertPt);
245   
246   //modify all functions and return values to restore the local variable to/from
247   //the global variable
248   for(Function::iterator fib = F->begin(), fie = F->end();
249       fib != fie; ++fib)
250     for(BasicBlock::iterator bib = fib->begin(), bie = fib->end();
251         bib != bie; ++bib)
252       if (isa<CallInst>(bib)) {
253         LoadInst* l = new LoadInst(AI, "counter", bib);
254         new StoreInst(l, Counter, bib);
255         l = new LoadInst(Counter, "counter", ++bib);
256         new StoreInst(l, AI, bib--);
257       } else if (isa<InvokeInst>(bib)) {
258         LoadInst* l = new LoadInst(AI, "counter", bib);
259         new StoreInst(l, Counter, bib);
260         
261         BasicBlock* bb = cast<InvokeInst>(bib)->getNormalDest();
262         BasicBlock::iterator i = bb->begin();
263         while (isa<PHINode>(i))
264           ++i;
265         l = new LoadInst(Counter, "counter", i);
266         
267         bb = cast<InvokeInst>(bib)->getUnwindDest();
268         i = bb->begin();
269         while (isa<PHINode>(i)) ++i;
270         l = new LoadInst(Counter, "counter", i);
271         new StoreInst(l, AI, i);
272       } else if (isa<UnwindInst>(&*bib) || isa<ReturnInst>(&*bib)) {
273         LoadInst* l = new LoadInst(AI, "counter", bib);
274         new StoreInst(l, Counter, bib);
275       }
276 }
277
278 void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) {
279   BranchInst* t = cast<BranchInst>(bb->getTerminator());
280   
281   //decrement counter
282   LoadInst* l = new LoadInst(AI, "counter", t);
283   
284   ICmpInst* s = new ICmpInst(ICmpInst::ICMP_EQ, l, ConstantInt::get(T, 0), 
285                              "countercc", t);
286
287   Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
288                                         "counternew", t);
289   new StoreInst(nv, AI, t);
290   t->setCondition(s);
291   
292   //reset counter
293   BasicBlock* oldnext = t->getSuccessor(0);
294   BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(), 
295                                           oldnext);
296   TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
297   t->setSuccessor(0, resetblock);
298   new StoreInst(ResetValue, AI, t2);
299   ReplacePhiPred(oldnext, bb, resetblock);
300 }
301
302
303 CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) {
304   F = m.getOrInsertFunction("llvm.readcyclecounter", Type::Int64Ty, NULL);
305 }
306
307 CycleCounter::~CycleCounter() {}
308
309 void CycleCounter::PrepFunction(Function* F) {}
310
311 void CycleCounter::ProcessChoicePoint(BasicBlock* bb) {
312   BranchInst* t = cast<BranchInst>(bb->getTerminator());
313   
314   CallInst* c = new CallInst(F, "rdcc", t);
315   BinaryOperator* b = 
316     BinaryOperator::createAnd(c, ConstantInt::get(Type::Int64Ty, rm),
317                               "mrdcc", t);
318   
319   ICmpInst *s = new ICmpInst(ICmpInst::ICMP_EQ, b,
320                              ConstantInt::get(Type::Int64Ty, 0), 
321                              "mrdccc", t);
322
323   t->setCondition(s);
324 }
325
326 ///////////////////////////////////////
327 // Profiling:
328 ///////////////////////////////////////
329 bool RSProfilers_std::isProfiling(Value* v) {
330   if (profcode.find(v) != profcode.end())
331     return true;
332   //else
333   RSProfilers& LI = getAnalysis<RSProfilers>();
334   return LI.isProfiling(v);
335 }
336
337 void RSProfilers_std::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
338                                           GlobalValue *CounterArray) {
339   // Insert the increment after any alloca or PHI instructions...
340   BasicBlock::iterator InsertPos = BB->begin();
341   while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
342     ++InsertPos;
343   
344   // Create the getelementptr constant expression
345   std::vector<Constant*> Indices(2);
346   Indices[0] = Constant::getNullValue(Type::Int32Ty);
347   Indices[1] = ConstantInt::get(Type::Int32Ty, CounterNum);
348   Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray,
349                                                         &Indices[0], 2);
350   
351   // Load, increment and store the value back.
352   Value *OldVal = new LoadInst(ElementPtr, "OldCounter", InsertPos);
353   profcode.insert(OldVal);
354   Value *NewVal = BinaryOperator::createAdd(OldVal,
355                                             ConstantInt::get(Type::Int32Ty, 1),
356                                             "NewCounter", InsertPos);
357   profcode.insert(NewVal);
358   profcode.insert(new StoreInst(NewVal, ElementPtr, InsertPos));
359 }
360
361 void RSProfilers_std::getAnalysisUsage(AnalysisUsage &AU) const {
362   //grab any outstanding profiler, or get the null one
363   AU.addRequired<RSProfilers>();
364 }
365
366 ///////////////////////////////////////
367 // RS Framework
368 ///////////////////////////////////////
369
370 Value* ProfilerRS::Translate(Value* v) {
371   if(TransCache[v])
372     return TransCache[v];
373   
374   if (BasicBlock* bb = dyn_cast<BasicBlock>(v)) {
375     if (bb == &bb->getParent()->getEntryBlock())
376       TransCache[bb] = bb; //don't translate entry block
377     else
378       TransCache[bb] = new BasicBlock("dup_" + bb->getName(), bb->getParent(), 
379                                       NULL);
380     return TransCache[bb];
381   } else if (Instruction* i = dyn_cast<Instruction>(v)) {
382     //we have already translated this
383     //do not translate entry block allocas
384     if(&i->getParent()->getParent()->getEntryBlock() == i->getParent()) {
385       TransCache[i] = i;
386       return i;
387     } else {
388       //translate this
389       Instruction* i2 = i->clone();
390       if (i->hasName())
391         i2->setName("dup_" + i->getName());
392       TransCache[i] = i2;
393       //NumNewInst++;
394       for (unsigned x = 0; x < i2->getNumOperands(); ++x)
395         i2->setOperand(x, Translate(i2->getOperand(x)));
396       return i2;
397     }
398   } else if (isa<Function>(v) || isa<Constant>(v) || isa<Argument>(v)) {
399     TransCache[v] = v;
400     return v;
401   }
402   assert(0 && "Value not handled");
403   return 0;
404 }
405
406 void ProfilerRS::Duplicate(Function& F, RSProfilers& LI)
407 {
408   //perform a breadth first search, building up a duplicate of the code
409   std::queue<BasicBlock*> worklist;
410   std::set<BasicBlock*> seen;
411   
412   //This loop ensures proper BB order, to help performance
413   for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib)
414     worklist.push(fib);
415   while (!worklist.empty()) {
416     Translate(worklist.front());
417     worklist.pop();
418   }
419   
420   //remember than reg2mem created a new entry block we don't want to duplicate
421   worklist.push(F.getEntryBlock().getTerminator()->getSuccessor(0));
422   seen.insert(&F.getEntryBlock());
423   
424   while (!worklist.empty()) {
425     BasicBlock* bb = worklist.front();
426     worklist.pop();
427     if(seen.find(bb) == seen.end()) {
428       BasicBlock* bbtarget = cast<BasicBlock>(Translate(bb));
429       BasicBlock::InstListType& instlist = bbtarget->getInstList();
430       for (BasicBlock::iterator iib = bb->begin(), iie = bb->end(); 
431            iib != iie; ++iib) {
432         //NumOldInst++;
433         if (!LI.isProfiling(&*iib)) {
434           Instruction* i = cast<Instruction>(Translate(iib));
435           instlist.insert(bbtarget->end(), i);
436         }
437       }
438       //updated search state;
439       seen.insert(bb);
440       TerminatorInst* ti = bb->getTerminator();
441       for (unsigned x = 0; x < ti->getNumSuccessors(); ++x) {
442         BasicBlock* bbs = ti->getSuccessor(x);
443         if (seen.find(bbs) == seen.end()) {
444           worklist.push(bbs);
445         }
446       }
447     }
448   }
449 }
450
451 void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) {
452   //given a backedge from B -> A, and translations A' and B',
453   //a: insert C and C'
454   //b: add branches in C to A and A' and in C' to A and A'
455   //c: mod terminators@B, replace A with C
456   //d: mod terminators@B', replace A' with C'
457   //e: mod phis@A for pred B to be pred C
458   //       if multiple entries, simplify to one
459   //f: mod phis@A' for pred B' to be pred C'
460   //       if multiple entries, simplify to one
461   //g: for all phis@A with pred C using x
462   //       add in edge from C' using x'
463   //       add in edge from C using x in A'
464   
465   //a:
466   Function::iterator BBN = src; ++BBN;
467   BasicBlock* bbC = new BasicBlock("choice", &F, BBN);
468   //ChoicePoints.insert(bbC);
469   BBN = cast<BasicBlock>(Translate(src));
470   BasicBlock* bbCp = new BasicBlock("choice", &F, ++BBN);
471   ChoicePoints.insert(bbCp);
472   
473   //b:
474   new BranchInst(cast<BasicBlock>(Translate(dst)), bbC);
475   new BranchInst(dst, cast<BasicBlock>(Translate(dst)), 
476                  ConstantInt::get(Type::Int1Ty, true), bbCp);
477   //c:
478   {
479     TerminatorInst* iB = src->getTerminator();
480     for (unsigned x = 0; x < iB->getNumSuccessors(); ++x)
481       if (iB->getSuccessor(x) == dst)
482         iB->setSuccessor(x, bbC);
483   }
484   //d:
485   {
486     TerminatorInst* iBp = cast<TerminatorInst>(Translate(src->getTerminator()));
487     for (unsigned x = 0; x < iBp->getNumSuccessors(); ++x)
488       if (iBp->getSuccessor(x) == cast<BasicBlock>(Translate(dst)))
489         iBp->setSuccessor(x, bbCp);
490   }
491   //e:
492   ReplacePhiPred(dst, src, bbC);
493   //src could be a switch, in which case we are replacing several edges with one
494   //thus collapse those edges int the Phi
495   CollapsePhi(dst, bbC);
496   //f:
497   ReplacePhiPred(cast<BasicBlock>(Translate(dst)),
498                  cast<BasicBlock>(Translate(src)),bbCp);
499   CollapsePhi(cast<BasicBlock>(Translate(dst)), bbCp);
500   //g:
501   for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie;
502       ++ib)
503     if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
504       for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
505         if(bbC == phi->getIncomingBlock(x)) {
506           phi->addIncoming(Translate(phi->getIncomingValue(x)), bbCp);
507           cast<PHINode>(Translate(phi))->addIncoming(phi->getIncomingValue(x), 
508                                                      bbC);
509         }
510       phi->removeIncomingValue(bbC);
511     }
512 }
513
514 bool ProfilerRS::runOnFunction(Function& F) {
515   if (!F.isDeclaration()) {
516     std::set<std::pair<BasicBlock*, BasicBlock*> > BackEdges;
517     RSProfilers& LI = getAnalysis<RSProfilers>();
518     
519     getBackEdges(F, BackEdges);
520     Duplicate(F, LI);
521     //assume that stuff worked.  now connect the duplicated basic blocks 
522     //with the originals in such a way as to preserve ssa.  yuk!
523     for (std::set<std::pair<BasicBlock*, BasicBlock*> >::iterator 
524            ib = BackEdges.begin(), ie = BackEdges.end(); ib != ie; ++ib)
525       ProcessBackEdge(ib->first, ib->second, F);
526     
527     //oh, and add the edge from the reg2mem created entry node to the 
528     //duplicated second node
529     TerminatorInst* T = F.getEntryBlock().getTerminator();
530     ReplaceInstWithInst(T, new BranchInst(T->getSuccessor(0),
531                                           cast<BasicBlock>(
532                                             Translate(T->getSuccessor(0))),
533                                           ConstantInt::get(Type::Int1Ty, true)));
534     
535     //do whatever is needed now that the function is duplicated
536     c->PrepFunction(&F);
537     
538     //add entry node to choice points
539     ChoicePoints.insert(&F.getEntryBlock());
540     
541     for (std::set<BasicBlock*>::iterator 
542            ii = ChoicePoints.begin(), ie = ChoicePoints.end(); ii != ie; ++ii)
543       c->ProcessChoicePoint(*ii);
544     
545     ChoicePoints.clear();
546     TransCache.clear();
547     
548     return true;
549   }
550   return false;
551 }
552
553 bool ProfilerRS::doInitialization(Module &M) {
554   switch (RandomMethod) {
555   case GBV:
556     c = new GlobalRandomCounter(M, Type::Int32Ty, (1 << 14) - 1);
557     break;
558   case GBVO:
559     c = new GlobalRandomCounterOpt(M, Type::Int32Ty, (1 << 14) - 1);
560     break;
561   case HOSTCC:
562     c = new CycleCounter(M, (1 << 14) - 1);
563     break;
564   };
565   return true;
566 }
567
568 void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const {
569   AU.addRequired<RSProfilers>();
570   AU.addRequiredID(DemoteRegisterToMemoryID);
571 }
572
573 ///////////////////////////////////////
574 // Utilities:
575 ///////////////////////////////////////
576 static void ReplacePhiPred(BasicBlock* btarget, 
577                            BasicBlock* bold, BasicBlock* bnew) {
578   for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
579       ib != ie; ++ib)
580     if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
581       for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
582         if(bold == phi->getIncomingBlock(x))
583           phi->setIncomingBlock(x, bnew);
584     }
585 }
586
587 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) {
588   for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
589       ib != ie; ++ib)
590     if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
591       std::map<BasicBlock*, Value*> counter;
592       for(unsigned i = 0; i < phi->getNumIncomingValues(); ) {
593         if (counter[phi->getIncomingBlock(i)]) {
594           assert(phi->getIncomingValue(i) == counter[phi->getIncomingBlock(i)]);
595           phi->removeIncomingValue(i, false);
596         } else {
597           counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i);
598           ++i;
599         }
600       }
601     } 
602 }
603
604 template<class T>
605 static void recBackEdge(BasicBlock* bb, T& BackEdges, 
606                         std::map<BasicBlock*, int>& color,
607                         std::map<BasicBlock*, int>& depth,
608                         std::map<BasicBlock*, int>& finish,
609                         int& time)
610 {
611   color[bb] = 1;
612   ++time;
613   depth[bb] = time;
614   TerminatorInst* t= bb->getTerminator();
615   for(unsigned i = 0; i < t->getNumSuccessors(); ++i) {
616     BasicBlock* bbnew = t->getSuccessor(i);
617     if (color[bbnew] == 0)
618       recBackEdge(bbnew, BackEdges, color, depth, finish, time);
619     else if (color[bbnew] == 1) {
620       BackEdges.insert(std::make_pair(bb, bbnew));
621       //NumBackEdges++;
622     }
623   }
624   color[bb] = 2;
625   ++time;
626   finish[bb] = time;
627 }
628
629
630
631 //find the back edges and where they go to
632 template<class T>
633 static void getBackEdges(Function& F, T& BackEdges) {
634   std::map<BasicBlock*, int> color;
635   std::map<BasicBlock*, int> depth;
636   std::map<BasicBlock*, int> finish;
637   int time = 0;
638   recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time);
639   DOUT << F.getName() << " " << BackEdges.size() << "\n";
640 }
641
642
643 //Creation functions
644 ModulePass* llvm::createNullProfilerRSPass() {
645   return new NullProfilerRS();
646 }
647
648 FunctionPass* llvm::createRSProfilingPass() {
649   return new ProfilerRS();
650 }