finegrainify namespacification
[oota-llvm.git] / lib / Transforms / Instrumentation / BlockProfiling.cpp
1 //===- BlockProfiling.cpp - Insert counters for block profiling -----------===//
2 // 
3 //                      The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass instruments the specified program with counters for basic block or
11 // function profiling.  This is the most basic form of profiling, which can tell
12 // which blocks are hot, but cannot reliably detect hot paths through the CFG.
13 // Block profiling counts the number of times each basic block executes, and
14 // function profiling counts the number of times each function is called.
15 //
16 // Note that this implementation is very naive.  Control equivalent regions of
17 // the CFG should not require duplicate counters, but we do put duplicate
18 // counters in.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/Pass.h"
27 using namespace llvm;
28
29 static void insertInitializationCall(Function *MainFn, const char *FnName,
30                                      GlobalValue *Array) {
31   const Type *ArgVTy = PointerType::get(PointerType::get(Type::SByteTy));
32   const Type *UIntPtr = PointerType::get(Type::UIntTy);
33   Module &M = *MainFn->getParent();
34   Function *InitFn = M.getOrInsertFunction(FnName, Type::IntTy, Type::IntTy,
35                                            ArgVTy, UIntPtr, Type::UIntTy, 0);
36
37   // This could force argc and argv into programs that wouldn't otherwise have
38   // them, but instead we just pass null values in.
39   std::vector<Value*> Args(4);
40   Args[0] = Constant::getNullValue(Type::IntTy);
41   Args[1] = Constant::getNullValue(ArgVTy);
42
43   // Skip over any allocas in the entry block.
44   BasicBlock *Entry = MainFn->begin();
45   BasicBlock::iterator InsertPos = Entry->begin();
46   while (isa<AllocaInst>(InsertPos)) ++InsertPos;
47
48   ConstantPointerRef *ArrayCPR = ConstantPointerRef::get(Array);
49   std::vector<Constant*> GEPIndices(2, Constant::getNullValue(Type::LongTy));
50   Args[2] = ConstantExpr::getGetElementPtr(ArrayCPR, GEPIndices);
51   
52   unsigned NumElements =
53     cast<ArrayType>(Array->getType()->getElementType())->getNumElements();
54   Args[3] = ConstantUInt::get(Type::UIntTy, NumElements);
55   
56   Instruction *InitCall = new CallInst(InitFn, Args, "newargc", InsertPos);
57
58   // If argc or argv are not available in main, just pass null values in.
59   Function::aiterator AI;
60   switch (MainFn->asize()) {
61   default:
62   case 2:
63     AI = MainFn->abegin(); ++AI;
64     if (AI->getType() != ArgVTy) {
65       InitCall->setOperand(2, new CastInst(AI, ArgVTy, "argv.cast", InitCall));
66     } else {
67       InitCall->setOperand(2, AI);
68     }
69
70   case 1:
71     AI = MainFn->abegin();
72     // If the program looked at argc, have it look at the return value of the
73     // init call instead.
74     if (AI->getType() != Type::IntTy) {
75       if (!AI->use_empty())
76         AI->replaceAllUsesWith(new CastInst(InitCall, AI->getType(), "",
77                                             InsertPos));
78       InitCall->setOperand(1, new CastInst(AI, Type::IntTy, "argc.cast",
79                                            InitCall));
80     } else {
81       AI->replaceAllUsesWith(InitCall);
82       InitCall->setOperand(1, AI);
83     }
84     
85   case 0: break;
86   }
87 }
88
89 static void IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
90                                     ConstantPointerRef *CounterArray) {
91   // Insert the increment after any alloca or PHI instructions...
92   BasicBlock::iterator InsertPos = BB->begin();
93   while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
94     ++InsertPos;
95
96   // Create the getelementptr constant expression
97   std::vector<Constant*> Indices(2);
98   Indices[0] = Constant::getNullValue(Type::LongTy);
99   Indices[1] = ConstantSInt::get(Type::LongTy, CounterNum);
100   Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray, Indices);
101
102   // Load, increment and store the value back.
103   Value *OldVal = new LoadInst(ElementPtr, "OldFuncCounter", InsertPos);
104   Value *NewVal = BinaryOperator::create(Instruction::Add, OldVal,
105                                          ConstantInt::get(Type::UIntTy, 1),
106                                          "NewFuncCounter", InsertPos);
107   new StoreInst(NewVal, ElementPtr, InsertPos);
108 }
109
110
111 namespace {
112   class FunctionProfiler : public Pass {
113     bool run(Module &M);
114   };
115
116   RegisterOpt<FunctionProfiler> X("insert-function-profiling",
117                                "Insert instrumentation for function profiling");
118 }
119
120 bool FunctionProfiler::run(Module &M) {
121   Function *Main = M.getMainFunction();
122   if (Main == 0) {
123     std::cerr << "WARNING: cannot insert function profiling into a module"
124               << " with no main function!\n";
125     return false;  // No main, no instrumentation!
126   }
127
128   unsigned NumFunctions = 0;
129   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
130     if (!I->isExternal())
131       ++NumFunctions;
132
133   const Type *ATy = ArrayType::get(Type::UIntTy, NumFunctions);
134   GlobalVariable *Counters =
135     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
136                        Constant::getNullValue(ATy), "FuncProfCounters", &M);
137
138   ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
139
140   // Instrument all of the functions...
141   unsigned i = 0;
142   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
143     if (!I->isExternal())
144       // Insert counter at the start of the function
145       IncrementCounterInBlock(I->begin(), i++, CounterCPR);
146
147   // Add the initialization call to main.
148   insertInitializationCall(Main, "llvm_start_func_profiling", Counters);
149   return true;
150 }
151
152
153 namespace {
154   class BlockProfiler : public Pass {
155     bool run(Module &M);
156   };
157
158   RegisterOpt<BlockProfiler> Y("insert-block-profiling",
159                                "Insert instrumentation for block profiling");
160 }
161
162 bool BlockProfiler::run(Module &M) {
163   Function *Main = M.getMainFunction();
164   if (Main == 0) {
165     std::cerr << "WARNING: cannot insert block profiling into a module"
166               << " with no main function!\n";
167     return false;  // No main, no instrumentation!
168   }
169
170   unsigned NumBlocks = 0;
171   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
172     NumBlocks += I->size();
173
174   const Type *ATy = ArrayType::get(Type::UIntTy, NumBlocks);
175   GlobalVariable *Counters =
176     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
177                        Constant::getNullValue(ATy), "BlockProfCounters", &M);
178
179   ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
180
181   // Instrument all of the blocks...
182   unsigned i = 0;
183   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
184     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
185       // Insert counter at the start of the block
186       IncrementCounterInBlock(BB, i++, CounterCPR);
187
188   // Add the initialization call to main.
189   insertInitializationCall(Main, "llvm_start_block_profiling", Counters);
190   return true;
191 }
192