1 //===- RSProfiling.cpp - Various profiling using random sampling ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
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.
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)
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)
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
33 //===----------------------------------------------------------------------===//
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"
58 cl::opt<RandomMeth> RandomMethod("profile-randomness",
59 cl::desc("How to randomly choose to profile:"),
61 clEnumValN(GBV, "global", "global counter"),
62 clEnumValN(GBVO, "ra_global",
63 "register allocated global counter"),
64 clEnumValN(HOSTCC, "rdcc", "cycle counter"),
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 {
72 static char ID; // Pass identification, replacement for typeid
73 bool isProfiling(Value* v) {
76 bool runOnModule(Module &M) {
79 void getAnalysisUsage(AnalysisUsage &AU) const {
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);
89 /// Chooser - Something that chooses when to make a sample of the profiled code
90 class VISIBILITY_HIDDEN Chooser {
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;
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;
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);
115 //Same is GRC, but allow register allocation of the global counter
116 class VISIBILITY_HIDDEN GlobalRandomCounterOpt : public Chooser {
117 GlobalVariable* Counter;
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);
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 {
134 CycleCounter(Module& m, uint64_t resetmask);
135 virtual ~CycleCounter();
136 virtual void PrepFunction(Function* F);
137 virtual void ProcessChoicePoint(BasicBlock* bb);
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) {}
145 std::map<Value*, Value*> TransCache;
146 std::set<BasicBlock*> ChoicePoints;
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;
161 RegisterPass<ProfilerRS> X("insert-rs-profiling-framework",
162 "Insert random sampling instrumentation framework");
165 char RSProfilers::ID = 0;
166 char NullProfilerRS::ID = 0;
167 char ProfilerRS::ID = 0;
170 static void ReplacePhiPred(BasicBlock* btarget,
171 BasicBlock* bold, BasicBlock* bnew);
173 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc);
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,
182 //find the back edges and where they go to
184 static void getBackEdges(Function& F, T& BackEdges);
187 ///////////////////////////////////////
188 // Methods of choosing when to profile
189 ///////////////////////////////////////
191 GlobalRandomCounter::GlobalRandomCounter(Module& M, const Type* t,
192 uint64_t resetval) : T(t) {
193 ConstantInt* Init = ConstantInt::get(T, resetval);
195 Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
196 Init, "RandomSteeringCounter", &M);
199 GlobalRandomCounter::~GlobalRandomCounter() {}
201 void GlobalRandomCounter::PrepFunction(Function* F) {}
203 void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) {
204 BranchInst* t = cast<BranchInst>(bb->getTerminator());
207 LoadInst* l = new LoadInst(Counter, "counter", t);
209 ICmpInst* s = new ICmpInst(ICmpInst::ICMP_EQ, l, ConstantInt::get(T, 0),
212 Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
214 new StoreInst(nv, Counter, t);
218 BasicBlock* oldnext = t->getSuccessor(0);
219 BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(),
221 TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
222 t->setSuccessor(0, resetblock);
223 new StoreInst(ResetValue, Counter, t2);
224 ReplacePhiPred(oldnext, bb, resetblock);
227 GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const Type* t,
230 ConstantInt* Init = ConstantInt::get(T, resetval);
232 Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
233 Init, "RandomSteeringCounter", &M);
236 GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {}
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);
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();
250 for(BasicBlock::iterator bib = fib->begin(), bie = fib->end();
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);
261 BasicBlock* bb = cast<InvokeInst>(bib)->getNormalDest();
262 BasicBlock::iterator i = bb->begin();
263 while (isa<PHINode>(i))
265 l = new LoadInst(Counter, "counter", i);
267 bb = cast<InvokeInst>(bib)->getUnwindDest();
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);
278 void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) {
279 BranchInst* t = cast<BranchInst>(bb->getTerminator());
282 LoadInst* l = new LoadInst(AI, "counter", t);
284 ICmpInst* s = new ICmpInst(ICmpInst::ICMP_EQ, l, ConstantInt::get(T, 0),
287 Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
289 new StoreInst(nv, AI, t);
293 BasicBlock* oldnext = t->getSuccessor(0);
294 BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(),
296 TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
297 t->setSuccessor(0, resetblock);
298 new StoreInst(ResetValue, AI, t2);
299 ReplacePhiPred(oldnext, bb, resetblock);
303 CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) {
304 F = m.getOrInsertFunction("llvm.readcyclecounter", Type::Int64Ty, NULL);
307 CycleCounter::~CycleCounter() {}
309 void CycleCounter::PrepFunction(Function* F) {}
311 void CycleCounter::ProcessChoicePoint(BasicBlock* bb) {
312 BranchInst* t = cast<BranchInst>(bb->getTerminator());
314 CallInst* c = new CallInst(F, "rdcc", t);
316 BinaryOperator::createAnd(c, ConstantInt::get(Type::Int64Ty, rm),
319 ICmpInst *s = new ICmpInst(ICmpInst::ICMP_EQ, b,
320 ConstantInt::get(Type::Int64Ty, 0),
326 ///////////////////////////////////////
328 ///////////////////////////////////////
329 bool RSProfilers_std::isProfiling(Value* v) {
330 if (profcode.find(v) != profcode.end())
333 RSProfilers& LI = getAnalysis<RSProfilers>();
334 return LI.isProfiling(v);
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))
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,
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));
361 void RSProfilers_std::getAnalysisUsage(AnalysisUsage &AU) const {
362 //grab any outstanding profiler, or get the null one
363 AU.addRequired<RSProfilers>();
366 ///////////////////////////////////////
368 ///////////////////////////////////////
370 Value* ProfilerRS::Translate(Value* v) {
372 return TransCache[v];
374 if (BasicBlock* bb = dyn_cast<BasicBlock>(v)) {
375 if (bb == &bb->getParent()->getEntryBlock())
376 TransCache[bb] = bb; //don't translate entry block
378 TransCache[bb] = new BasicBlock("dup_" + bb->getName(), bb->getParent(),
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()) {
389 Instruction* i2 = i->clone();
391 i2->setName("dup_" + i->getName());
394 for (unsigned x = 0; x < i2->getNumOperands(); ++x)
395 i2->setOperand(x, Translate(i2->getOperand(x)));
398 } else if (isa<Function>(v) || isa<Constant>(v) || isa<Argument>(v)) {
402 assert(0 && "Value not handled");
406 void ProfilerRS::Duplicate(Function& F, RSProfilers& LI)
408 //perform a breadth first search, building up a duplicate of the code
409 std::queue<BasicBlock*> worklist;
410 std::set<BasicBlock*> seen;
412 //This loop ensures proper BB order, to help performance
413 for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib)
415 while (!worklist.empty()) {
416 Translate(worklist.front());
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());
424 while (!worklist.empty()) {
425 BasicBlock* bb = worklist.front();
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();
433 if (!LI.isProfiling(&*iib)) {
434 Instruction* i = cast<Instruction>(Translate(iib));
435 instlist.insert(bbtarget->end(), i);
438 //updated search state;
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()) {
451 void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) {
452 //given a backedge from B -> A, and translations A' and B',
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'
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);
474 new BranchInst(cast<BasicBlock>(Translate(dst)), bbC);
475 new BranchInst(dst, cast<BasicBlock>(Translate(dst)),
476 ConstantInt::get(Type::Int1Ty, true), bbCp);
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);
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);
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);
497 ReplacePhiPred(cast<BasicBlock>(Translate(dst)),
498 cast<BasicBlock>(Translate(src)),bbCp);
499 CollapsePhi(cast<BasicBlock>(Translate(dst)), bbCp);
501 for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie;
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),
510 phi->removeIncomingValue(bbC);
514 bool ProfilerRS::runOnFunction(Function& F) {
515 if (!F.isDeclaration()) {
516 std::set<std::pair<BasicBlock*, BasicBlock*> > BackEdges;
517 RSProfilers& LI = getAnalysis<RSProfilers>();
519 getBackEdges(F, BackEdges);
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);
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),
532 Translate(T->getSuccessor(0))),
533 ConstantInt::get(Type::Int1Ty, true)));
535 //do whatever is needed now that the function is duplicated
538 //add entry node to choice points
539 ChoicePoints.insert(&F.getEntryBlock());
541 for (std::set<BasicBlock*>::iterator
542 ii = ChoicePoints.begin(), ie = ChoicePoints.end(); ii != ie; ++ii)
543 c->ProcessChoicePoint(*ii);
545 ChoicePoints.clear();
553 bool ProfilerRS::doInitialization(Module &M) {
554 switch (RandomMethod) {
556 c = new GlobalRandomCounter(M, Type::Int32Ty, (1 << 14) - 1);
559 c = new GlobalRandomCounterOpt(M, Type::Int32Ty, (1 << 14) - 1);
562 c = new CycleCounter(M, (1 << 14) - 1);
568 void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const {
569 AU.addRequired<RSProfilers>();
570 AU.addRequiredID(DemoteRegisterToMemoryID);
573 ///////////////////////////////////////
575 ///////////////////////////////////////
576 static void ReplacePhiPred(BasicBlock* btarget,
577 BasicBlock* bold, BasicBlock* bnew) {
578 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
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);
587 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) {
588 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
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);
597 counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i);
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,
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));
631 //find the back edges and where they go to
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;
638 recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time);
639 DOUT << F.getName() << " " << BackEdges.size() << "\n";
644 ModulePass* llvm::createNullProfilerRSPass() {
645 return new NullProfilerRS();
648 FunctionPass* llvm::createRSProfilingPass() {
649 return new ProfilerRS();