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