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 "llvm/DerivedTypes.h"
12 #include "llvm/Function.h"
13 #include "llvm/ExecutionEngine/GenericValue.h"
14 #include "llvm/ExecutionEngine/JITMemoryManager.h"
15 #include "llvm/ExecutionEngine/MCJIT.h"
16 #include "llvm/ExecutionEngine/ObjectBuffer.h"
17 #include "llvm/ExecutionEngine/ObjectImage.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/DynamicLibrary.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/MutexGuard.h"
23 #include "llvm/DataLayout.h"
29 static struct RegisterJIT {
30 RegisterJIT() { MCJIT::Register(); }
35 extern "C" void LLVMLinkInMCJIT() {
38 ExecutionEngine *MCJIT::createJIT(Module *M,
39 std::string *ErrorStr,
40 JITMemoryManager *JMM,
43 // Try to register the program as a source of symbols to resolve against.
45 // FIXME: Don't do this here.
46 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
48 return new MCJIT(M, TM, JMM, GVsWithCode);
51 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
52 bool AllocateGVsWithCode)
53 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
54 isCompiled(false), M(m) {
56 setDataLayout(TM->getDataLayout());
64 void 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
67 /// is passed as a parameter here to prepare for multiple module support in
71 // Get a thread lock to make sure we aren't trying to compile multiple times
72 MutexGuard locked(lock);
74 // FIXME: Track compilation state on a per-module basis when multiple modules
76 // Re-compilation is not supported
82 PM.add(new DataLayout(*TM->getDataLayout()));
84 // The RuntimeDyld will take ownership of this shortly
85 OwningPtr<ObjectBufferStream> Buffer(new ObjectBufferStream());
87 // Turn the machine code intermediate representation into bytes in memory
88 // that may be executed.
89 if (TM->addPassesToEmitMC(PM, Ctx, Buffer->getOStream(), false)) {
90 report_fatal_error("Target does not support MC emission!");
95 // Flush the output buffer to get the generated code into memory
98 // Load the object into the dynamic linker.
99 // handing off ownership of the buffer
100 LoadedObject.reset(Dyld.loadObject(Buffer.take()));
102 report_fatal_error(Dyld.getErrorString());
104 // Resolve any relocations.
105 Dyld.resolveRelocations();
107 // FIXME: Make this optional, maybe even move it to a JIT event listener
108 LoadedObject->registerWithDebugger();
110 // FIXME: Add support for per-module compilation state
114 // FIXME: Add a parameter to identify which object is being finalized when
115 // MCJIT supports multiple modules.
116 void MCJIT::finalizeObject() {
117 // If the module hasn't been compiled, just do that.
119 // If the call to Dyld.resolveRelocations() is removed from emitObject()
120 // we'll need to do that here.
125 // Resolve any relocations.
126 Dyld.resolveRelocations();
129 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
130 report_fatal_error("not yet implemented");
133 void *MCJIT::getPointerToFunction(Function *F) {
134 // 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
139 // FIXME: Add support for per-module compilation state
143 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
144 bool AbortOnFailure = !F->hasExternalWeakLinkage();
145 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
146 addGlobalMapping(F, Addr);
150 // FIXME: Should the Dyld be retaining module information? Probably not.
151 // FIXME: Should we be using the mangler for this? Probably.
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.
155 StringRef BaseName = F->getName();
156 if (BaseName[0] == '\1')
157 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
158 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
162 void *MCJIT::recompileAndRelinkFunction(Function *F) {
163 report_fatal_error("not yet implemented");
166 void MCJIT::freeMachineCodeForFunction(Function *F) {
167 report_fatal_error("not yet implemented");
170 GenericValue MCJIT::runFunction(Function *F,
171 const std::vector<GenericValue> &ArgValues) {
172 assert(F && "Function *F was null at entry to run()");
174 void *FPtr = getPointerToFunction(F);
175 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
176 FunctionType *FTy = F->getFunctionType();
177 Type *RetTy = FTy->getReturnType();
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)!");
185 // Handle some common cases first. These cases correspond to common `main'
187 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
188 switch (ArgValues.size()) {
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;
196 // Call the function.
198 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
199 (char **)GVTOP(ArgValues[1]),
200 (const char **)GVTOP(ArgValues[2])));
205 if (FTy->getParamType(0)->isIntegerTy(32) &&
206 FTy->getParamType(1)->isPointerTy()) {
207 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
209 // Call the function.
211 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
212 (char **)GVTOP(ArgValues[1])));
217 if (FTy->getNumParams() == 1 &&
218 FTy->getParamType(0)->isIntegerTy(32)) {
220 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
221 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
228 // Handle cases where no arguments are passed first.
229 if (ArgValues.empty()) {
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();
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)());
246 llvm_unreachable("Integer types > 64 bits not supported");
250 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
252 case Type::FloatTyID:
253 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
255 case Type::DoubleTyID:
256 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
258 case Type::X86_FP80TyID:
259 case Type::FP128TyID:
260 case Type::PPC_FP128TyID:
261 llvm_unreachable("long double not supported yet");
262 case Type::PointerTyID:
263 return PTOGV(((void*(*)())(intptr_t)FPtr)());
267 llvm_unreachable("Full-featured argument passing not supported yet!");
270 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
271 bool AbortOnFailure) {
272 // FIXME: Add support for per-module compilation state
276 if (!isSymbolSearchingDisabled() && MemMgr) {
277 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
282 /// If a LazyFunctionCreator is installed, use it to get/create the function.
283 if (LazyFunctionCreator)
284 if (void *RP = LazyFunctionCreator(Name))
287 if (AbortOnFailure) {
288 report_fatal_error("Program used external function '"+Name+
289 "' which could not be resolved!");