blob: 739ffd7d85da78d418ca552020dcb640220498b4 [file] [log] [blame]
Eric Christopherbb498ca2011-04-22 03:07:06 +00001//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
Daniel Dunbar6aec2982010-11-17 16:06:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "MCJIT.h"
Jim Grosbachfcbe5b72011-04-04 23:04:39 +000011#include "MCJITMemoryManager.h"
Jim Grosbach34714a02011-03-22 18:05:27 +000012#include "llvm/DerivedTypes.h"
Jim Grosbach31649e62011-03-18 22:48:41 +000013#include "llvm/Function.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000014#include "llvm/ExecutionEngine/GenericValue.h"
15#include "llvm/ExecutionEngine/MCJIT.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000016#include "llvm/ExecutionEngine/JITMemoryManager.h"
17#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000018#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000019#include "llvm/Support/DynamicLibrary.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000020#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000021#include "llvm/Support/MutexGuard.h"
Jim Grosbach31649e62011-03-18 22:48:41 +000022#include "llvm/Target/TargetData.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000023
24using namespace llvm;
25
26namespace {
27
28static struct RegisterJIT {
29 RegisterJIT() { MCJIT::Register(); }
30} JITRegistrator;
31
32}
33
34extern "C" void LLVMLinkInMCJIT() {
35}
36
37ExecutionEngine *MCJIT::createJIT(Module *M,
38 std::string *ErrorStr,
39 JITMemoryManager *JMM,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000040 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000041 TargetMachine *TM) {
Daniel Dunbar6aec2982010-11-17 16:06:43 +000042 // Try to register the program as a source of symbols to resolve against.
43 //
44 // FIXME: Don't do this here.
45 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
46
Daniel Dunbar6aec2982010-11-17 16:06:43 +000047 // If the target supports JIT code generation, create the JIT.
48 if (TargetJITInfo *TJ = TM->getJITInfo())
Benjamin Kramer95a9d932012-06-06 19:47:08 +000049 return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM), GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000050
51 if (ErrorStr)
52 *ErrorStr = "target does not support JIT code generation";
53 return 0;
54}
55
Jim Grosbach31649e62011-03-18 22:48:41 +000056MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
Dylan Noblesmith9ea47172011-12-12 04:20:36 +000057 RTDyldMemoryManager *MM, bool AllocateGVsWithCode)
Andrew Kaylorea708d12012-08-07 18:33:00 +000058 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
59 isCompiled(false), M(m), OS(Buffer) {
Jim Grosbach31649e62011-03-18 22:48:41 +000060
Danil Malyshev0ba3c0a2011-09-30 16:40:10 +000061 setTargetData(TM->getTargetData());
Andrew Kaylorea708d12012-08-07 18:33:00 +000062}
63
64MCJIT::~MCJIT() {
65 delete MemMgr;
66 delete TM;
67}
68
69void MCJIT::emitObject(Module *m) {
70 /// Currently, MCJIT only supports a single module and the module passed to
71 /// this function call is expected to be the contained module. The module
72 /// is passed as a parameter here to prepare for multiple module support in
73 /// the future.
74 assert(M == m);
75
76 // Get a thread lock to make sure we aren't trying to compile multiple times
77 MutexGuard locked(lock);
78
79 // FIXME: Track compilation state on a per-module basis when multiple modules
80 // are supported.
81 // Re-compilation is not supported
82 if (isCompiled)
83 return;
84
85 PassManager PM;
86
Jim Grosbach31649e62011-03-18 22:48:41 +000087 PM.add(new TargetData(*TM->getTargetData()));
88
89 // Turn the machine code intermediate representation into bytes in memory
90 // that may be executed.
Evan Chengb95fc312011-11-16 08:38:26 +000091 if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
Jim Grosbach31649e62011-03-18 22:48:41 +000092 report_fatal_error("Target does not support MC emission!");
93 }
94
95 // Initialize passes.
Jim Grosbach31649e62011-03-18 22:48:41 +000096 // FIXME: When we support multiple modules, we'll want to move the code
97 // gen and finalization out of the constructor here and do it more
98 // on-demand as part of getPointerToFunction().
Andrew Kaylorea708d12012-08-07 18:33:00 +000099 PM.run(*m);
Jim Grosbach31649e62011-03-18 22:48:41 +0000100 // Flush the output buffer so the SmallVector gets its data.
101 OS.flush();
Jim Grosbachf9229102011-03-22 01:06:42 +0000102
103 // Load the object into the dynamic linker.
Andrew Kaylorea708d12012-08-07 18:33:00 +0000104 MemoryBuffer* MB = MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
Preston Gurdc68dda82012-04-12 20:13:57 +0000105 Buffer.size()),
106 "", false);
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000107 if (Dyld.loadObject(MB))
108 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000109
Jim Grosbach69e81322011-04-13 15:28:10 +0000110 // Resolve any relocations.
111 Dyld.resolveRelocations();
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000112
Andrew Kaylorea708d12012-08-07 18:33:00 +0000113 // FIXME: Add support for per-module compilation state
114 isCompiled = true;
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000115}
116
117void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
118 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000119}
120
121void *MCJIT::getPointerToFunction(Function *F) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000122 // FIXME: Add support for per-module compilation state
123 if (!isCompiled)
124 emitObject(M);
125
Jim Grosbach34714a02011-03-22 18:05:27 +0000126 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
127 bool AbortOnFailure = !F->hasExternalWeakLinkage();
128 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
129 addGlobalMapping(F, Addr);
130 return Addr;
131 }
132
Andrew Kaylorea708d12012-08-07 18:33:00 +0000133 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000134 // FIXME: Should we be using the mangler for this? Probably.
135 StringRef BaseName = F->getName();
136 if (BaseName[0] == '\1')
Jim Grosbachc0ceedb2011-05-19 00:45:05 +0000137 return (void*)Dyld.getSymbolAddress(BaseName.substr(1));
138 return (void*)Dyld.getSymbolAddress((TM->getMCAsmInfo()->getGlobalPrefix()
139 + BaseName).str());
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000140}
141
142void *MCJIT::recompileAndRelinkFunction(Function *F) {
143 report_fatal_error("not yet implemented");
144}
145
146void MCJIT::freeMachineCodeForFunction(Function *F) {
147 report_fatal_error("not yet implemented");
148}
149
150GenericValue MCJIT::runFunction(Function *F,
151 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000152 assert(F && "Function *F was null at entry to run()");
153
Jim Grosbach31649e62011-03-18 22:48:41 +0000154 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000155 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000156 FunctionType *FTy = F->getFunctionType();
157 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000158
159 assert((FTy->getNumParams() == ArgValues.size() ||
160 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
161 "Wrong number of arguments passed into function!");
162 assert(FTy->getNumParams() == ArgValues.size() &&
163 "This doesn't support passing arguments through varargs (yet)!");
164
165 // Handle some common cases first. These cases correspond to common `main'
166 // prototypes.
167 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
168 switch (ArgValues.size()) {
169 case 3:
170 if (FTy->getParamType(0)->isIntegerTy(32) &&
171 FTy->getParamType(1)->isPointerTy() &&
172 FTy->getParamType(2)->isPointerTy()) {
173 int (*PF)(int, char **, const char **) =
174 (int(*)(int, char **, const char **))(intptr_t)FPtr;
175
176 // Call the function.
177 GenericValue rv;
178 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
179 (char **)GVTOP(ArgValues[1]),
180 (const char **)GVTOP(ArgValues[2])));
181 return rv;
182 }
183 break;
184 case 2:
185 if (FTy->getParamType(0)->isIntegerTy(32) &&
186 FTy->getParamType(1)->isPointerTy()) {
187 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
188
189 // Call the function.
190 GenericValue rv;
191 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
192 (char **)GVTOP(ArgValues[1])));
193 return rv;
194 }
195 break;
196 case 1:
197 if (FTy->getNumParams() == 1 &&
198 FTy->getParamType(0)->isIntegerTy(32)) {
199 GenericValue rv;
200 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
201 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
202 return rv;
203 }
204 break;
205 }
206 }
207
208 // Handle cases where no arguments are passed first.
209 if (ArgValues.empty()) {
210 GenericValue rv;
211 switch (RetTy->getTypeID()) {
212 default: llvm_unreachable("Unknown return type for function call!");
213 case Type::IntegerTyID: {
214 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
215 if (BitWidth == 1)
216 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
217 else if (BitWidth <= 8)
218 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
219 else if (BitWidth <= 16)
220 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
221 else if (BitWidth <= 32)
222 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
223 else if (BitWidth <= 64)
224 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
225 else
226 llvm_unreachable("Integer types > 64 bits not supported");
227 return rv;
228 }
229 case Type::VoidTyID:
230 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
231 return rv;
232 case Type::FloatTyID:
233 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
234 return rv;
235 case Type::DoubleTyID:
236 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
237 return rv;
238 case Type::X86_FP80TyID:
239 case Type::FP128TyID:
240 case Type::PPC_FP128TyID:
241 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000242 case Type::PointerTyID:
243 return PTOGV(((void*(*)())(intptr_t)FPtr)());
244 }
245 }
246
Craig Topper85814382012-02-07 05:05:23 +0000247 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000248}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000249
250void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000251 bool AbortOnFailure) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000252 // FIXME: Add support for per-module compilation state
253 if (!isCompiled)
254 emitObject(M);
255
Danil Malyshev30b9e322012-03-28 21:46:36 +0000256 if (!isSymbolSearchingDisabled() && MemMgr) {
257 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
258 if (ptr)
259 return ptr;
260 }
261
262 /// If a LazyFunctionCreator is installed, use it to get/create the function.
263 if (LazyFunctionCreator)
264 if (void *RP = LazyFunctionCreator(Name))
265 return RP;
266
267 if (AbortOnFailure) {
268 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000269 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000270 }
271 return 0;
272}