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 return new MCJIT(M, TM, new MCJITMemoryManager(JMM), GVsWithCode);
50 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
51 bool AllocateGVsWithCode)
52 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
53 isCompiled(false), M(m), OS(Buffer) {
55 setTargetData(TM->getTargetData());
63 void 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
70 // Get a thread lock to make sure we aren't trying to compile multiple times
71 MutexGuard locked(lock);
73 // FIXME: Track compilation state on a per-module basis when multiple modules
75 // Re-compilation is not supported
81 PM.add(new TargetData(*TM->getTargetData()));
83 // Turn the machine code intermediate representation into bytes in memory
84 // that may be executed.
85 if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
86 report_fatal_error("Target does not support MC emission!");
90 // 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().
94 // Flush the output buffer so the SmallVector gets its data.
97 // Load the object into the dynamic linker.
98 MemoryBuffer* MB = MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
101 if (Dyld.loadObject(MB))
102 report_fatal_error(Dyld.getErrorString());
104 // Resolve any relocations.
105 Dyld.resolveRelocations();
107 // FIXME: Add support for per-module compilation state
111 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
112 report_fatal_error("not yet implemented");
115 void *MCJIT::getPointerToFunction(Function *F) {
116 // FIXME: Add support for per-module compilation state
120 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
121 bool AbortOnFailure = !F->hasExternalWeakLinkage();
122 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
123 addGlobalMapping(F, Addr);
127 // FIXME: Should the Dyld be retaining module information? Probably not.
128 // FIXME: Should we be using the mangler for this? Probably.
129 StringRef BaseName = F->getName();
130 if (BaseName[0] == '\1')
131 return (void*)Dyld.getSymbolAddress(BaseName.substr(1));
132 return (void*)Dyld.getSymbolAddress((TM->getMCAsmInfo()->getGlobalPrefix()
136 void *MCJIT::recompileAndRelinkFunction(Function *F) {
137 report_fatal_error("not yet implemented");
140 void MCJIT::freeMachineCodeForFunction(Function *F) {
141 report_fatal_error("not yet implemented");
144 GenericValue MCJIT::runFunction(Function *F,
145 const std::vector<GenericValue> &ArgValues) {
146 assert(F && "Function *F was null at entry to run()");
148 void *FPtr = getPointerToFunction(F);
149 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
150 FunctionType *FTy = F->getFunctionType();
151 Type *RetTy = FTy->getReturnType();
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)!");
159 // Handle some common cases first. These cases correspond to common `main'
161 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
162 switch (ArgValues.size()) {
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;
170 // Call the function.
172 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
173 (char **)GVTOP(ArgValues[1]),
174 (const char **)GVTOP(ArgValues[2])));
179 if (FTy->getParamType(0)->isIntegerTy(32) &&
180 FTy->getParamType(1)->isPointerTy()) {
181 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
183 // Call the function.
185 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
186 (char **)GVTOP(ArgValues[1])));
191 if (FTy->getNumParams() == 1 &&
192 FTy->getParamType(0)->isIntegerTy(32)) {
194 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
195 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
202 // Handle cases where no arguments are passed first.
203 if (ArgValues.empty()) {
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();
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)());
220 llvm_unreachable("Integer types > 64 bits not supported");
224 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
226 case Type::FloatTyID:
227 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
229 case Type::DoubleTyID:
230 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
232 case Type::X86_FP80TyID:
233 case Type::FP128TyID:
234 case Type::PPC_FP128TyID:
235 llvm_unreachable("long double not supported yet");
236 case Type::PointerTyID:
237 return PTOGV(((void*(*)())(intptr_t)FPtr)());
241 llvm_unreachable("Full-featured argument passing not supported yet!");
244 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
245 bool AbortOnFailure) {
246 // FIXME: Add support for per-module compilation state
250 if (!isSymbolSearchingDisabled() && MemMgr) {
251 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
256 /// If a LazyFunctionCreator is installed, use it to get/create the function.
257 if (LazyFunctionCreator)
258 if (void *RP = LazyFunctionCreator(Name))
261 if (AbortOnFailure) {
262 report_fatal_error("Program used external function '"+Name+
263 "' which could not be resolved!");