use of org.bytedeco.llvm.LLVM.LLVMMemoryBufferRef in project javacpp-presets by bytedeco.
the class EmitBitcode method EvaluateBitcode.
/**
* Sample code for importing a LLVM bitcode file and running a function
* inside of the imported module
* <p>
* This sample depends on EmitBitcode to produce the bitcode file. Make sure
* you've ran the EmitBitcode sample and have the 'sum.bc' bitcode file.
* <p>
* This sample contains code for the following steps:
* <p>
* 1. Initializing required LLVM components
* 2. Load and parse the bitcode
* 3. Run the 'sum' function inside the module
* 4. Dispose of the allocated resources
*/
public static void EvaluateBitcode() {
// Stage 1: Initialize LLVM components
LLVMInitializeCore(LLVMGetGlobalPassRegistry());
LLVMInitializeNativeAsmPrinter();
LLVMInitializeNativeAsmParser();
LLVMInitializeNativeTarget();
// Stage 2: Load and parse bitcode
LLVMContextRef context = LLVMContextCreate();
LLVMTypeRef i32Type = LLVMInt32TypeInContext(context);
LLVMModuleRef module = new LLVMModuleRef();
LLVMMemoryBufferRef membuf = new LLVMMemoryBufferRef();
BytePointer inputFile = new BytePointer("./sum.bc");
if (LLVMCreateMemoryBufferWithContentsOfFile(inputFile, membuf, error) != 0) {
System.err.println("Failed to read file into memory buffer: " + error.getString());
LLVMDisposeMessage(error);
return;
}
if (LLVMParseBitcodeInContext2(context, membuf, module) != 0) {
System.err.println("Failed to parser module from bitcode");
return;
}
LLVMExecutionEngineRef engine = new LLVMExecutionEngineRef();
if (LLVMCreateInterpreterForModule(engine, module, error) != 0) {
System.err.println("Failed to create LLVM interpreter: " + error.getString());
LLVMDisposeMessage(error);
return;
}
LLVMValueRef sum = LLVMGetNamedFunction(module, "sum");
PointerPointer<Pointer> arguments = new PointerPointer<>(2).put(0, LLVMCreateGenericValueOfInt(i32Type, 42, /* signExtend */
0)).put(1, LLVMCreateGenericValueOfInt(i32Type, 30, /* signExtend */
0));
LLVMGenericValueRef result = LLVMRunFunction(engine, sum, 2, arguments);
System.out.println();
System.out.print("The result of add(42, 30) imported from bitcode and executed with LLVM interpreter is: ");
System.out.println(LLVMGenericValueToInt(result, /* signExtend */
0));
// Stage 4: Dispose of the allocated resources
LLVMDisposeModule(module);
LLVMContextDispose(context);
}
Aggregations