1 //===- BlockProfiling.cpp - Insert counters for block profiling -----------===//
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 // 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.
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
20 //===----------------------------------------------------------------------===//
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"
29 static void insertInitializationCall(Function *MainFn, const char *FnName,
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);
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);
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;
48 ConstantPointerRef *ArrayCPR = ConstantPointerRef::get(Array);
49 std::vector<Constant*> GEPIndices(2, Constant::getNullValue(Type::LongTy));
50 Args[2] = ConstantExpr::getGetElementPtr(ArrayCPR, GEPIndices);
52 unsigned NumElements =
53 cast<ArrayType>(Array->getType()->getElementType())->getNumElements();
54 Args[3] = ConstantUInt::get(Type::UIntTy, NumElements);
56 Instruction *InitCall = new CallInst(InitFn, Args, "newargc", InsertPos);
58 // If argc or argv are not available in main, just pass null values in.
59 Function::aiterator AI;
60 switch (MainFn->asize()) {
63 AI = MainFn->abegin(); ++AI;
64 if (AI->getType() != ArgVTy) {
65 InitCall->setOperand(2, new CastInst(AI, ArgVTy, "argv.cast", InitCall));
67 InitCall->setOperand(2, AI);
71 AI = MainFn->abegin();
72 // If the program looked at argc, have it look at the return value of the
74 if (AI->getType() != Type::IntTy) {
76 AI->replaceAllUsesWith(new CastInst(InitCall, AI->getType(), "",
78 InitCall->setOperand(1, new CastInst(AI, Type::IntTy, "argc.cast",
81 AI->replaceAllUsesWith(InitCall);
82 InitCall->setOperand(1, AI);
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))
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);
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);
112 class FunctionProfiler : public Pass {
116 RegisterOpt<FunctionProfiler> X("insert-function-profiling",
117 "Insert instrumentation for function profiling");
120 bool FunctionProfiler::run(Module &M) {
121 Function *Main = M.getMainFunction();
123 std::cerr << "WARNING: cannot insert function profiling into a module"
124 << " with no main function!\n";
125 return false; // No main, no instrumentation!
128 unsigned NumFunctions = 0;
129 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
130 if (!I->isExternal())
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);
138 ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
140 // Instrument all of the functions...
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);
147 // Add the initialization call to main.
148 insertInitializationCall(Main, "llvm_start_func_profiling", Counters);
154 class BlockProfiler : public Pass {
158 RegisterOpt<BlockProfiler> Y("insert-block-profiling",
159 "Insert instrumentation for block profiling");
162 bool BlockProfiler::run(Module &M) {
163 Function *Main = M.getMainFunction();
165 std::cerr << "WARNING: cannot insert block profiling into a module"
166 << " with no main function!\n";
167 return false; // No main, no instrumentation!
170 unsigned NumBlocks = 0;
171 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
172 NumBlocks += I->size();
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);
179 ConstantPointerRef *CounterCPR = ConstantPointerRef::get(Counters);
181 // Instrument all of the blocks...
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);
188 // Add the initialization call to main.
189 insertInitializationCall(Main, "llvm_start_block_profiling", Counters);