#include "ProfilingUtils.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Instrumentation.h"
#include <set>
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN EdgeProfiler : public ModulePass {
bool runOnModule(Module &M);
public:
static char ID; EdgeProfiler() : ModulePass(&ID) {}
};
}
char EdgeProfiler::ID = 0;
static RegisterPass<EdgeProfiler>
X("insert-edge-profiling", "Insert instrumentation for edge profiling");
ModulePass *llvm::createEdgeProfilerPass() { return new EdgeProfiler(); }
bool EdgeProfiler::runOnModule(Module &M) {
Function *Main = M.getFunction("main");
if (Main == 0) {
cerr << "WARNING: cannot insert edge profiling into a module"
<< " with no main function!\n";
return false; }
std::set<BasicBlock*> BlocksToInstrument;
unsigned NumEdges = 0;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
BlocksToInstrument.insert(BB);
NumEdges += BB->getTerminator()->getNumSuccessors();
}
const Type *ATy = ArrayType::get(Type::Int32Ty, NumEdges);
GlobalVariable *Counters =
new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
Constant::getNullValue(ATy), "EdgeProfCounters", &M);
unsigned i = 0;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
if (BlocksToInstrument.count(BB)) { TerminatorInst *TI = BB->getTerminator();
for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
SplitCriticalEdge(TI, s, this);
if (TI->getNumSuccessors() == 1) {
IncrementCounterInBlock(BB, i++, Counters);
} else {
IncrementCounterInBlock(TI->getSuccessor(s), i++, Counters);
}
}
}
InsertProfilingInitCall(Main, "llvm_start_edge_profiling", Counters);
return true;
}