MCJIT.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
2//
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"
11#include "llvm/ExecutionEngine/GenericValue.h"
12#include "llvm/ExecutionEngine/JITEventListener.h"
13#include "llvm/ExecutionEngine/JITMemoryManager.h"
14#include "llvm/ExecutionEngine/MCJIT.h"
15#include "llvm/ExecutionEngine/ObjectBuffer.h"
16#include "llvm/ExecutionEngine/ObjectImage.h"
17#include "llvm/ExecutionEngine/SectionMemoryManager.h"
18#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Mangler.h"
22#include "llvm/IR/Module.h"
23#include "llvm/MC/MCAsmInfo.h"
24#include "llvm/Object/Archive.h"
25#include "llvm/PassManager.h"
26#include "llvm/Support/DynamicLibrary.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/MutexGuard.h"
30#include "llvm/Target/TargetLowering.h"
31
32using namespace llvm;
33
34namespace {
35
36static struct RegisterJIT {
37  RegisterJIT() { MCJIT::Register(); }
38} JITRegistrator;
39
40}
41
42extern "C" void LLVMLinkInMCJIT() {
43}
44
45ExecutionEngine *MCJIT::createJIT(Module *M,
46                                  std::string *ErrorStr,
47                                  RTDyldMemoryManager *MemMgr,
48                                  bool GVsWithCode,
49                                  TargetMachine *TM) {
50  // Try to register the program as a source of symbols to resolve against.
51  //
52  // FIXME: Don't do this here.
53  sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
54
55  return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
56                   GVsWithCode);
57}
58
59MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
60             bool AllocateGVsWithCode)
61  : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
62    ObjCache(nullptr) {
63
64  OwnedModules.addModule(m);
65  setDataLayout(TM->getDataLayout());
66}
67
68MCJIT::~MCJIT() {
69  MutexGuard locked(lock);
70  // FIXME: We are managing our modules, so we do not want the base class
71  // ExecutionEngine to manage them as well. To avoid double destruction
72  // of the first (and only) module added in ExecutionEngine constructor
73  // we remove it from EE and will destruct it ourselves.
74  //
75  // It may make sense to move our module manager (based on SmallStPtr) back
76  // into EE if the JIT and Interpreter can live with it.
77  // If so, additional functions: addModule, removeModule, FindFunctionNamed,
78  // runStaticConstructorsDestructors could be moved back to EE as well.
79  //
80  Modules.clear();
81  Dyld.deregisterEHFrames();
82
83  LoadedObjectList::iterator it, end;
84  for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
85    ObjectImage *Obj = *it;
86    if (Obj) {
87      NotifyFreeingObject(*Obj);
88      delete Obj;
89    }
90  }
91  LoadedObjects.clear();
92
93
94  SmallVector<object::Archive *, 2>::iterator ArIt, ArEnd;
95  for (ArIt = Archives.begin(), ArEnd = Archives.end(); ArIt != ArEnd; ++ArIt) {
96    object::Archive *A = *ArIt;
97    delete A;
98  }
99  Archives.clear();
100
101  delete TM;
102}
103
104void MCJIT::addModule(Module *M) {
105  MutexGuard locked(lock);
106  OwnedModules.addModule(M);
107}
108
109bool MCJIT::removeModule(Module *M) {
110  MutexGuard locked(lock);
111  return OwnedModules.removeModule(M);
112}
113
114
115
116void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
117  ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
118  if (!LoadedObject || Dyld.hasError())
119    report_fatal_error(Dyld.getErrorString());
120
121  LoadedObjects.push_back(LoadedObject);
122
123  NotifyObjectEmitted(*LoadedObject);
124}
125
126void MCJIT::addArchive(object::Archive *A) {
127  Archives.push_back(A);
128}
129
130
131void MCJIT::setObjectCache(ObjectCache* NewCache) {
132  MutexGuard locked(lock);
133  ObjCache = NewCache;
134}
135
136ObjectBufferStream* MCJIT::emitObject(Module *M) {
137  MutexGuard locked(lock);
138
139  // This must be a module which has already been added but not loaded to this
140  // MCJIT instance, since these conditions are tested by our caller,
141  // generateCodeForModule.
142
143  PassManager PM;
144
145  M->setDataLayout(TM->getDataLayout());
146  PM.add(new DataLayoutPass(M));
147
148  // The RuntimeDyld will take ownership of this shortly
149  std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
150
151  // Turn the machine code intermediate representation into bytes in memory
152  // that may be executed.
153  if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
154                            !getVerifyModules())) {
155    report_fatal_error("Target does not support MC emission!");
156  }
157
158  // Initialize passes.
159  PM.run(*M);
160  // Flush the output buffer to get the generated code into memory
161  CompiledObject->flush();
162
163  // If we have an object cache, tell it about the new object.
164  // Note that we're using the compiled image, not the loaded image (as below).
165  if (ObjCache) {
166    // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
167    // to create a temporary object here and delete it after the call.
168    std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
169    ObjCache->notifyObjectCompiled(M, MB.get());
170  }
171
172  return CompiledObject.release();
173}
174
175void MCJIT::generateCodeForModule(Module *M) {
176  // Get a thread lock to make sure we aren't trying to load multiple times
177  MutexGuard locked(lock);
178
179  // This must be a module which has already been added to this MCJIT instance.
180  assert(OwnedModules.ownsModule(M) &&
181         "MCJIT::generateCodeForModule: Unknown module.");
182
183  // Re-compilation is not supported
184  if (OwnedModules.hasModuleBeenLoaded(M))
185    return;
186
187  std::unique_ptr<ObjectBuffer> ObjectToLoad;
188  // Try to load the pre-compiled object from cache if possible
189  if (ObjCache) {
190    std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
191    if (PreCompiledObject.get())
192      ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
193  }
194
195  // If the cache did not contain a suitable object, compile the object
196  if (!ObjectToLoad) {
197    ObjectToLoad.reset(emitObject(M));
198    assert(ObjectToLoad.get() && "Compilation did not produce an object.");
199  }
200
201  // Load the object into the dynamic linker.
202  // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
203  ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
204  LoadedObjects.push_back(LoadedObject);
205  if (!LoadedObject)
206    report_fatal_error(Dyld.getErrorString());
207
208  // FIXME: Make this optional, maybe even move it to a JIT event listener
209  LoadedObject->registerWithDebugger();
210
211  NotifyObjectEmitted(*LoadedObject);
212
213  OwnedModules.markModuleAsLoaded(M);
214}
215
216void MCJIT::finalizeLoadedModules() {
217  MutexGuard locked(lock);
218
219  // Resolve any outstanding relocations.
220  Dyld.resolveRelocations();
221
222  OwnedModules.markAllLoadedModulesAsFinalized();
223
224  // Register EH frame data for any module we own which has been loaded
225  Dyld.registerEHFrames();
226
227  // Set page permissions.
228  MemMgr.finalizeMemory();
229}
230
231// FIXME: Rename this.
232void MCJIT::finalizeObject() {
233  MutexGuard locked(lock);
234
235  for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
236                              E = OwnedModules.end_added();
237       I != E; ++I) {
238    Module *M = *I;
239    generateCodeForModule(M);
240  }
241
242  finalizeLoadedModules();
243}
244
245void MCJIT::finalizeModule(Module *M) {
246  MutexGuard locked(lock);
247
248  // This must be a module which has already been added to this MCJIT instance.
249  assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
250
251  // If the module hasn't been compiled, just do that.
252  if (!OwnedModules.hasModuleBeenLoaded(M))
253    generateCodeForModule(M);
254
255  finalizeLoadedModules();
256}
257
258void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
259  report_fatal_error("not yet implemented");
260}
261
262uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
263  Mangler Mang(TM->getDataLayout());
264  SmallString<128> FullName;
265  Mang.getNameWithPrefix(FullName, Name);
266  return Dyld.getSymbolLoadAddress(FullName);
267}
268
269Module *MCJIT::findModuleForSymbol(const std::string &Name,
270                                   bool CheckFunctionsOnly) {
271  MutexGuard locked(lock);
272
273  // If it hasn't already been generated, see if it's in one of our modules.
274  for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
275                              E = OwnedModules.end_added();
276       I != E; ++I) {
277    Module *M = *I;
278    Function *F = M->getFunction(Name);
279    if (F && !F->isDeclaration())
280      return M;
281    if (!CheckFunctionsOnly) {
282      GlobalVariable *G = M->getGlobalVariable(Name);
283      if (G && !G->isDeclaration())
284        return M;
285      // FIXME: Do we need to worry about global aliases?
286    }
287  }
288  // We didn't find the symbol in any of our modules.
289  return nullptr;
290}
291
292uint64_t MCJIT::getSymbolAddress(const std::string &Name,
293                                 bool CheckFunctionsOnly)
294{
295  MutexGuard locked(lock);
296
297  // First, check to see if we already have this symbol.
298  uint64_t Addr = getExistingSymbolAddress(Name);
299  if (Addr)
300    return Addr;
301
302  SmallVector<object::Archive*, 2>::iterator I, E;
303  for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
304    object::Archive *A = *I;
305    // Look for our symbols in each Archive
306    object::Archive::child_iterator ChildIt = A->findSym(Name);
307    if (ChildIt != A->child_end()) {
308      std::unique_ptr<object::Binary> ChildBin;
309      // FIXME: Support nested archives?
310      if (!ChildIt->getAsBinary(ChildBin) && ChildBin->isObject()) {
311        std::unique_ptr<object::ObjectFile> OF(
312            static_cast<object::ObjectFile *>(ChildBin.release()));
313        // This causes the object file to be loaded.
314        addObjectFile(std::move(OF));
315        // The address should be here now.
316        Addr = getExistingSymbolAddress(Name);
317        if (Addr)
318          return Addr;
319      }
320    }
321  }
322
323  // If it hasn't already been generated, see if it's in one of our modules.
324  Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
325  if (!M)
326    return 0;
327
328  generateCodeForModule(M);
329
330  // Check the RuntimeDyld table again, it should be there now.
331  return getExistingSymbolAddress(Name);
332}
333
334uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
335  MutexGuard locked(lock);
336  uint64_t Result = getSymbolAddress(Name, false);
337  if (Result != 0)
338    finalizeLoadedModules();
339  return Result;
340}
341
342uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
343  MutexGuard locked(lock);
344  uint64_t Result = getSymbolAddress(Name, true);
345  if (Result != 0)
346    finalizeLoadedModules();
347  return Result;
348}
349
350// Deprecated.  Use getFunctionAddress instead.
351void *MCJIT::getPointerToFunction(Function *F) {
352  MutexGuard locked(lock);
353
354  if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
355    bool AbortOnFailure = !F->hasExternalWeakLinkage();
356    void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
357    addGlobalMapping(F, Addr);
358    return Addr;
359  }
360
361  Module *M = F->getParent();
362  bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
363
364  // Make sure the relevant module has been compiled and loaded.
365  if (HasBeenAddedButNotLoaded)
366    generateCodeForModule(M);
367  else if (!OwnedModules.hasModuleBeenLoaded(M))
368    // If this function doesn't belong to one of our modules, we're done.
369    return nullptr;
370
371  // FIXME: Should the Dyld be retaining module information? Probably not.
372  //
373  // This is the accessor for the target address, so make sure to check the
374  // load address of the symbol, not the local address.
375  Mangler Mang(TM->getDataLayout());
376  SmallString<128> Name;
377  TM->getNameWithPrefix(Name, F, Mang);
378  return (void*)Dyld.getSymbolLoadAddress(Name);
379}
380
381void *MCJIT::recompileAndRelinkFunction(Function *F) {
382  report_fatal_error("not yet implemented");
383}
384
385void MCJIT::freeMachineCodeForFunction(Function *F) {
386  report_fatal_error("not yet implemented");
387}
388
389void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
390    bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
391  for (; I != E; ++I) {
392    ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
393  }
394}
395
396void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
397  // Execute global ctors/dtors for each module in the program.
398  runStaticConstructorsDestructorsInModulePtrSet(
399      isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
400  runStaticConstructorsDestructorsInModulePtrSet(
401      isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
402  runStaticConstructorsDestructorsInModulePtrSet(
403      isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
404}
405
406Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
407                                                 ModulePtrSet::iterator I,
408                                                 ModulePtrSet::iterator E) {
409  for (; I != E; ++I) {
410    if (Function *F = (*I)->getFunction(FnName))
411      return F;
412  }
413  return nullptr;
414}
415
416Function *MCJIT::FindFunctionNamed(const char *FnName) {
417  Function *F = FindFunctionNamedInModulePtrSet(
418      FnName, OwnedModules.begin_added(), OwnedModules.end_added());
419  if (!F)
420    F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
421                                        OwnedModules.end_loaded());
422  if (!F)
423    F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
424                                        OwnedModules.end_finalized());
425  return F;
426}
427
428GenericValue MCJIT::runFunction(Function *F,
429                                const std::vector<GenericValue> &ArgValues) {
430  assert(F && "Function *F was null at entry to run()");
431
432  void *FPtr = getPointerToFunction(F);
433  assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
434  FunctionType *FTy = F->getFunctionType();
435  Type *RetTy = FTy->getReturnType();
436
437  assert((FTy->getNumParams() == ArgValues.size() ||
438          (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
439         "Wrong number of arguments passed into function!");
440  assert(FTy->getNumParams() == ArgValues.size() &&
441         "This doesn't support passing arguments through varargs (yet)!");
442
443  // Handle some common cases first.  These cases correspond to common `main'
444  // prototypes.
445  if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
446    switch (ArgValues.size()) {
447    case 3:
448      if (FTy->getParamType(0)->isIntegerTy(32) &&
449          FTy->getParamType(1)->isPointerTy() &&
450          FTy->getParamType(2)->isPointerTy()) {
451        int (*PF)(int, char **, const char **) =
452          (int(*)(int, char **, const char **))(intptr_t)FPtr;
453
454        // Call the function.
455        GenericValue rv;
456        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
457                                 (char **)GVTOP(ArgValues[1]),
458                                 (const char **)GVTOP(ArgValues[2])));
459        return rv;
460      }
461      break;
462    case 2:
463      if (FTy->getParamType(0)->isIntegerTy(32) &&
464          FTy->getParamType(1)->isPointerTy()) {
465        int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
466
467        // Call the function.
468        GenericValue rv;
469        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
470                                 (char **)GVTOP(ArgValues[1])));
471        return rv;
472      }
473      break;
474    case 1:
475      if (FTy->getNumParams() == 1 &&
476          FTy->getParamType(0)->isIntegerTy(32)) {
477        GenericValue rv;
478        int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
479        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
480        return rv;
481      }
482      break;
483    }
484  }
485
486  // Handle cases where no arguments are passed first.
487  if (ArgValues.empty()) {
488    GenericValue rv;
489    switch (RetTy->getTypeID()) {
490    default: llvm_unreachable("Unknown return type for function call!");
491    case Type::IntegerTyID: {
492      unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
493      if (BitWidth == 1)
494        rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
495      else if (BitWidth <= 8)
496        rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
497      else if (BitWidth <= 16)
498        rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
499      else if (BitWidth <= 32)
500        rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
501      else if (BitWidth <= 64)
502        rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
503      else
504        llvm_unreachable("Integer types > 64 bits not supported");
505      return rv;
506    }
507    case Type::VoidTyID:
508      rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
509      return rv;
510    case Type::FloatTyID:
511      rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
512      return rv;
513    case Type::DoubleTyID:
514      rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
515      return rv;
516    case Type::X86_FP80TyID:
517    case Type::FP128TyID:
518    case Type::PPC_FP128TyID:
519      llvm_unreachable("long double not supported yet");
520    case Type::PointerTyID:
521      return PTOGV(((void*(*)())(intptr_t)FPtr)());
522    }
523  }
524
525  llvm_unreachable("Full-featured argument passing not supported yet!");
526}
527
528void *MCJIT::getPointerToNamedFunction(const std::string &Name,
529                                       bool AbortOnFailure) {
530  if (!isSymbolSearchingDisabled()) {
531    void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
532    if (ptr)
533      return ptr;
534  }
535
536  /// If a LazyFunctionCreator is installed, use it to get/create the function.
537  if (LazyFunctionCreator)
538    if (void *RP = LazyFunctionCreator(Name))
539      return RP;
540
541  if (AbortOnFailure) {
542    report_fatal_error("Program used external function '"+Name+
543                       "' which could not be resolved!");
544  }
545  return nullptr;
546}
547
548void MCJIT::RegisterJITEventListener(JITEventListener *L) {
549  if (!L)
550    return;
551  MutexGuard locked(lock);
552  EventListeners.push_back(L);
553}
554void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
555  if (!L)
556    return;
557  MutexGuard locked(lock);
558  SmallVector<JITEventListener*, 2>::reverse_iterator I=
559      std::find(EventListeners.rbegin(), EventListeners.rend(), L);
560  if (I != EventListeners.rend()) {
561    std::swap(*I, EventListeners.back());
562    EventListeners.pop_back();
563  }
564}
565void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
566  MutexGuard locked(lock);
567  MemMgr.notifyObjectLoaded(this, &Obj);
568  for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
569    EventListeners[I]->NotifyObjectEmitted(Obj);
570  }
571}
572void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
573  MutexGuard locked(lock);
574  for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
575    EventListeners[I]->NotifyFreeingObject(Obj);
576  }
577}
578
579uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
580  uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
581  // If the symbols wasn't found and it begins with an underscore, try again
582  // without the underscore.
583  if (!Result && Name[0] == '_')
584    Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
585  if (Result)
586    return Result;
587  return ClientMM->getSymbolAddress(Name);
588}
589