#include "llvm/Pass.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Type.h"
#include "llvm/Instructions.h"
#include "llvm/Instruction.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IRBuilder.h"
using namespace llvm;
Module * M;
LLVMContext Context;
Twine * name = new Twine("print");
FunctionType *STy=FunctionType::get(Type::getInt32Ty(Context),Type::getInt32Ty(Context), false);
Function *check = Function::Create(STy, Function::ExternalLinkage, *name ,M);
AllocaInst* count;
namespace{
struct bishe_insert : public FunctionPass{
static char ID;
bishe_insert() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &func)
{
count = new AllocaInst(IntegerType::getInt32Ty(Context), 0, "count");
count->setAlignment(4);
for(Function::iterator F = func.begin(), E = func.end(); F!= E; ++F)
{
if(F == func.begin())
{
bishe_insert::insertOnFirstBlock(F);
}
bishe_insert::runOnBasicBlock(F);
}
return false;
}
/*insert alloca instruction in the start of the first basic block*/
virtual bool insertOnFirstBlock(Function::iterator &BB)
{
for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI)
{
if(BI == BB->begin())
{
BB->getInstList().insert((Instruction*)BI, count);
break;
}//end of if
}
return true;
}
virtual bool runOnBasicBlock(Function::iterator &BB)
{
for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI)
{
if(isa<LoadInst>(&(*BI)))
{
LoadInst *CI = dyn_cast<LoadInst>(BI);
/*load count*/
LoadInst* load_count = new LoadInst(count, "", false);
load_count->setAlignment(4);
/*call print(count)*/
CallInst* call_print = CallInst::Create(check, load_count, "");
/*insert the instructions*/
BB->getInstList().insert((Instruction*)CI, load_count);
BB->getInstList().insert((Instruction*)CI, call_print);
}//end of if
}
return true;
}
};
}
char bishe_insert::ID = 0;
static RegisterPass<bishe_insert> X("bishe_insert", "insert print calls");