How do I insert a printf call in the IR?

Hi Everyone,

I want to generate IR for the following C code
printf("Hello World!");

To insert a printf call in the IR, I use

Function* myPrint = M.getFunction("printf");

to get the function from my symbol table.

Once I have the function
to make a call to this function I use

CallInst::Create(myPrint, args.begin(), args.end(),"", B);

But I am not being able to pass a string into the argument vector.
should I define args as
std::vector<const Type*> args;
or
std::vector<const PointerType*> args;
or
std::vector<Value*> args;

and how do I convert a constant string to either of these types, so that I can push it on the args list.

Thanks!
Mrunal

Shah, Mrunal J wrote:

Once I have the function
to make a call to this function I use

CallInst::Create(myPrint, args.begin(), args.end(),"", B);

But I am not being able to pass a string into the argument vector.
should I define args as
std::vector<const Type*> args;
or
std::vector<const PointerType*> args;
or std::vector<Value*> args;

and how do I convert a constant string to either of these types, so that I can push it on the args list.

You need to put the string constant into a GlobalVariable (which is a Value).

This is a bit tricky if you're using the direct API. I suggest using "llc -march=cpp" on a program that does printf("Hello world!");

Using IRBuilder is easier. Starting with LLVM 2.4, there's a CreateGlobalString function that takes a const char *String and returns a Value*.

Nick

Thanks a lot Nick

-march=cpp was very helpful.
But I still have a small problem, I am trying to insert a printf in a transformation pass.
So when the original program already has a printf, on executing the transformation pass, it tries to create function "printf1" instead of "printf"

Am I missing something here?

Thanks again!
Mrunal

I figured it!

Instead of creating the function, I use module.getFunction if it already exists.
Or I could use getOrInsertFunction().

I did it and it worked.

Thanks again!
Mrunal

Shah, Mrunal J wrote:

Thanks a lot Nick

-march=cpp was very helpful.
But I still have a small problem, I am trying to insert a printf in a transformation pass. So when the original program already has a printf, on executing the transformation pass, it tries to create function "printf1" instead of "printf"

Am I missing something here?

Use M->getOrInsertFunction.

http://llvm.org/doxygen/classllvm_1_1Module.html#04eca33967535248a35daaf216420bef

Nick