Skip to content

Instantly share code, notes, and snippets.

@nicolasff
Created April 23, 2009 12:16
Show Gist options
  • Save nicolasff/100469 to your computer and use it in GitHub Desktop.
Save nicolasff/100469 to your computer and use it in GitHub Desktop.
/**
* g++ `llvm-config --cxxflags` -c -o test.o test.cpp
* g++ -o test `llvm-config --ldflags --libs` test.o
*/
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/ModuleProvider.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/Interpreter.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include <iostream>
using namespace llvm;
using std::endl;
static Function *CreatePlusFunction(Module *M) {
// Create the plus function and insert it into module M. This function is said
// to return an int and take two int parameters.
Function *PlusF = cast<Function>(M->getOrInsertFunction("plus",
Type::Int32Ty, Type::Int32Ty,
Type::Int32Ty, (Type *)0));
// Get pointers to the integer arguments
Function::arg_iterator ai = PlusF->arg_begin();
Argument *Arg0 = ai;
Arg0->setName("Arg0");
ai++;
Argument *Arg1 = ai;
Arg1->setName("Arg1");
BasicBlock* mainBB = new BasicBlock("main", PlusF);
Value *Sum = BinaryOperator::createAdd(Arg0, Arg1, "addresult", mainBB);
new ReturnInst(Sum, mainBB);
return PlusF;
}
int
main(int argc, char *argv[]) {
Module *M = new Module("test");
// We are about to create the "plus" function:
Function *PlusF = CreatePlusFunction(M);
// Now we going to create JIT
ExistingModuleProvider *MP = new ExistingModuleProvider(M);
ExecutionEngine *EE = ExecutionEngine::create(MP, false);
cerr << *M << endl;
cerr << "verifying... " << endl;
// if (verifyModule(*M)) {
// std::cerr << argv[0] << ": Error constructing function!\n";
// return 1;
// }
int a = 1700, b = 29;
std::vector<GenericValue> Args(2);
Args[0].IntVal = APInt(32, a);
Args[1].IntVal = APInt(32, b);
GenericValue GVret = EE->runFunction(PlusF, Args);
// import result of execution
cerr << "plus("<<a<<","<<b<<")=" << GVret.IntVal.toStringUnsigned(10) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment