blob: 99c65ecf95021d601f327b7f038e4e7e637c6c60 [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
Jim Grosbach8005bcd2012-08-21 15:42:49 +000047 return new MCJIT(M, TM, new MCJITMemoryManager(JMM), GVsWithCode);
Daniel Dunbar6aec2982010-11-17 16:06:43 +000048}
49
Jim Grosbach8005bcd2012-08-21 15:42:49 +000050MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
51 bool AllocateGVsWithCode)
52 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
Andrew Kaylorea708d12012-08-07 18:33:00 +000053 isCompiled(false), M(m), OS(Buffer) {
Jim Grosbach31649e62011-03-18 22:48:41 +000054
Danil Malyshev0ba3c0a2011-09-30 16:40:10 +000055 setTargetData(TM->getTargetData());
Andrew Kaylorea708d12012-08-07 18:33:00 +000056}
57
58MCJIT::~MCJIT() {
59 delete MemMgr;
60 delete TM;
61}
62
63void MCJIT::emitObject(Module *m) {
64 /// Currently, MCJIT only supports a single module and the module passed to
65 /// this function call is expected to be the contained module. The module
66 /// is passed as a parameter here to prepare for multiple module support in
67 /// the future.
68 assert(M == m);
69
70 // Get a thread lock to make sure we aren't trying to compile multiple times
71 MutexGuard locked(lock);
72
73 // FIXME: Track compilation state on a per-module basis when multiple modules
74 // are supported.
75 // Re-compilation is not supported
76 if (isCompiled)
77 return;
78
79 PassManager PM;
80
Jim Grosbach31649e62011-03-18 22:48:41 +000081 PM.add(new TargetData(*TM->getTargetData()));
82
83 // Turn the machine code intermediate representation into bytes in memory
84 // that may be executed.
Evan Chengb95fc312011-11-16 08:38:26 +000085 if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
Jim Grosbach31649e62011-03-18 22:48:41 +000086 report_fatal_error("Target does not support MC emission!");
87 }
88
89 // Initialize passes.
Jim Grosbach31649e62011-03-18 22:48:41 +000090 // FIXME: When we support multiple modules, we'll want to move the code
91 // gen and finalization out of the constructor here and do it more
92 // on-demand as part of getPointerToFunction().
Andrew Kaylorea708d12012-08-07 18:33:00 +000093 PM.run(*m);
Jim Grosbach31649e62011-03-18 22:48:41 +000094 // Flush the output buffer so the SmallVector gets its data.
95 OS.flush();
Jim Grosbachf9229102011-03-22 01:06:42 +000096
97 // Load the object into the dynamic linker.
Andrew Kaylorea708d12012-08-07 18:33:00 +000098 MemoryBuffer* MB = MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
Preston Gurdc68dda82012-04-12 20:13:57 +000099 Buffer.size()),
100 "", false);
Jim Grosbach8086f3b2011-03-23 19:51:34 +0000101 if (Dyld.loadObject(MB))
102 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 Kaylorea708d12012-08-07 18:33:00 +0000107 // FIXME: Add support for per-module compilation state
108 isCompiled = true;
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000109}
110
111void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
112 report_fatal_error("not yet implemented");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000113}
114
115void *MCJIT::getPointerToFunction(Function *F) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000116 // FIXME: Add support for per-module compilation state
117 if (!isCompiled)
118 emitObject(M);
119
Jim Grosbach34714a02011-03-22 18:05:27 +0000120 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
121 bool AbortOnFailure = !F->hasExternalWeakLinkage();
122 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
123 addGlobalMapping(F, Addr);
124 return Addr;
125 }
126
Andrew Kaylorea708d12012-08-07 18:33:00 +0000127 // FIXME: Should the Dyld be retaining module information? Probably not.
Jim Grosbach3ec2c7c2011-05-18 23:53:21 +0000128 // FIXME: Should we be using the mangler for this? Probably.
129 StringRef BaseName = F->getName();
130 if (BaseName[0] == '\1')
Jim Grosbachc0ceedb2011-05-19 00:45:05 +0000131 return (void*)Dyld.getSymbolAddress(BaseName.substr(1));
132 return (void*)Dyld.getSymbolAddress((TM->getMCAsmInfo()->getGlobalPrefix()
133 + BaseName).str());
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000134}
135
136void *MCJIT::recompileAndRelinkFunction(Function *F) {
137 report_fatal_error("not yet implemented");
138}
139
140void MCJIT::freeMachineCodeForFunction(Function *F) {
141 report_fatal_error("not yet implemented");
142}
143
144GenericValue MCJIT::runFunction(Function *F,
145 const std::vector<GenericValue> &ArgValues) {
Jim Grosbach34714a02011-03-22 18:05:27 +0000146 assert(F && "Function *F was null at entry to run()");
147
Jim Grosbach31649e62011-03-18 22:48:41 +0000148 void *FPtr = getPointerToFunction(F);
Jim Grosbach34714a02011-03-22 18:05:27 +0000149 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000150 FunctionType *FTy = F->getFunctionType();
151 Type *RetTy = FTy->getReturnType();
Jim Grosbach34714a02011-03-22 18:05:27 +0000152
153 assert((FTy->getNumParams() == ArgValues.size() ||
154 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
155 "Wrong number of arguments passed into function!");
156 assert(FTy->getNumParams() == ArgValues.size() &&
157 "This doesn't support passing arguments through varargs (yet)!");
158
159 // Handle some common cases first. These cases correspond to common `main'
160 // prototypes.
161 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
162 switch (ArgValues.size()) {
163 case 3:
164 if (FTy->getParamType(0)->isIntegerTy(32) &&
165 FTy->getParamType(1)->isPointerTy() &&
166 FTy->getParamType(2)->isPointerTy()) {
167 int (*PF)(int, char **, const char **) =
168 (int(*)(int, char **, const char **))(intptr_t)FPtr;
169
170 // Call the function.
171 GenericValue rv;
172 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
173 (char **)GVTOP(ArgValues[1]),
174 (const char **)GVTOP(ArgValues[2])));
175 return rv;
176 }
177 break;
178 case 2:
179 if (FTy->getParamType(0)->isIntegerTy(32) &&
180 FTy->getParamType(1)->isPointerTy()) {
181 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
182
183 // Call the function.
184 GenericValue rv;
185 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
186 (char **)GVTOP(ArgValues[1])));
187 return rv;
188 }
189 break;
190 case 1:
191 if (FTy->getNumParams() == 1 &&
192 FTy->getParamType(0)->isIntegerTy(32)) {
193 GenericValue rv;
194 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
195 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
196 return rv;
197 }
198 break;
199 }
200 }
201
202 // Handle cases where no arguments are passed first.
203 if (ArgValues.empty()) {
204 GenericValue rv;
205 switch (RetTy->getTypeID()) {
206 default: llvm_unreachable("Unknown return type for function call!");
207 case Type::IntegerTyID: {
208 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
209 if (BitWidth == 1)
210 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
211 else if (BitWidth <= 8)
212 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
213 else if (BitWidth <= 16)
214 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
215 else if (BitWidth <= 32)
216 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
217 else if (BitWidth <= 64)
218 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
219 else
220 llvm_unreachable("Integer types > 64 bits not supported");
221 return rv;
222 }
223 case Type::VoidTyID:
224 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
225 return rv;
226 case Type::FloatTyID:
227 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
228 return rv;
229 case Type::DoubleTyID:
230 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
231 return rv;
232 case Type::X86_FP80TyID:
233 case Type::FP128TyID:
234 case Type::PPC_FP128TyID:
235 llvm_unreachable("long double not supported yet");
Jim Grosbach34714a02011-03-22 18:05:27 +0000236 case Type::PointerTyID:
237 return PTOGV(((void*(*)())(intptr_t)FPtr)());
238 }
239 }
240
Craig Topper85814382012-02-07 05:05:23 +0000241 llvm_unreachable("Full-featured argument passing not supported yet!");
Daniel Dunbar6aec2982010-11-17 16:06:43 +0000242}
Danil Malyshev30b9e322012-03-28 21:46:36 +0000243
244void *MCJIT::getPointerToNamedFunction(const std::string &Name,
Eli Bendersky5fe01982012-04-29 12:40:47 +0000245 bool AbortOnFailure) {
Andrew Kaylorea708d12012-08-07 18:33:00 +0000246 // FIXME: Add support for per-module compilation state
247 if (!isCompiled)
248 emitObject(M);
249
Danil Malyshev30b9e322012-03-28 21:46:36 +0000250 if (!isSymbolSearchingDisabled() && MemMgr) {
251 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
252 if (ptr)
253 return ptr;
254 }
255
256 /// If a LazyFunctionCreator is installed, use it to get/create the function.
257 if (LazyFunctionCreator)
258 if (void *RP = LazyFunctionCreator(Name))
259 return RP;
260
261 if (AbortOnFailure) {
262 report_fatal_error("Program used external function '"+Name+
Eli Bendersky5fe01982012-04-29 12:40:47 +0000263 "' which could not be resolved!");
Danil Malyshev30b9e322012-03-28 21:46:36 +0000264 }
265 return 0;
266}