1 //===-- VM.cpp - LLVM Just in Time Compiler -------------------------------===//
3 // This tool implements a just-in-time compiler for LLVM, allowing direct
4 // execution of LLVM bytecode in an efficient manner.
6 //===----------------------------------------------------------------------===//
9 #include "llvm/Function.h"
10 #include "llvm/ModuleProvider.h"
11 #include "llvm/CodeGen/MachineCodeEmitter.h"
12 #include "llvm/Target/TargetMachine.h"
19 /// setupPassManager - Initialize the VM PassManager object with all of the
20 /// passes needed for the target to generate code.
22 void VM::setupPassManager() {
23 // Compile LLVM Code down to machine code in the intermediate representation
24 if (TM.addPassesToJITCompile(PM)) {
25 std::cerr << "lli: target '" << TM.getName()
26 << "' doesn't support JIT compilation!\n";
30 // Turn the machine code intermediate representation into bytes in memory that
33 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
34 std::cerr << "lli: target '" << TM.getName()
35 << "' doesn't support machine code emission!\n";
40 /// runJITOnFunction - Run the FunctionPassManager full of
41 /// just-in-time compilation passes on F, hopefully filling in
42 /// GlobalAddress[F] with the address of F's machine code.
44 void VM::runJITOnFunction (Function *F) {
45 static bool isAlreadyCodeGenerating = false;
46 assert(!isAlreadyCodeGenerating && "ERROR: RECURSIVE COMPILATION DETECTED!");
49 isAlreadyCodeGenerating = true;
51 isAlreadyCodeGenerating = false;
54 /// getPointerToFunction - This method is used to get the address of the
55 /// specified function, compiling it if neccesary.
57 void *VM::getPointerToFunction(Function *F) {
58 void *&Addr = GlobalAddress[F]; // Check if function already code gen'd
59 if (Addr) return Addr;
61 // Make sure we read in the function if it exists in this Module
62 MP->materializeFunction(F);
65 return Addr = getPointerToNamedFunction(F->getName());
68 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
72 /// recompileAndRelinkFunction - This method is used to force a function
73 /// which has already been compiled, to be compiled again, possibly
74 /// after it has been modified. Then the entry to the old copy is overwritten
75 /// with a branch to the new copy. If there was no old copy, this acts
76 /// just like VM::getPointerToFunction().
78 void *VM::recompileAndRelinkFunction(Function *F) {
79 void *&Addr = GlobalAddress[F]; // Check if function already code gen'd
81 // If it's not already compiled (this is kind of weird) there is no
82 // reason to patch it up.
83 if (!Addr) { return getPointerToFunction (F); }
88 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
89 TM.replaceMachineCodeForFunction (OldAddr, Addr);