How to create a CallInst that calls a standard c function like "printf"

I am working on a program based on LLVM. I want to modify the .bc file
throught C++ APIs provided by LLVM, but I don't know how to create a
CallInst that calls a standard c function like "printf", can anyone help me
with this problem?

The file attached is the program I wrote, it can be compiled, however, the
result of the dump of the retrieved module is not correct(missing global
variable and will cause 'program use external function 'myprintf' which
could not be resolved') problem.
http://old.nabble.com/file/p27210247/test.cpp test.cpp

SOS!!!
It is really an emergency problem for me to resolve, if anyone knows the
answer, please let me know, I will
appreciate it, thank you very much!

Mary_nju wrote:

I am working on a program based on LLVM. I want to modify the .bc file
throught C++ APIs provided by LLVM, but I don't know how to create a
CallInst that calls a standard c function like "printf", can anyone help
me with this problem?

The file attached is the program I wrote, it can be compiled, however, the
result of the dump of the retrieved module is not correct(missing global
variable and will cause 'program use external function 'myprintf' which
could not be resolved') problem.
http://old.nabble.com/file/p27210247/test.cpp test.cpp

:slight_smile:

Mary_nju wrote:

SOS!!!
It is really an emergency problem for me to resolve, if anyone knows the
answer, please let me know, I will appreciate it, thank you very much!
  
The way to do this is to write code to do two things:

1) Write code that will insert a new function named printf that has no body.
2) Write code that will insert a call instruction (CallInst) that will call the printf function you created in step 1.

After running your transform, you should generate native code and then link against the C library. The function with no body will be resolved during the final native code link. The JIT will automatically do this for you. If you're doing static compilation, you use llc to generate native assembly code from the bitcode (.bc file) and then use gcc to assembly the output and link it with standard libraries.

Looking at your code, you seem to have done this. The only problem is that you named the function "myprintf" instead of "printf".

-- John T.

Hi

A good way to work this kind of thing out is to use the online demo
application and look at the C++ code that it prints out when you
compile it.

e.g.

* Go to http://llvm.org/demo/
* Click "Show LLVM C++ API code"
* Click "Compile Source Code"

Search the code for "printf" and you should be able to easily see how
it is used.

Cheers
Rich