blob: 622215b7a7b8119b266a64297ea30a38a77e6e14 [file] [log] [blame]
Chris Lattner6701a862003-05-14 13:26:47 +00001//===-- VM.cpp - LLVM Just in Time Compiler -------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00002//
3// This tool implements a just-in-time compiler for LLVM, allowing direct
4// execution of LLVM bytecode in an efficient manner.
5//
6//===----------------------------------------------------------------------===//
7
8#include "VM.h"
9#include "llvm/Target/TargetMachine.h"
10#include "llvm/CodeGen/MachineCodeEmitter.h"
11#include "llvm/Function.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012
13VM::~VM() {
14 delete MCE;
15 delete &TM;
16}
17
18/// setupPassManager - Initialize the VM PassManager object with all of the
19/// passes needed for the target to generate code.
20///
21void VM::setupPassManager() {
22 // Compile LLVM Code down to machine code in the intermediate representation
23 if (TM.addPassesToJITCompile(PM)) {
24 std::cerr << "lli: target '" << TM.getName()
25 << "' doesn't support JIT compilation!\n";
26 abort();
27 }
28
29 // Turn the machine code intermediate representation into bytes in memory that
30 // may be executed.
31 //
32 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
33 std::cerr << "lli: target '" << TM.getName()
34 << "' doesn't support machine code emission!\n";
35 abort();
36 }
37}
38
Chris Lattnerbd199fb2002-12-24 00:01:05 +000039/// getPointerToFunction - This method is used to get the address of the
40/// specified function, compiling it if neccesary.
41///
Brian Gaeke71d84782003-08-13 18:16:34 +000042void *VM::getPointerToFunction(Function *F) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000043 void *&Addr = GlobalAddress[F]; // Function already code gen'd
44 if (Addr) return Addr;
45
Misha Brukman005e5e92003-10-14 21:37:41 +000046 // Make sure we read in the function if it exists in this Module
47 MP->materializeFunction(F);
48
Chris Lattner0d448c02003-01-13 01:00:48 +000049 if (F->isExternal())
50 return Addr = getPointerToNamedFunction(F->getName());
Chris Lattnerbd199fb2002-12-24 00:01:05 +000051
Chris Lattner66a84942003-05-08 21:08:43 +000052 static bool isAlreadyCodeGenerating = false;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +000053 assert(!isAlreadyCodeGenerating && "ERROR: RECURSIVE COMPILATION DETECTED!");
Chris Lattner66a84942003-05-08 21:08:43 +000054
Brian Gaeke71d84782003-08-13 18:16:34 +000055 // JIT the function
Chris Lattner66a84942003-05-08 21:08:43 +000056 isAlreadyCodeGenerating = true;
Brian Gaeke71d84782003-08-13 18:16:34 +000057 PM.run(*F);
Chris Lattner66a84942003-05-08 21:08:43 +000058 isAlreadyCodeGenerating = false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000059
60 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
61 return Addr;
62}