Created
June 14, 2017 03:05
-
-
Save zz-jason/d8d95860c785680cffa26c83bc0f46a3 to your computer and use it in GitHub Desktop.
example of using llvm IR library and JIT system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <iostream> | |
#include "llvm/ExecutionEngine/JIT.h" | |
#include "llvm/ADT/OwningPtr.h" | |
#include "llvm/Bitcode/ReaderWriter.h" | |
#include "llvm/IR/LLVMContext.h" | |
#include "llvm/IR/Module.h" | |
#include "llvm/Support/FileSystem.h" | |
#include "llvm/Support/MemoryBuffer.h" | |
#include "llvm/Support/ManagedStatic.h" | |
#include "llvm/Support/raw_ostream.h" | |
#include "llvm/Support/system_error.h" | |
#include "llvm/Support/TargetSelect.h" | |
using namespace llvm; | |
int main() | |
{ | |
llvm::InitializeNativeTarget(); | |
// read byte-code from file | |
llvm::OwningPtr<llvm::MemoryBuffer> Buffer; | |
if (llvm::MemoryBuffer::getFile("./sum.bc", Buffer)) | |
{ | |
llvm::errs() << "sum.bc not found\n"; | |
return -1; | |
} | |
// generate corresponding LLVM module | |
llvm::LLVMContext Context; | |
std::string ErrorMessage; | |
llvm::Module* M = llvm::ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage); | |
if (! M) | |
{ | |
llvm::errs() << ErrorMessage << "\n"; | |
return -1; | |
} | |
// create JIT execution engine and setup JIT, no function is complied yet | |
llvm::OwningPtr<llvm::ExecutionEngine> EE(llvm::EngineBuilder(M).create()); | |
// retrieve the Function IR object that represents sum | |
llvm::Function* SumFn = M->getFunction("sum"); | |
// trigger JIT compilation | |
int(*Sum)(int, int) = (int(*)(int, int))EE->getPointerToFunction(SumFn); | |
// call the original sum function via the JIT-compiled function | |
int res = Sum(4, 5); | |
llvm::outs() << "Sum result: " << res << "\n"; | |
// release the execution engine allocated memory that holds the function code | |
EE->freeMachineCodeForFunction(SumFn); | |
llvm::llvm_shutdown(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment