Help needed with a pass

I’m a newbie to LLVM and I’ve really been struggling to write a pass which changes the behavior of the following function:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void foo(char* bar)
{
const char* path;
path=getenv(<SOME_ENV_VAR>);

if (path!=NULL)
{strcpy(bar,path);}
else
{printf(“env_var not set!”);}
}

In the pass, I hope to invoke strncpy(dest,src,n) instead of strcpy(dest,src).

After looking at the IR, this is what I’ve got so far:

#include <stdlib.h>

#include <stdio.h>

#include “llvm/Pass.h”

#include “llvm/IR/Function.h”

#include “llvm/Support/raw_ostream.h”

#include “llvm/IR/Module.h”

#include “llvm/PassManager.h”

#include “llvm/Analysis/Verifier.h”

#include “llvm/Assembly/PrintModulePass.h”

#include “llvm/IR/IRBuilder.h”

using namespace llvm;

Module* makeLLVMModule() {

Module* mod = new Module(getGlobalContext());

Function* strncpy_func = cast(mod->getOrInsertFunction(new StringRef(“strncpy”), Type::getInt32Ty(getGlobalContext()), Type::getInt32Ty(getGlobalContext()), Type::getInt32Ty(getGlobalContext()), NULL));

Function* printf_func = cast(mod->getOrInsertFunction(new StringRef(“printf”), Type::getInt32Ty(getGlobalContext()), NULL));

Constant* c = mod->getOrInsertFunction(new StringRef(“foo”),Type::getInt32Ty(getGlobalContext()),NULL);

Function* foo = cast(c);

Function::arg_iterator args =foo->arg_begin();

Value* bar = args++;

BasicBlock* Entry = BasicBlock::Create(getGlobalContext(),new Twine(“Entry”), foo);

BasicBlock* False = BasicBlock::Create(getGlobalContext(),new Twine(“False”), foo);

BasicBlock* True = BasicBlock::Create(getGlobalContext(),new Twine(“True”), foo);

const char* pPath;

pPath = getenv("<SOME_ENV_VAR>");

Twine temp=new Twine(“tmp”);

IRBuilder<> builder(Entry);

Value* envVarDoesntExist = builder.CreateICmpEQ(new StringRef(pPath),Constant::getNullValue(StringRef),temp);

builder.CreateCondBr(envVarDoesntExist, False, True);

builder.SetInsertPoint(True);

builder.CreateCall3(strncpy_func,buf,new StringRef(pPath),29,temp);

builder.SetInsertPoint(False);

builder.CreateCall(printf_func,“Set <SOME_ENV_VAR>\n”,temp);

return mod;

}

}

char funcP::ID = 0;

static RegisterPass X(“funcp”, “funcP”, false, false);

Any help would be appreciated.

Thanks,
Rohit