Help with creating and replacing instructions in LLVM

Hi,

I have the following instruction in my IR-
%call2 = call i8* @strcpy(i8* %1, i8* %2) #2

I intend to change call to strcpy with strncpy. I have included the following code in runOnFunction, so that when it is strcpy’s turn to be invoked, strncpy is invoked instead.

Assuming I* is the strcpy instruction,

CallInst* x=new CallInst::CreateCall3(strncpy,1,2,ConstantInt(16),llvm::Twine(“my_strncpy”));
ReplaceInstWithInst(I*,x);

I’m running into a whole bunch of errors in CreateCall3(). How can I go about writing this correctly?

Any help would be appreciated.

Thanks.

Hi Shivam,

CallInst* x=new
CallInst::CreateCall3(strncpy,1,2,ConstantInt(16),llvm::Twine("my_strncpy"));
ReplaceInstWithInst(I*,x);

There are quite a few problems with this fragment
1. "new" is an operator which takes a type and allocates memory for
it. A function call like that can never be a correct argument for it.
In this case CreateCall3 already includes a "new".
2. CreateCall3 is a method of the IRBuilder, not CallInst (so you
probably want "Builder.CreateCall3").
3. You're confusing names in the LLVM IR with names available at the C
level. If you look at
http://llvm.org/docs/doxygen/html/classllvm_1_1IRBuilder.html, you'll
see that CreateCall3's first 3 arguments need to have type "Value *".
Neither "strncpy", 1 or 2 qualify.
a) For 1 and 2, you want "I->getOperand(0)" and "I->getOperand(1)".
b) For "strncpy" you want to call the Module's getOrInsertFunction
method to teach it about strncpy and it's prototype. Take a look at
the prototype here:
http://llvm.org/docs/doxygen/html/classllvm_1_1Module.html
4. ConstantInt doesn't have a constructor like that. You need to call
ConstantInt::get (see
http://llvm.org/docs/doxygen/html/classllvm_1_1ConstantInt.html) and
provide it with a type as well as the value (so that the call knows
whether to "call @strncpy(..., i32 16)", "call @strncpy(..., i64 16)"
or whatever.
5. "I*" is invalid syntax in C++. You probably just mean "I", the
pointer to the Instruction.

Overall, I'd suggest living keeping the LLVM docs site open all the
time and making sure you're using the correct functions from there.

Cheers.

Tim.