blob: 71d713468b67ca26d9795cfd9dad6cc3d7e7a0a6 [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 Grosbach34714a02011-03-22 18:05:27 +000011#include "llvm/DerivedTypes.h"
Jim Grosbach31649e62011-03-18 22:48:41 +000012#include "llvm/Function.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000013#include "llvm/ExecutionEngine/GenericValue.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000014#include "llvm/ExecutionEngine/JITMemoryManager.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000015#include "llvm/ExecutionEngine/MCJIT.h"
16#include "llvm/ExecutionEngine/ObjectBuffer.h"
17#include "llvm/ExecutionEngine/ObjectImage.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000019#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000020#include "llvm/Support/DynamicLibrary.h"
Jim Grosbachf9229102011-03-22 01:06:42 +000021#include "llvm/Support/MemoryBuffer.h"
Andrew Kaylorea708d12012-08-07 18:33:00 +000022#include "llvm/Support/MutexGuard.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000023#include "llvm/DataLayout.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000024
25using namespace llvm;
26
27namespace {
28
29static struct RegisterJIT {
30 RegisterJIT() { MCJIT::Register(); }
31} JITRegistrator;
32
33}
34
35extern "C" void LLVMLinkInMCJIT() {
36}
37
38ExecutionEngine *MCJIT::createJIT(Module *M,
39 std::string *ErrorStr,
40 JITMemoryManager *JMM,
Daniel Dunbar6aec2982010-11-17 16:06:43 +000041 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000042 TargetMachine *TM) {
Daniel Dunbar6aec2982010-11-17 16:06:43 +000043 // Try to register the program as a source of symbols to resolve against.
44 //
45 // FIXME: Don't do this here.
46 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
47
Andrew Kaylor647d6d72012-11-01 00:46:04 +000048 return new MCJIT(M, TM, JMM, GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000049}
50
Jim Grosbach8005bcd2012-08-21 15:42:49 +000051MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
52 bool AllocateGVsWithCode)
53 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000054 isCompiled(false), M(m) {
Jim Grosbach31649e62011-03-18 22:48:41 +000055
Micah Villmow3574eca2012-10-08 16:38:25 +000056 setDataLayout(TM->getDataLayout());
Andrew Kaylorea708d12012-08-07 18:33:00 +000057}
58
59MCJIT::~MCJIT() {
60 delete MemMgr;
61 delete TM;
62}
63
64void MCJIT::emitObject(Module *m) {
65 /// Currently, MCJIT only supports a single module and the module passed to
66 /// this function call is expected to be the contained module. The module
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000067 /// is passed as a parameter here to prepare for multiple module support in
Andrew Kaylorea708d12012-08-07 18:33:00 +000068 /// the future.
69 assert(M == m);
70
71 // Get a thread lock to make sure we aren't trying to compile multiple times
72 MutexGuard locked(lock);
73
74 // FIXME: Track compilation state on a per-module basis when multiple modules
75 // are supported.
76 // Re-compilation is not supported
77 if (isCompiled)
78 return;
79
80 PassManager PM;
81
Micah Villmow3574eca2012-10-08 16:38:25 +000082 PM.add(new DataLayout(*TM->getDataLayout()));
Jim Grosbach31649e62011-03-18 22:48:41 +000083
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000084 // The RuntimeDyld will take ownership of this shortly
85 OwningPtr<ObjectBufferStream> Buffer(new ObjectBufferStream());
86
Jim Grosbach31649e62011-03-18 22:48:41 +000087 // Turn the machine code intermediate representation into bytes in memory
88 // that may be executed.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000089 if (TM->addPassesToEmitMC(PM, Ctx, Buffer->getOStream(), false)) {
Jim Grosbach31649e62011-03-18 22:48:41 +000090 report_fatal_error("Target does not support MC emission!");
91 }
92
93 // Initialize passes.
Andrew Kaylorea708d12012-08-07 18:33:00 +000094 PM.run(*m);
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000095 // Flush the output buffer to get the generated code into memory
96 Buffer->flush();
Jim Grosbachf9229102011-03-22 01:06:42 +000097
98 // Load the object into the dynamic linker.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000099 // handing off ownership of the buffer
100 LoadedObject.reset(Dyld.loadObject(Buffer.take()));
101 if (!LoadedObject)
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000102 report_fatal_error(Dyld.getErrorString());
Andrew Kaylorea708d12012-08-07 18:33:00 +0000103
Jim Grosbach69e81322011-04-13 15:28:10 +0000104 // Resolve any relocations.
105 Dyld.resolveRelocations();
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000106
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000107 // FIXME: Make this optional, maybe even move it to a JIT event listener
108 LoadedObject->registerWithDebugger();
109
Andrew Kaylorea708d12012-08-07 18:33:00 +0000110 // FIXME: Add support for per-module compilation state
111 isCompiled = true;
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000112}
113
Andrew Kaylor28989882012-11-05 20:57:16 +0000114// FIXME: Add a parameter to identify which object is being finalized when
115// MCJIT supports multiple modules.
116void MCJIT::finalizeObject() {
117 // If the module hasn't been compiled, just do that.
118 if (!isCompiled) {
119 // If the call to Dyld.resolveRelocations() is removed from emitObject()
120 // we'll need to do that here.
121 emitObject(M);
122 return;
123 }
124
125 // Resolve any relocations.
126 Dyld.resolveRelocations();
127}
128
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000129void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
130 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000131}
132
133void *MCJIT::getPointerToFunction(Function *F) {
Jim Grosbach35ed8422012-09-05 16:50:40 +0000134 // FIXME: This should really return a uint64_t since it's a pointer in the
135 // target address space, not our local address space. That's part of the
136 // ExecutionEngine interface, though. Fix that when the old JIT finally
137 // dies.
138
Andrew Kaylorea708d12012-08-07 18:33:00 +0000139 // FIXME: Add support for per-module compilation state
140 if (!isCompiled)
141 emitObject(M);
142
Jim Grosbach34714a02011-03-22 18:05:27 +0000143 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
144 bool AbortOnFailure = !F->hasExternalWeakLinkage();
145 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
146 addGlobalMapping(F, Addr);
147 return Addr;
148 }
149
Andrew Kaylorea708d12012-08-07 18:33:00 +0000150 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000151 // FIXME: Should we be using the mangler for this? Probably.
Jim Grosbach35ed8422012-09-05 16:50:40 +0000152 //
153 // This is the accessor for the target address, so make sure to check the
154 // load address of the symbol, not the local address.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000155 StringRef BaseName = F->getName();
156 if (BaseName[0] == '\1')
Jim Grosbach35ed8422012-09-05 16:50:40 +0000157 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
158 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
Jim Grosbachc0ceedb2011-05-19 00:45:05 +0000159 + BaseName).str());
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000160}
161
162void *MCJIT::recompileAndRelinkFunction(Function *F) {
163 report_fatal_error("not yet implemented");
164}
165
166void MCJIT::freeMachineCodeForFunction(Function *F) {
167 report_fatal_error("not yet implemented");
168}
169
170GenericValue MCJIT::runFunction(Function *F,
171 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000172 assert(F && "Function *F was null at entry to run()");
173
Jim Grosbach31649e62011-03-18 22:48:41 +0000174 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000175 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000176 FunctionType *FTy = F->getFunctionType();
177 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000178
179 assert((FTy->getNumParams() == ArgValues.size() ||
180 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
181 "Wrong number of arguments passed into function!");
182 assert(FTy->getNumParams() == ArgValues.size() &&
183 "This doesn't support passing arguments through varargs (yet)!");
184
185 // Handle some common cases first. These cases correspond to common `main'
186 // prototypes.
187 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
188 switch (ArgValues.size()) {
189 case 3:
190 if (FTy->getParamType(0)->isIntegerTy(32) &&
191 FTy->getParamType(1)->isPointerTy() &&
192 FTy->getParamType(2)->isPointerTy()) {
193 int (*PF)(int, char **, const char **) =
194 (int(*)(int, char **, const char **))(intptr_t)FPtr;
195
196 // Call the function.
197 GenericValue rv;
198 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
199 (char **)GVTOP(ArgValues[1]),
200 (const char **)GVTOP(ArgValues[2])));
201 return rv;
202 }
203 break;
204 case 2:
205 if (FTy->getParamType(0)->isIntegerTy(32) &&
206 FTy->getParamType(1)->isPointerTy()) {
207 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
208
209 // Call the function.
210 GenericValue rv;
211 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
212 (char **)GVTOP(ArgValues[1])));
213 return rv;
214 }
215 break;
216 case 1:
217 if (FTy->getNumParams() == 1 &&
218 FTy->getParamType(0)->isIntegerTy(32)) {
219 GenericValue rv;
220 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
221 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
222 return rv;
223 }
224 break;
225 }
226 }
227
228 // Handle cases where no arguments are passed first.
229 if (ArgValues.empty()) {
230 GenericValue rv;
231 switch (RetTy->getTypeID()) {
232 default: llvm_unreachable("Unknown return type for function call!");
233 case Type::IntegerTyID: {
234 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
235 if (BitWidth == 1)
236 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
237 else if (BitWidth <= 8)
238 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
239 else if (BitWidth <= 16)
240 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
241 else if (BitWidth <= 32)
242 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
243 else if (BitWidth <= 64)
244 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
245 else
246 llvm_unreachable("Integer types > 64 bits not supported");
247 return rv;
248 }
249 case Type::VoidTyID:
250 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
251 return rv;
252 case Type::FloatTyID:
253 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
254 return rv;
255 case Type::DoubleTyID:
256 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
257 return rv;
258 case Type::X86_FP80TyID:
259 case Type::FP128TyID:
260 case Type::PPC_FP128TyID:
261 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000262 case Type::PointerTyID:
263 return PTOGV(((void*(*)())(intptr_t)FPtr)());
264 }
265 }
266
Craig Topper85814382012-02-07 05:05:23 +0000267 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000268}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000269
270void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000271 bool AbortOnFailure) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000272 // FIXME: Add support for per-module compilation state
273 if (!isCompiled)
274 emitObject(M);
275
Danil Malyshev30b9e322012-03-28 21:46:36 +0000276 if (!isSymbolSearchingDisabled() && MemMgr) {
277 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
278 if (ptr)
279 return ptr;
280 }
281
282 /// If a LazyFunctionCreator is installed, use it to get/create the function.
283 if (LazyFunctionCreator)
284 if (void *RP = LazyFunctionCreator(Name))
285 return RP;
286
287 if (AbortOnFailure) {
288 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000289 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000290 }
291 return 0;
292}