blob: 30c2dc7162a46370ac15d9776cd48ae52a9100e3 [file] [log] [blame]
Andrew Lenharth701f5ac2005-11-28 00:58:09 +00001//===- RSProfiling.cpp - Various profiling using random sampling ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Andrew Lenharth701f5ac2005-11-28 00:58:09 +00007//
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
Andrew Lenharthbb227c12005-11-28 18:00:38 +000013// passes which insert profiling into the program, and remember what they
14// inserted.
15//
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000016// 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//
Gordon Henriksen55cbec32007-10-26 03:03:51 +000021// It is highly recommended that after this pass one runs mem2reg and adce
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000022// (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"
Owen Anderson50895512009-07-06 18:42:36 +000036#include "llvm/LLVMContext.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000037#include "llvm/Module.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000038#include "llvm/Instructions.h"
39#include "llvm/Constants.h"
40#include "llvm/DerivedTypes.h"
Duncan Sandse2c43042008-04-07 13:45:04 +000041#include "llvm/Intrinsics.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000042#include "llvm/Transforms/Scalar.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000044#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000045#include "llvm/Support/Compiler.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000046#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000047#include "llvm/Support/ErrorHandling.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000048#include "llvm/Transforms/Instrumentation.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000049#include "RSProfiling.h"
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000050#include <set>
51#include <map>
52#include <queue>
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000053using namespace llvm;
54
55namespace {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000056 enum RandomMeth {
57 GBV, GBVO, HOSTCC
58 };
Dan Gohman844731a2008-05-13 00:00:25 +000059}
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000060
Dan Gohman844731a2008-05-13 00:00:25 +000061static cl::opt<RandomMeth> RandomMethod("profile-randomness",
62 cl::desc("How to randomly choose to profile:"),
63 cl::values(
64 clEnumValN(GBV, "global", "global counter"),
65 clEnumValN(GBVO, "ra_global",
66 "register allocated global counter"),
67 clEnumValN(HOSTCC, "rdcc", "cycle counter"),
68 clEnumValEnd));
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000069
Dan Gohman844731a2008-05-13 00:00:25 +000070namespace {
Andrew Lenharth8dc2d502005-11-28 18:10:59 +000071 /// NullProfilerRS - The basic profiler that does nothing. It is the default
72 /// profiler and thus terminates RSProfiler chains. It is useful for
73 /// measuring framework overhead
Reid Spencer9133fe22007-02-05 23:32:05 +000074 class VISIBILITY_HIDDEN NullProfilerRS : public RSProfilers {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000075 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000076 static char ID; // Pass identification, replacement for typeid
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000077 bool isProfiling(Value* v) {
78 return false;
79 }
80 bool runOnModule(Module &M) {
81 return false;
82 }
83 void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.setPreservesAll();
85 }
86 };
Dan Gohman844731a2008-05-13 00:00:25 +000087}
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000088
Dan Gohman844731a2008-05-13 00:00:25 +000089static RegisterAnalysisGroup<RSProfilers> A("Profiling passes");
90static RegisterPass<NullProfilerRS> NP("insert-null-profiling-rs",
91 "Measure profiling framework overhead");
92static RegisterAnalysisGroup<RSProfilers, true> NPT(NP);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000093
Dan Gohman844731a2008-05-13 00:00:25 +000094namespace {
Andrew Lenharth8dc2d502005-11-28 18:10:59 +000095 /// Chooser - Something that chooses when to make a sample of the profiled code
Reid Spencer9133fe22007-02-05 23:32:05 +000096 class VISIBILITY_HIDDEN Chooser {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +000097 public:
Andrew Lenharth8dc2d502005-11-28 18:10:59 +000098 /// ProcessChoicePoint - is called for each basic block inserted to choose
99 /// between normal and sample code
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000100 virtual void ProcessChoicePoint(BasicBlock*) = 0;
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000101 /// PrepFunction - is called once per function before other work is done.
102 /// This gives the opertunity to insert new allocas and such.
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000103 virtual void PrepFunction(Function*) = 0;
104 virtual ~Chooser() {}
105 };
106
107 //Things that implement sampling policies
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000108 //A global value that is read-mod-stored to choose when to sample.
109 //A sample is taken when the global counter hits 0
Reid Spencer9133fe22007-02-05 23:32:05 +0000110 class VISIBILITY_HIDDEN GlobalRandomCounter : public Chooser {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000111 GlobalVariable* Counter;
112 Value* ResetValue;
Dan Gohman6de29f82009-06-15 22:12:54 +0000113 const IntegerType* T;
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000114 public:
Dan Gohman6de29f82009-06-15 22:12:54 +0000115 GlobalRandomCounter(Module& M, const IntegerType* t, uint64_t resetval);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000116 virtual ~GlobalRandomCounter();
117 virtual void PrepFunction(Function* F);
118 virtual void ProcessChoicePoint(BasicBlock* bb);
119 };
120
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000121 //Same is GRC, but allow register allocation of the global counter
Reid Spencer9133fe22007-02-05 23:32:05 +0000122 class VISIBILITY_HIDDEN GlobalRandomCounterOpt : public Chooser {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000123 GlobalVariable* Counter;
124 Value* ResetValue;
125 AllocaInst* AI;
Dan Gohman6de29f82009-06-15 22:12:54 +0000126 const IntegerType* T;
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000127 public:
Dan Gohman6de29f82009-06-15 22:12:54 +0000128 GlobalRandomCounterOpt(Module& M, const IntegerType* t, uint64_t resetval);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000129 virtual ~GlobalRandomCounterOpt();
130 virtual void PrepFunction(Function* F);
131 virtual void ProcessChoicePoint(BasicBlock* bb);
132 };
133
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000134 //Use the cycle counter intrinsic as a source of pseudo randomness when
135 //deciding when to sample.
Reid Spencer9133fe22007-02-05 23:32:05 +0000136 class VISIBILITY_HIDDEN CycleCounter : public Chooser {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000137 uint64_t rm;
Chris Lattnerfebe5f12007-01-07 07:22:20 +0000138 Constant *F;
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000139 public:
140 CycleCounter(Module& m, uint64_t resetmask);
141 virtual ~CycleCounter();
142 virtual void PrepFunction(Function* F);
143 virtual void ProcessChoicePoint(BasicBlock* bb);
144 };
145
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000146 /// ProfilerRS - Insert the random sampling framework
Reid Spencer9133fe22007-02-05 23:32:05 +0000147 struct VISIBILITY_HIDDEN ProfilerRS : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000148 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000149 ProfilerRS() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000150
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000151 std::map<Value*, Value*> TransCache;
152 std::set<BasicBlock*> ChoicePoints;
153 Chooser* c;
154
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000155 //Translate and duplicate values for the new profile free version of stuff
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000156 Value* Translate(Value* v);
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000157 //Duplicate an entire function (with out profiling)
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000158 void Duplicate(Function& F, RSProfilers& LI);
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000159 //Called once for each backedge, handle the insertion of choice points and
160 //the interconection of the two versions of the code
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000161 void ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F);
162 bool runOnFunction(Function& F);
163 bool doInitialization(Module &M);
164 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
165 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000166}
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000167
Dan Gohman844731a2008-05-13 00:00:25 +0000168static RegisterPass<ProfilerRS>
169X("insert-rs-profiling-framework",
170 "Insert random sampling instrumentation framework");
171
Devang Patel19974732007-05-03 01:11:54 +0000172char RSProfilers::ID = 0;
173char NullProfilerRS::ID = 0;
174char ProfilerRS::ID = 0;
Lauro Ramos Venancioc7182882007-05-02 20:37:47 +0000175
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000176//Local utilities
177static void ReplacePhiPred(BasicBlock* btarget,
178 BasicBlock* bold, BasicBlock* bnew);
179
180static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc);
181
182template<class T>
183static void recBackEdge(BasicBlock* bb, T& BackEdges,
184 std::map<BasicBlock*, int>& color,
185 std::map<BasicBlock*, int>& depth,
186 std::map<BasicBlock*, int>& finish,
187 int& time);
188
189//find the back edges and where they go to
190template<class T>
191static void getBackEdges(Function& F, T& BackEdges);
192
193
194///////////////////////////////////////
195// Methods of choosing when to profile
196///////////////////////////////////////
197
Dan Gohman6de29f82009-06-15 22:12:54 +0000198GlobalRandomCounter::GlobalRandomCounter(Module& M, const IntegerType* t,
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000199 uint64_t resetval) : T(t) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000200 ConstantInt* Init = ConstantInt::get(T, resetval);
Reid Spencerb83eb642006-10-20 07:07:24 +0000201 ResetValue = Init;
Owen Andersone9b11b42009-07-08 19:03:57 +0000202 Counter = new GlobalVariable(M, T, false, GlobalValue::InternalLinkage,
203 Init, "RandomSteeringCounter");
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000204}
205
206GlobalRandomCounter::~GlobalRandomCounter() {}
207
208void GlobalRandomCounter::PrepFunction(Function* F) {}
209
210void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) {
211 BranchInst* t = cast<BranchInst>(bb->getTerminator());
212
213 //decrement counter
214 LoadInst* l = new LoadInst(Counter, "counter", t);
215
Owen Anderson333c4002009-07-09 23:48:35 +0000216 ICmpInst* s = new ICmpInst(t, ICmpInst::ICMP_EQ, l,
Owen Andersoneed707b2009-07-24 23:12:02 +0000217 ConstantInt::get(T, 0),
Owen Anderson333c4002009-07-09 23:48:35 +0000218 "countercc");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000219
Owen Andersoneed707b2009-07-24 23:12:02 +0000220 Value* nv = BinaryOperator::CreateSub(l, ConstantInt::get(T, 1),
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000221 "counternew", t);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000222 new StoreInst(nv, Counter, t);
223 t->setCondition(s);
224
225 //reset counter
226 BasicBlock* oldnext = t->getSuccessor(0);
Gabor Greif051a9502008-04-06 20:25:17 +0000227 BasicBlock* resetblock = BasicBlock::Create("reset", oldnext->getParent(),
228 oldnext);
229 TerminatorInst* t2 = BranchInst::Create(oldnext, resetblock);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000230 t->setSuccessor(0, resetblock);
231 new StoreInst(ResetValue, Counter, t2);
232 ReplacePhiPred(oldnext, bb, resetblock);
233}
234
Dan Gohman6de29f82009-06-15 22:12:54 +0000235GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const IntegerType* t,
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000236 uint64_t resetval)
237 : AI(0), T(t) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000238 ConstantInt* Init = ConstantInt::get(T, resetval);
Reid Spencerb83eb642006-10-20 07:07:24 +0000239 ResetValue = Init;
Owen Andersone9b11b42009-07-08 19:03:57 +0000240 Counter = new GlobalVariable(M, T, false, GlobalValue::InternalLinkage,
241 Init, "RandomSteeringCounter");
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000242}
243
244GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {}
245
246void GlobalRandomCounterOpt::PrepFunction(Function* F) {
247 //make a local temporary to cache the global
248 BasicBlock& bb = F->getEntryBlock();
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000249 BasicBlock::iterator InsertPt = bb.begin();
Owen Anderson50dead02009-07-15 23:53:25 +0000250 AI = new AllocaInst(T, 0, "localcounter", InsertPt);
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000251 LoadInst* l = new LoadInst(Counter, "counterload", InsertPt);
252 new StoreInst(l, AI, InsertPt);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000253
Andrew Lenharth8dc2d502005-11-28 18:10:59 +0000254 //modify all functions and return values to restore the local variable to/from
255 //the global variable
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000256 for(Function::iterator fib = F->begin(), fie = F->end();
257 fib != fie; ++fib)
258 for(BasicBlock::iterator bib = fib->begin(), bie = fib->end();
259 bib != bie; ++bib)
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000260 if (isa<CallInst>(bib)) {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000261 LoadInst* l = new LoadInst(AI, "counter", bib);
262 new StoreInst(l, Counter, bib);
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000263 l = new LoadInst(Counter, "counter", ++bib);
264 new StoreInst(l, AI, bib--);
265 } else if (isa<InvokeInst>(bib)) {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000266 LoadInst* l = new LoadInst(AI, "counter", bib);
267 new StoreInst(l, Counter, bib);
268
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000269 BasicBlock* bb = cast<InvokeInst>(bib)->getNormalDest();
Dan Gohman02dea8b2008-05-23 21:05:58 +0000270 BasicBlock::iterator i = bb->getFirstNonPHI();
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000271 l = new LoadInst(Counter, "counter", i);
272
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000273 bb = cast<InvokeInst>(bib)->getUnwindDest();
Dan Gohman02dea8b2008-05-23 21:05:58 +0000274 i = bb->getFirstNonPHI();
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000275 l = new LoadInst(Counter, "counter", i);
Chris Lattnera0e1b0e2007-04-17 17:51:03 +0000276 new StoreInst(l, AI, i);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000277 } else if (isa<UnwindInst>(&*bib) || isa<ReturnInst>(&*bib)) {
278 LoadInst* l = new LoadInst(AI, "counter", bib);
279 new StoreInst(l, Counter, bib);
280 }
281}
282
283void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) {
284 BranchInst* t = cast<BranchInst>(bb->getTerminator());
285
286 //decrement counter
287 LoadInst* l = new LoadInst(AI, "counter", t);
288
Owen Anderson333c4002009-07-09 23:48:35 +0000289 ICmpInst* s = new ICmpInst(t, ICmpInst::ICMP_EQ, l,
Owen Andersoneed707b2009-07-24 23:12:02 +0000290 ConstantInt::get(T, 0),
Owen Anderson333c4002009-07-09 23:48:35 +0000291 "countercc");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000292
Owen Andersoneed707b2009-07-24 23:12:02 +0000293 Value* nv = BinaryOperator::CreateSub(l, ConstantInt::get(T, 1),
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000294 "counternew", t);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000295 new StoreInst(nv, AI, t);
296 t->setCondition(s);
297
298 //reset counter
299 BasicBlock* oldnext = t->getSuccessor(0);
Gabor Greif051a9502008-04-06 20:25:17 +0000300 BasicBlock* resetblock = BasicBlock::Create("reset", oldnext->getParent(),
301 oldnext);
302 TerminatorInst* t2 = BranchInst::Create(oldnext, resetblock);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000303 t->setSuccessor(0, resetblock);
304 new StoreInst(ResetValue, AI, t2);
305 ReplacePhiPred(oldnext, bb, resetblock);
306}
307
308
309CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) {
Duncan Sandse2c43042008-04-07 13:45:04 +0000310 F = Intrinsic::getDeclaration(&m, Intrinsic::readcyclecounter);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000311}
312
313CycleCounter::~CycleCounter() {}
314
315void CycleCounter::PrepFunction(Function* F) {}
316
317void CycleCounter::ProcessChoicePoint(BasicBlock* bb) {
318 BranchInst* t = cast<BranchInst>(bb->getTerminator());
319
Gabor Greif051a9502008-04-06 20:25:17 +0000320 CallInst* c = CallInst::Create(F, "rdcc", t);
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000321 BinaryOperator* b =
Owen Andersoneed707b2009-07-24 23:12:02 +0000322 BinaryOperator::CreateAnd(c, ConstantInt::get(Type::Int64Ty, rm),
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000323 "mrdcc", t);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000324
Owen Anderson333c4002009-07-09 23:48:35 +0000325 ICmpInst *s = new ICmpInst(t, ICmpInst::ICMP_EQ, b,
Owen Andersoneed707b2009-07-24 23:12:02 +0000326 ConstantInt::get(Type::Int64Ty, 0),
Owen Anderson333c4002009-07-09 23:48:35 +0000327 "mrdccc");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000328
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000329 t->setCondition(s);
330}
331
332///////////////////////////////////////
333// Profiling:
334///////////////////////////////////////
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000335bool RSProfilers_std::isProfiling(Value* v) {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000336 if (profcode.find(v) != profcode.end())
337 return true;
338 //else
339 RSProfilers& LI = getAnalysis<RSProfilers>();
340 return LI.isProfiling(v);
341}
342
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000343void RSProfilers_std::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000344 GlobalValue *CounterArray) {
345 // Insert the increment after any alloca or PHI instructions...
Dan Gohman02dea8b2008-05-23 21:05:58 +0000346 BasicBlock::iterator InsertPos = BB->getFirstNonPHI();
347 while (isa<AllocaInst>(InsertPos))
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000348 ++InsertPos;
349
350 // Create the getelementptr constant expression
351 std::vector<Constant*> Indices(2);
Owen Andersone922c022009-07-22 00:24:57 +0000352 Indices[0] = BB->getContext().getNullValue(Type::Int32Ty);
Owen Andersoneed707b2009-07-24 23:12:02 +0000353 Indices[1] = ConstantInt::get(Type::Int32Ty, CounterNum);
Owen Andersone922c022009-07-22 00:24:57 +0000354 Constant *ElementPtr =
355 BB->getContext().getConstantExprGetElementPtr(CounterArray,
Chris Lattnerec1f7522007-02-19 07:34:47 +0000356 &Indices[0], 2);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000357
358 // Load, increment and store the value back.
359 Value *OldVal = new LoadInst(ElementPtr, "OldCounter", InsertPos);
360 profcode.insert(OldVal);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000361 Value *NewVal = BinaryOperator::CreateAdd(OldVal,
Owen Andersoneed707b2009-07-24 23:12:02 +0000362 ConstantInt::get(Type::Int32Ty, 1),
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000363 "NewCounter", InsertPos);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000364 profcode.insert(NewVal);
365 profcode.insert(new StoreInst(NewVal, ElementPtr, InsertPos));
366}
367
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000368void RSProfilers_std::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000369 //grab any outstanding profiler, or get the null one
370 AU.addRequired<RSProfilers>();
371}
372
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000373///////////////////////////////////////
374// RS Framework
375///////////////////////////////////////
376
377Value* ProfilerRS::Translate(Value* v) {
378 if(TransCache[v])
379 return TransCache[v];
380
381 if (BasicBlock* bb = dyn_cast<BasicBlock>(v)) {
382 if (bb == &bb->getParent()->getEntryBlock())
383 TransCache[bb] = bb; //don't translate entry block
384 else
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000385 TransCache[bb] = BasicBlock::Create("dup_" + bb->getName(),
386 bb->getParent(), NULL);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000387 return TransCache[bb];
388 } else if (Instruction* i = dyn_cast<Instruction>(v)) {
389 //we have already translated this
390 //do not translate entry block allocas
391 if(&i->getParent()->getParent()->getEntryBlock() == i->getParent()) {
392 TransCache[i] = i;
393 return i;
394 } else {
395 //translate this
Owen Andersone922c022009-07-22 00:24:57 +0000396 Instruction* i2 = i->clone(v->getContext());
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000397 if (i->hasName())
398 i2->setName("dup_" + i->getName());
399 TransCache[i] = i2;
400 //NumNewInst++;
401 for (unsigned x = 0; x < i2->getNumOperands(); ++x)
402 i2->setOperand(x, Translate(i2->getOperand(x)));
403 return i2;
404 }
405 } else if (isa<Function>(v) || isa<Constant>(v) || isa<Argument>(v)) {
406 TransCache[v] = v;
407 return v;
408 }
Torok Edwinc23197a2009-07-14 16:55:14 +0000409 llvm_unreachable("Value not handled");
Jeff Cohen3523f6e2005-11-28 06:45:57 +0000410 return 0;
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000411}
412
413void ProfilerRS::Duplicate(Function& F, RSProfilers& LI)
414{
415 //perform a breadth first search, building up a duplicate of the code
416 std::queue<BasicBlock*> worklist;
417 std::set<BasicBlock*> seen;
418
419 //This loop ensures proper BB order, to help performance
420 for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib)
421 worklist.push(fib);
422 while (!worklist.empty()) {
423 Translate(worklist.front());
424 worklist.pop();
425 }
426
427 //remember than reg2mem created a new entry block we don't want to duplicate
428 worklist.push(F.getEntryBlock().getTerminator()->getSuccessor(0));
429 seen.insert(&F.getEntryBlock());
430
431 while (!worklist.empty()) {
432 BasicBlock* bb = worklist.front();
433 worklist.pop();
434 if(seen.find(bb) == seen.end()) {
435 BasicBlock* bbtarget = cast<BasicBlock>(Translate(bb));
436 BasicBlock::InstListType& instlist = bbtarget->getInstList();
437 for (BasicBlock::iterator iib = bb->begin(), iie = bb->end();
438 iib != iie; ++iib) {
439 //NumOldInst++;
440 if (!LI.isProfiling(&*iib)) {
441 Instruction* i = cast<Instruction>(Translate(iib));
442 instlist.insert(bbtarget->end(), i);
443 }
444 }
445 //updated search state;
446 seen.insert(bb);
447 TerminatorInst* ti = bb->getTerminator();
448 for (unsigned x = 0; x < ti->getNumSuccessors(); ++x) {
449 BasicBlock* bbs = ti->getSuccessor(x);
450 if (seen.find(bbs) == seen.end()) {
451 worklist.push(bbs);
452 }
453 }
454 }
455 }
456}
457
458void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) {
459 //given a backedge from B -> A, and translations A' and B',
460 //a: insert C and C'
461 //b: add branches in C to A and A' and in C' to A and A'
462 //c: mod terminators@B, replace A with C
463 //d: mod terminators@B', replace A' with C'
464 //e: mod phis@A for pred B to be pred C
465 // if multiple entries, simplify to one
466 //f: mod phis@A' for pred B' to be pred C'
467 // if multiple entries, simplify to one
468 //g: for all phis@A with pred C using x
469 // add in edge from C' using x'
470 // add in edge from C using x in A'
471
472 //a:
Chris Lattnere24c92a2007-04-17 17:54:12 +0000473 Function::iterator BBN = src; ++BBN;
Gabor Greif051a9502008-04-06 20:25:17 +0000474 BasicBlock* bbC = BasicBlock::Create("choice", &F, BBN);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000475 //ChoicePoints.insert(bbC);
Chris Lattnere24c92a2007-04-17 17:54:12 +0000476 BBN = cast<BasicBlock>(Translate(src));
Gabor Greif051a9502008-04-06 20:25:17 +0000477 BasicBlock* bbCp = BasicBlock::Create("choice", &F, ++BBN);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000478 ChoicePoints.insert(bbCp);
479
480 //b:
Gabor Greif051a9502008-04-06 20:25:17 +0000481 BranchInst::Create(cast<BasicBlock>(Translate(dst)), bbC);
482 BranchInst::Create(dst, cast<BasicBlock>(Translate(dst)),
Owen Andersoneed707b2009-07-24 23:12:02 +0000483 ConstantInt::get(Type::Int1Ty, true), bbCp);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000484 //c:
485 {
486 TerminatorInst* iB = src->getTerminator();
487 for (unsigned x = 0; x < iB->getNumSuccessors(); ++x)
488 if (iB->getSuccessor(x) == dst)
489 iB->setSuccessor(x, bbC);
490 }
491 //d:
492 {
493 TerminatorInst* iBp = cast<TerminatorInst>(Translate(src->getTerminator()));
494 for (unsigned x = 0; x < iBp->getNumSuccessors(); ++x)
495 if (iBp->getSuccessor(x) == cast<BasicBlock>(Translate(dst)))
496 iBp->setSuccessor(x, bbCp);
497 }
498 //e:
499 ReplacePhiPred(dst, src, bbC);
500 //src could be a switch, in which case we are replacing several edges with one
501 //thus collapse those edges int the Phi
502 CollapsePhi(dst, bbC);
503 //f:
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000504 ReplacePhiPred(cast<BasicBlock>(Translate(dst)),
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000505 cast<BasicBlock>(Translate(src)),bbCp);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000506 CollapsePhi(cast<BasicBlock>(Translate(dst)), bbCp);
507 //g:
508 for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie;
509 ++ib)
510 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
511 for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
512 if(bbC == phi->getIncomingBlock(x)) {
513 phi->addIncoming(Translate(phi->getIncomingValue(x)), bbCp);
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000514 cast<PHINode>(Translate(phi))->addIncoming(phi->getIncomingValue(x),
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000515 bbC);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000516 }
517 phi->removeIncomingValue(bbC);
518 }
519}
520
521bool ProfilerRS::runOnFunction(Function& F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000522 if (!F.isDeclaration()) {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000523 std::set<std::pair<BasicBlock*, BasicBlock*> > BackEdges;
524 RSProfilers& LI = getAnalysis<RSProfilers>();
525
526 getBackEdges(F, BackEdges);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000527 Duplicate(F, LI);
528 //assume that stuff worked. now connect the duplicated basic blocks
529 //with the originals in such a way as to preserve ssa. yuk!
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000530 for (std::set<std::pair<BasicBlock*, BasicBlock*> >::iterator
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000531 ib = BackEdges.begin(), ie = BackEdges.end(); ib != ie; ++ib)
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000532 ProcessBackEdge(ib->first, ib->second, F);
533
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000534 //oh, and add the edge from the reg2mem created entry node to the
535 //duplicated second node
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000536 TerminatorInst* T = F.getEntryBlock().getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +0000537 ReplaceInstWithInst(T, BranchInst::Create(T->getSuccessor(0),
538 cast<BasicBlock>(
539 Translate(T->getSuccessor(0))),
Owen Andersoneed707b2009-07-24 23:12:02 +0000540 ConstantInt::get(Type::Int1Ty, true)));
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000541
542 //do whatever is needed now that the function is duplicated
543 c->PrepFunction(&F);
544
545 //add entry node to choice points
546 ChoicePoints.insert(&F.getEntryBlock());
547
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000548 for (std::set<BasicBlock*>::iterator
Anton Korobeynikovbed29462007-04-16 18:10:23 +0000549 ii = ChoicePoints.begin(), ie = ChoicePoints.end(); ii != ie; ++ii)
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000550 c->ProcessChoicePoint(*ii);
551
552 ChoicePoints.clear();
553 TransCache.clear();
554
555 return true;
556 }
557 return false;
558}
559
560bool ProfilerRS::doInitialization(Module &M) {
561 switch (RandomMethod) {
562 case GBV:
Reid Spencerc5b206b2006-12-31 05:48:39 +0000563 c = new GlobalRandomCounter(M, Type::Int32Ty, (1 << 14) - 1);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000564 break;
565 case GBVO:
Reid Spencerc5b206b2006-12-31 05:48:39 +0000566 c = new GlobalRandomCounterOpt(M, Type::Int32Ty, (1 << 14) - 1);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000567 break;
568 case HOSTCC:
569 c = new CycleCounter(M, (1 << 14) - 1);
570 break;
571 };
572 return true;
573}
574
575void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const {
576 AU.addRequired<RSProfilers>();
577 AU.addRequiredID(DemoteRegisterToMemoryID);
578}
579
580///////////////////////////////////////
581// Utilities:
582///////////////////////////////////////
583static void ReplacePhiPred(BasicBlock* btarget,
584 BasicBlock* bold, BasicBlock* bnew) {
585 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
586 ib != ie; ++ib)
587 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
588 for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
589 if(bold == phi->getIncomingBlock(x))
590 phi->setIncomingBlock(x, bnew);
591 }
592}
593
594static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) {
595 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
596 ib != ie; ++ib)
597 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000598 std::map<BasicBlock*, Value*> counter;
599 for(unsigned i = 0; i < phi->getNumIncomingValues(); ) {
600 if (counter[phi->getIncomingBlock(i)]) {
Andrew Lenharthbb227c12005-11-28 18:00:38 +0000601 assert(phi->getIncomingValue(i) == counter[phi->getIncomingBlock(i)]);
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000602 phi->removeIncomingValue(i, false);
603 } else {
604 counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i);
605 ++i;
606 }
607 }
608 }
609}
610
611template<class T>
612static void recBackEdge(BasicBlock* bb, T& BackEdges,
613 std::map<BasicBlock*, int>& color,
614 std::map<BasicBlock*, int>& depth,
615 std::map<BasicBlock*, int>& finish,
616 int& time)
617{
618 color[bb] = 1;
619 ++time;
620 depth[bb] = time;
621 TerminatorInst* t= bb->getTerminator();
622 for(unsigned i = 0; i < t->getNumSuccessors(); ++i) {
623 BasicBlock* bbnew = t->getSuccessor(i);
624 if (color[bbnew] == 0)
625 recBackEdge(bbnew, BackEdges, color, depth, finish, time);
626 else if (color[bbnew] == 1) {
627 BackEdges.insert(std::make_pair(bb, bbnew));
628 //NumBackEdges++;
629 }
630 }
631 color[bb] = 2;
632 ++time;
633 finish[bb] = time;
634}
635
636
637
638//find the back edges and where they go to
639template<class T>
640static void getBackEdges(Function& F, T& BackEdges) {
641 std::map<BasicBlock*, int> color;
642 std::map<BasicBlock*, int> depth;
643 std::map<BasicBlock*, int> finish;
644 int time = 0;
645 recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time);
Bill Wendling62c804a2006-11-26 09:17:06 +0000646 DOUT << F.getName() << " " << BackEdges.size() << "\n";
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000647}
648
649
650//Creation functions
Andrew Lenharth701f5ac2005-11-28 00:58:09 +0000651ModulePass* llvm::createNullProfilerRSPass() {
652 return new NullProfilerRS();
653}
654
655FunctionPass* llvm::createRSProfilingPass() {
656 return new ProfilerRS();
657}