Put all LLVM code into the llvm namespace, as per bug 109.
[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
28 namespace llvm {
29
30 static void insertInitializationCall(Function *MainFn, const char *FnName,
31                                      GlobalValue *Array) {
32   const Type *ArgVTy = PointerType::get(PointerType::get(Type::SByteTy));
33   const Type *UIntPtr = PointerType::get(Type::UIntTy);
34   Module &M = *MainFn->getParent();
35   Function *InitFn = M.getOrInsertFunction(FnName, Type::VoidTy, Type::IntTy,
36                                            ArgVTy, UIntPtr, Type::UIntTy, 0);
37
38   // This could force argc and argv into programs that wouldn't otherwise have
39   // them, but instead we just pass null values in.
40   std::vector<Value*> Args(4);
41   Args[0] = Constant::getNullValue(Type::IntTy);
42   Args[1] = Constant::getNullValue(ArgVTy);
43
44   // Skip over any allocas in the entry block.
45   BasicBlock *Entry = MainFn->begin();
46   BasicBlock::iterator InsertPos = Entry->begin();
47   while (isa<AllocaInst>(InsertPos)) ++InsertPos;
48
49   Function::aiterator AI;
50   switch (MainFn->asize()) {
51   default:
52   case 2:
53     AI = MainFn->abegin(); ++AI;
54     if (AI->getType() != ArgVTy) {
55       Args[1] = new CastInst(AI, ArgVTy, "argv.cast", InsertPos);
56     } else {
57       Args[1] = AI;
58     }
59
60   case 1:
61     AI = MainFn->abegin();
62     if (AI->getType() != Type::IntTy) {
63       Args[0] = new CastInst(AI, Type::IntTy, "argc.cast", InsertPos);
64     } else {
65       Args[0] = AI;
66     }
67     
68   case 0:
69     break;
70   }
71
72   ConstantPointerRef *ArrayCPR = ConstantPointerRef::get(Array);
73   std::vector<Constant*> GEPIndices(2, Constant::getNullValue(Type::LongTy));
74   Args[2] = ConstantExpr::getGetElementPtr(ArrayCPR, GEPIndices);
75   
76   unsigned NumElements =
77     cast<ArrayType>(Array->getType()->getElementType())->getNumElements();
78   Args[3] = ConstantUInt::get(Type::UIntTy, NumElements);
79   
80   new CallInst(InitFn, Args, "", InsertPos);
81 }
82
83 static void IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
84                                     ConstantPointerRef *CounterArray) {
85   // Insert the increment after any alloca or PHI instructions...
86   BasicBlock::iterator InsertPos = BB->begin();
87   while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
88     ++InsertPos;
89
90   // Create the getelementptr constant expression
91   std::vector<Constant*> Indices(2);
92   Indices[0] = Constant::getNullValue(Type::LongTy);
93   Indices[1] = ConstantSInt::get(Type::LongTy, CounterNum);
94   Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray, Indices);
95
96   // Load, increment and store the value back.
97   Value *OldVal = new LoadInst(ElementPtr, "OldFuncCounter", InsertPos);
98   Value *NewVal = BinaryOperator::create(Instruction::Add, OldVal,
99                                          ConstantInt::get(Type::UIntTy, 1),
100                                          "NewFuncCounter", InsertPos);
101   new StoreInst(NewVal, ElementPtr, InsertPos);
102 }
103
104
105 namespace {
106   class FunctionProfiler : public Pass {
107     bool run(Module &M);
108   };
109
110   RegisterOpt<FunctionProfiler> X("insert-function-profiling",
111                                "Insert instrumentation for function profiling");
112 }
113
114 bool FunctionProfiler::run(Module &M) {
115   Function *Main = M.getMainFunction();
116   if (Main == 0) {
117     std::cerr << "WARNING: cannot insert function profiling into a module"
118               << " with no main function!\n";
119     return false;  // No main, no instrumentation!
120   }
121
122   unsigned NumFunctions = 0;
123   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
124     if (!I->isExternal())
125       ++NumFunctions;
126
127   const Type *ATy = ArrayType::get(Type::UIntTy, NumFunctions);
128   GlobalVariable *Counters =
129     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
130                        Constant::getNullValue(ATy), "FuncProfCounters", &M);
131
132   ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
133
134   // Instrument all of the functions...
135   unsigned i = 0;
136   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
137     if (!I->isExternal())
138       // Insert counter at the start of the function
139       IncrementCounterInBlock(I->begin(), i++, CounterCPR);
140
141   // Add the initialization call to main.
142   insertInitializationCall(Main, "llvm_start_func_profiling", Counters);
143   return true;
144 }
145
146
147 namespace {
148   class BlockProfiler : public Pass {
149     bool run(Module &M);
150   };
151
152   RegisterOpt<BlockProfiler> Y("insert-block-profiling",
153                                "Insert instrumentation for block profiling");
154 }
155
156 bool BlockProfiler::run(Module &M) {
157   Function *Main = M.getMainFunction();
158   if (Main == 0) {
159     std::cerr << "WARNING: cannot insert block profiling into a module"
160               << " with no main function!\n";
161     return false;  // No main, no instrumentation!
162   }
163
164   unsigned NumBlocks = 0;
165   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
166     NumBlocks += I->size();
167
168   const Type *ATy = ArrayType::get(Type::UIntTy, NumBlocks);
169   GlobalVariable *Counters =
170     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
171                        Constant::getNullValue(ATy), "BlockProfCounters", &M);
172
173   ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
174
175   // Instrument all of the blocks...
176   unsigned i = 0;
177   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) 
178     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
179       // Insert counter at the start of the block
180       IncrementCounterInBlock(BB, i++, CounterCPR);
181
182   // Add the initialization call to main.
183   insertInitializationCall(Main, "llvm_start_block_profiling", Counters);
184   return true;
185 }
186
187 } // End llvm namespace