1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "MCJITMemoryManager.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Function.h"
14 #include "llvm/ExecutionEngine/GenericValue.h"
15 #include "llvm/ExecutionEngine/MCJIT.h"
16 #include "llvm/ExecutionEngine/JITMemoryManager.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/DynamicLibrary.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/MutexGuard.h"
22 #include "llvm/Target/TargetData.h"
28 static struct RegisterJIT {
29 RegisterJIT() { MCJIT::Register(); }
34 extern "C" void LLVMLinkInMCJIT() {
37 ExecutionEngine *MCJIT::createJIT(Module *M,
38 std::string *ErrorStr,
39 JITMemoryManager *JMM,
42 // Try to register the program as a source of symbols to resolve against.
44 // FIXME: Don't do this here.
45 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
47 // If the target supports JIT code generation, create the JIT.
48 if (TargetJITInfo *TJ = TM->getJITInfo())
49 return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM), GVsWithCode);
52 *ErrorStr = "target does not support JIT code generation";
56 MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
57 RTDyldMemoryManager *MM, bool AllocateGVsWithCode)
58 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
59 isCompiled(false), M(m), OS(Buffer) {
61 setTargetData(TM->getTargetData());
69 void 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
76 // Get a thread lock to make sure we aren't trying to compile multiple times
77 MutexGuard locked(lock);
79 // FIXME: Track compilation state on a per-module basis when multiple modules
81 // Re-compilation is not supported
87 PM.add(new TargetData(*TM->getTargetData()));
89 // Turn the machine code intermediate representation into bytes in memory
90 // that may be executed.
91 if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
92 report_fatal_error("Target does not support MC emission!");
96 // 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().
100 // Flush the output buffer so the SmallVector gets its data.
103 // Load the object into the dynamic linker.
104 MemoryBuffer* MB = MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
107 if (Dyld.loadObject(MB))
108 report_fatal_error(Dyld.getErrorString());
110 // Resolve any relocations.
111 Dyld.resolveRelocations();
113 // FIXME: Add support for per-module compilation state
117 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
118 report_fatal_error("not yet implemented");
121 void *MCJIT::getPointerToFunction(Function *F) {
122 // FIXME: Add support for per-module compilation state
126 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
127 bool AbortOnFailure = !F->hasExternalWeakLinkage();
128 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
129 addGlobalMapping(F, Addr);
133 // FIXME: Should the Dyld be retaining module information? Probably not.
134 // FIXME: Should we be using the mangler for this? Probably.
135 StringRef BaseName = F->getName();
136 if (BaseName[0] == '\1')
137 return (void*)Dyld.getSymbolAddress(BaseName.substr(1));
138 return (void*)Dyld.getSymbolAddress((TM->getMCAsmInfo()->getGlobalPrefix()
142 void *MCJIT::recompileAndRelinkFunction(Function *F) {
143 report_fatal_error("not yet implemented");
146 void MCJIT::freeMachineCodeForFunction(Function *F) {
147 report_fatal_error("not yet implemented");
150 GenericValue MCJIT::runFunction(Function *F,
151 const std::vector<GenericValue> &ArgValues) {
152 assert(F && "Function *F was null at entry to run()");
154 void *FPtr = getPointerToFunction(F);
155 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
156 FunctionType *FTy = F->getFunctionType();
157 Type *RetTy = FTy->getReturnType();
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)!");
165 // Handle some common cases first. These cases correspond to common `main'
167 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
168 switch (ArgValues.size()) {
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;
176 // Call the function.
178 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
179 (char **)GVTOP(ArgValues[1]),
180 (const char **)GVTOP(ArgValues[2])));
185 if (FTy->getParamType(0)->isIntegerTy(32) &&
186 FTy->getParamType(1)->isPointerTy()) {
187 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
189 // Call the function.
191 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
192 (char **)GVTOP(ArgValues[1])));
197 if (FTy->getNumParams() == 1 &&
198 FTy->getParamType(0)->isIntegerTy(32)) {
200 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
201 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
208 // Handle cases where no arguments are passed first.
209 if (ArgValues.empty()) {
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();
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)());
226 llvm_unreachable("Integer types > 64 bits not supported");
230 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
232 case Type::FloatTyID:
233 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
235 case Type::DoubleTyID:
236 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
238 case Type::X86_FP80TyID:
239 case Type::FP128TyID:
240 case Type::PPC_FP128TyID:
241 llvm_unreachable("long double not supported yet");
242 case Type::PointerTyID:
243 return PTOGV(((void*(*)())(intptr_t)FPtr)());
247 llvm_unreachable("Full-featured argument passing not supported yet!");
250 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
251 bool AbortOnFailure) {
252 // FIXME: Add support for per-module compilation state
256 if (!isSymbolSearchingDisabled() && MemMgr) {
257 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
262 /// If a LazyFunctionCreator is installed, use it to get/create the function.
263 if (LazyFunctionCreator)
264 if (void *RP = LazyFunctionCreator(Name))
267 if (AbortOnFailure) {
268 report_fatal_error("Program used external function '"+Name+
269 "' which could not be resolved!");