问题
Now I use clang build my .c file to .s file. And I have used the llvm API modify the IR. However, now I can't save my modified IR to a file. I want to use "LLVMWriteBitcodeToFile", but I can't find the struct of "LLVMOpaqueModule"; I want to use "WriteBitcodeToFile", it always show me "type mismatch". And I also want to know how to build an IR file to a executable file.
Next are two methods I use to save a module:
1、First use WriteBitcodeToFile
bool unbuffered = false;
llvm::raw_ostream ro(unbuffered);
WriteBitcodeToFile(m, ro);
2、Second use LLVMWriteBitcodeToFile
const char *Path = "hello2.s";
int ans = LLVMWriteBitcodeToFile(m, Path);
note: m is a point of Module instance
回答1:
- For saving the IR into a file, see the answer to this question: writing module to .bc bitcode file
- For compiling IR to an object file, look at the
llc
tool and follow what itsmain
function does.
回答2:
Check out these functions in llvm-c/TargetMachine.h
:
/** Emits an asm or object file for the given module to the filename. This
wraps several c++ only classes (among them a file stream). Returns any
error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */
LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage);
/** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */
LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M,
LLVMCodeGenFileType codegen, char** ErrorMessage, LLVMMemoryBufferRef *OutMemBuf);
See also How to generate machine code with llvm
回答3:
for writing llvm bitcode to file what I do is :
std::error_code EC;
llvm::raw_fd_ostream OS("module", EC, llvm::sys::fs::F_None);
WriteBitcodeToFile(pBiFModule, OS);
OS.flush();
and then disassemble using llvm-dis.
来源:https://stackoverflow.com/questions/13928250/how-to-save-ir-to-a-file-and-build-it-to-an-executable-file