JIT.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. //===-- JIT.cpp - LLVM 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. // This tool implements a just-in-time compiler for LLVM, allowing direct
  11. // execution of LLVM bitcode in an efficient manner.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "JIT.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Function.h"
  18. #include "llvm/GlobalVariable.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/ModuleProvider.h"
  21. #include "llvm/CodeGen/JITCodeEmitter.h"
  22. #include "llvm/CodeGen/MachineCodeInfo.h"
  23. #include "llvm/ExecutionEngine/GenericValue.h"
  24. #include "llvm/ExecutionEngine/JITEventListener.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/Target/TargetMachine.h"
  27. #include "llvm/Target/TargetJITInfo.h"
  28. #include "llvm/Support/Dwarf.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/MutexGuard.h"
  31. #include "llvm/System/DynamicLibrary.h"
  32. #include "llvm/Config/config.h"
  33. using namespace llvm;
  34. #ifdef __APPLE__
  35. // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
  36. // of atexit). It passes the address of linker generated symbol __dso_handle
  37. // to the function.
  38. // This configuration change happened at version 5330.
  39. # include <AvailabilityMacros.h>
  40. # if defined(MAC_OS_X_VERSION_10_4) && \
  41. ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
  42. (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
  43. __APPLE_CC__ >= 5330))
  44. # ifndef HAVE___DSO_HANDLE
  45. # define HAVE___DSO_HANDLE 1
  46. # endif
  47. # endif
  48. #endif
  49. #if HAVE___DSO_HANDLE
  50. extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
  51. #endif
  52. namespace {
  53. static struct RegisterJIT {
  54. RegisterJIT() { JIT::Register(); }
  55. } JITRegistrator;
  56. }
  57. extern "C" void LLVMLinkInJIT() {
  58. }
  59. #if defined(__GNUC__) && !defined(__ARM__EABI__)
  60. // libgcc defines the __register_frame function to dynamically register new
  61. // dwarf frames for exception handling. This functionality is not portable
  62. // across compilers and is only provided by GCC. We use the __register_frame
  63. // function here so that code generated by the JIT cooperates with the unwinding
  64. // runtime of libgcc. When JITting with exception handling enable, LLVM
  65. // generates dwarf frames and registers it to libgcc with __register_frame.
  66. //
  67. // The __register_frame function works with Linux.
  68. //
  69. // Unfortunately, this functionality seems to be in libgcc after the unwinding
  70. // library of libgcc for darwin was written. The code for darwin overwrites the
  71. // value updated by __register_frame with a value fetched with "keymgr".
  72. // "keymgr" is an obsolete functionality, which should be rewritten some day.
  73. // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
  74. // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
  75. // values of an opaque key, used by libgcc to find dwarf tables.
  76. extern "C" void __register_frame(void*);
  77. #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
  78. # define USE_KEYMGR 1
  79. #else
  80. # define USE_KEYMGR 0
  81. #endif
  82. #if USE_KEYMGR
  83. namespace {
  84. // LibgccObject - This is the structure defined in libgcc. There is no #include
  85. // provided for this structure, so we also define it here. libgcc calls it
  86. // "struct object". The structure is undocumented in libgcc.
  87. struct LibgccObject {
  88. void *unused1;
  89. void *unused2;
  90. void *unused3;
  91. /// frame - Pointer to the exception table.
  92. void *frame;
  93. /// encoding - The encoding of the object?
  94. union {
  95. struct {
  96. unsigned long sorted : 1;
  97. unsigned long from_array : 1;
  98. unsigned long mixed_encoding : 1;
  99. unsigned long encoding : 8;
  100. unsigned long count : 21;
  101. } b;
  102. size_t i;
  103. } encoding;
  104. /// fde_end - libgcc defines this field only if some macro is defined. We
  105. /// include this field even if it may not there, to make libgcc happy.
  106. char *fde_end;
  107. /// next - At least we know it's a chained list!
  108. struct LibgccObject *next;
  109. };
  110. // "kemgr" stuff. Apparently, all frame tables are stored there.
  111. extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
  112. extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
  113. #define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
  114. /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
  115. /// probably contains all dwarf tables that are loaded.
  116. struct LibgccObjectInfo {
  117. /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
  118. ///
  119. struct LibgccObject* seenObjects;
  120. /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
  121. ///
  122. struct LibgccObject* unseenObjects;
  123. unsigned unused[2];
  124. };
  125. /// darwin_register_frame - Since __register_frame does not work with darwin's
  126. /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
  127. /// "Dwarf2 object list" key.
  128. void DarwinRegisterFrame(void* FrameBegin) {
  129. // Get the key.
  130. LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
  131. _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
  132. assert(LOI && "This should be preallocated by the runtime");
  133. // Allocate a new LibgccObject to represent this frame. Deallocation of this
  134. // object may be impossible: since darwin code in libgcc was written after
  135. // the ability to dynamically register frames, things may crash if we
  136. // deallocate it.
  137. struct LibgccObject* ob = (struct LibgccObject*)
  138. malloc(sizeof(struct LibgccObject));
  139. // Do like libgcc for the values of the field.
  140. ob->unused1 = (void *)-1;
  141. ob->unused2 = 0;
  142. ob->unused3 = 0;
  143. ob->frame = FrameBegin;
  144. ob->encoding.i = 0;
  145. ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
  146. // Put the info on both places, as libgcc uses the first or the the second
  147. // field. Note that we rely on having two pointers here. If fde_end was a
  148. // char, things would get complicated.
  149. ob->fde_end = (char*)LOI->unseenObjects;
  150. ob->next = LOI->unseenObjects;
  151. // Update the key's unseenObjects list.
  152. LOI->unseenObjects = ob;
  153. // Finally update the "key". Apparently, libgcc requires it.
  154. _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
  155. LOI);
  156. }
  157. }
  158. #endif // __APPLE__
  159. #endif // __GNUC__
  160. /// createJIT - This is the factory method for creating a JIT for the current
  161. /// machine, it does not fall back to the interpreter. This takes ownership
  162. /// of the module provider.
  163. ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
  164. std::string *ErrorStr,
  165. JITMemoryManager *JMM,
  166. CodeGenOpt::Level OptLevel) {
  167. ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, OptLevel);
  168. if (!EE) return 0;
  169. // Make sure we can resolve symbols in the program as well. The zero arg
  170. // to the function tells DynamicLibrary to load the program, not a library.
  171. sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
  172. return EE;
  173. }
  174. JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
  175. JITMemoryManager *JMM, CodeGenOpt::Level OptLevel)
  176. : ExecutionEngine(MP), TM(tm), TJI(tji) {
  177. setTargetData(TM.getTargetData());
  178. jitstate = new JITState(MP);
  179. // Initialize JCE
  180. JCE = createEmitter(*this, JMM);
  181. // Add target data
  182. MutexGuard locked(lock);
  183. FunctionPassManager &PM = jitstate->getPM(locked);
  184. PM.add(new TargetData(*TM.getTargetData()));
  185. // Turn the machine code intermediate representation into bytes in memory that
  186. // may be executed.
  187. if (TM.addPassesToEmitMachineCode(PM, *JCE, OptLevel)) {
  188. cerr << "Target does not support machine code emission!\n";
  189. abort();
  190. }
  191. // Register routine for informing unwinding runtime about new EH frames
  192. #if defined(__GNUC__) && !defined(__ARM_EABI__)
  193. #if USE_KEYMGR
  194. struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
  195. _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
  196. // The key is created on demand, and libgcc creates it the first time an
  197. // exception occurs. Since we need the key to register frames, we create
  198. // it now.
  199. if (!LOI)
  200. LOI = (LibgccObjectInfo*)calloc(sizeof(struct LibgccObjectInfo), 1);
  201. _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST, LOI);
  202. InstallExceptionTableRegister(DarwinRegisterFrame);
  203. #else
  204. InstallExceptionTableRegister(__register_frame);
  205. #endif // __APPLE__
  206. #endif // __GNUC__
  207. // Initialize passes.
  208. PM.doInitialization();
  209. }
  210. JIT::~JIT() {
  211. delete jitstate;
  212. delete JCE;
  213. delete &TM;
  214. }
  215. /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
  216. /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
  217. /// ModuleProvider.
  218. void JIT::addModuleProvider(ModuleProvider *MP) {
  219. MutexGuard locked(lock);
  220. if (Modules.empty()) {
  221. assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
  222. jitstate = new JITState(MP);
  223. FunctionPassManager &PM = jitstate->getPM(locked);
  224. PM.add(new TargetData(*TM.getTargetData()));
  225. // Turn the machine code intermediate representation into bytes in memory
  226. // that may be executed.
  227. if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
  228. cerr << "Target does not support machine code emission!\n";
  229. abort();
  230. }
  231. // Initialize passes.
  232. PM.doInitialization();
  233. }
  234. ExecutionEngine::addModuleProvider(MP);
  235. }
  236. /// removeModuleProvider - If we are removing the last ModuleProvider,
  237. /// invalidate the jitstate since the PassManager it contains references a
  238. /// released ModuleProvider.
  239. Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
  240. Module *result = ExecutionEngine::removeModuleProvider(MP, E);
  241. MutexGuard locked(lock);
  242. if (jitstate->getMP() == MP) {
  243. delete jitstate;
  244. jitstate = 0;
  245. }
  246. if (!jitstate && !Modules.empty()) {
  247. jitstate = new JITState(Modules[0]);
  248. FunctionPassManager &PM = jitstate->getPM(locked);
  249. PM.add(new TargetData(*TM.getTargetData()));
  250. // Turn the machine code intermediate representation into bytes in memory
  251. // that may be executed.
  252. if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
  253. cerr << "Target does not support machine code emission!\n";
  254. abort();
  255. }
  256. // Initialize passes.
  257. PM.doInitialization();
  258. }
  259. return result;
  260. }
  261. /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
  262. /// and deletes the ModuleProvider and owned Module. Avoids materializing
  263. /// the underlying module.
  264. void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
  265. ExecutionEngine::deleteModuleProvider(MP, E);
  266. MutexGuard locked(lock);
  267. if (jitstate->getMP() == MP) {
  268. delete jitstate;
  269. jitstate = 0;
  270. }
  271. if (!jitstate && !Modules.empty()) {
  272. jitstate = new JITState(Modules[0]);
  273. FunctionPassManager &PM = jitstate->getPM(locked);
  274. PM.add(new TargetData(*TM.getTargetData()));
  275. // Turn the machine code intermediate representation into bytes in memory
  276. // that may be executed.
  277. if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
  278. cerr << "Target does not support machine code emission!\n";
  279. abort();
  280. }
  281. // Initialize passes.
  282. PM.doInitialization();
  283. }
  284. }
  285. /// run - Start execution with the specified function and arguments.
  286. ///
  287. GenericValue JIT::runFunction(Function *F,
  288. const std::vector<GenericValue> &ArgValues) {
  289. assert(F && "Function *F was null at entry to run()");
  290. void *FPtr = getPointerToFunction(F);
  291. assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
  292. const FunctionType *FTy = F->getFunctionType();
  293. const Type *RetTy = FTy->getReturnType();
  294. assert((FTy->getNumParams() == ArgValues.size() ||
  295. (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
  296. "Wrong number of arguments passed into function!");
  297. assert(FTy->getNumParams() == ArgValues.size() &&
  298. "This doesn't support passing arguments through varargs (yet)!");
  299. // Handle some common cases first. These cases correspond to common `main'
  300. // prototypes.
  301. if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
  302. switch (ArgValues.size()) {
  303. case 3:
  304. if (FTy->getParamType(0) == Type::Int32Ty &&
  305. isa<PointerType>(FTy->getParamType(1)) &&
  306. isa<PointerType>(FTy->getParamType(2))) {
  307. int (*PF)(int, char **, const char **) =
  308. (int(*)(int, char **, const char **))(intptr_t)FPtr;
  309. // Call the function.
  310. GenericValue rv;
  311. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  312. (char **)GVTOP(ArgValues[1]),
  313. (const char **)GVTOP(ArgValues[2])));
  314. return rv;
  315. }
  316. break;
  317. case 2:
  318. if (FTy->getParamType(0) == Type::Int32Ty &&
  319. isa<PointerType>(FTy->getParamType(1))) {
  320. int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
  321. // Call the function.
  322. GenericValue rv;
  323. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
  324. (char **)GVTOP(ArgValues[1])));
  325. return rv;
  326. }
  327. break;
  328. case 1:
  329. if (FTy->getNumParams() == 1 &&
  330. FTy->getParamType(0) == Type::Int32Ty) {
  331. GenericValue rv;
  332. int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
  333. rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
  334. return rv;
  335. }
  336. break;
  337. }
  338. }
  339. // Handle cases where no arguments are passed first.
  340. if (ArgValues.empty()) {
  341. GenericValue rv;
  342. switch (RetTy->getTypeID()) {
  343. default: assert(0 && "Unknown return type for function call!");
  344. case Type::IntegerTyID: {
  345. unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
  346. if (BitWidth == 1)
  347. rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
  348. else if (BitWidth <= 8)
  349. rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
  350. else if (BitWidth <= 16)
  351. rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
  352. else if (BitWidth <= 32)
  353. rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
  354. else if (BitWidth <= 64)
  355. rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
  356. else
  357. assert(0 && "Integer types > 64 bits not supported");
  358. return rv;
  359. }
  360. case Type::VoidTyID:
  361. rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
  362. return rv;
  363. case Type::FloatTyID:
  364. rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
  365. return rv;
  366. case Type::DoubleTyID:
  367. rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
  368. return rv;
  369. case Type::X86_FP80TyID:
  370. case Type::FP128TyID:
  371. case Type::PPC_FP128TyID:
  372. assert(0 && "long double not supported yet");
  373. return rv;
  374. case Type::PointerTyID:
  375. return PTOGV(((void*(*)())(intptr_t)FPtr)());
  376. }
  377. }
  378. // Okay, this is not one of our quick and easy cases. Because we don't have a
  379. // full FFI, we have to codegen a nullary stub function that just calls the
  380. // function we are interested in, passing in constants for all of the
  381. // arguments. Make this function and return.
  382. // First, create the function.
  383. FunctionType *STy=FunctionType::get(RetTy, false);
  384. Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
  385. F->getParent());
  386. // Insert a basic block.
  387. BasicBlock *StubBB = BasicBlock::Create("", Stub);
  388. // Convert all of the GenericValue arguments over to constants. Note that we
  389. // currently don't support varargs.
  390. SmallVector<Value*, 8> Args;
  391. for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
  392. Constant *C = 0;
  393. const Type *ArgTy = FTy->getParamType(i);
  394. const GenericValue &AV = ArgValues[i];
  395. switch (ArgTy->getTypeID()) {
  396. default: assert(0 && "Unknown argument type for function call!");
  397. case Type::IntegerTyID:
  398. C = ConstantInt::get(AV.IntVal);
  399. break;
  400. case Type::FloatTyID:
  401. C = ConstantFP::get(APFloat(AV.FloatVal));
  402. break;
  403. case Type::DoubleTyID:
  404. C = ConstantFP::get(APFloat(AV.DoubleVal));
  405. break;
  406. case Type::PPC_FP128TyID:
  407. case Type::X86_FP80TyID:
  408. case Type::FP128TyID:
  409. C = ConstantFP::get(APFloat(AV.IntVal));
  410. break;
  411. case Type::PointerTyID:
  412. void *ArgPtr = GVTOP(AV);
  413. if (sizeof(void*) == 4)
  414. C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
  415. else
  416. C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
  417. C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
  418. break;
  419. }
  420. Args.push_back(C);
  421. }
  422. CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
  423. "", StubBB);
  424. TheCall->setCallingConv(F->getCallingConv());
  425. TheCall->setTailCall();
  426. if (TheCall->getType() != Type::VoidTy)
  427. ReturnInst::Create(TheCall, StubBB); // Return result of the call.
  428. else
  429. ReturnInst::Create(StubBB); // Just return void.
  430. // Finally, return the value returned by our nullary stub function.
  431. return runFunction(Stub, std::vector<GenericValue>());
  432. }
  433. void JIT::RegisterJITEventListener(JITEventListener *L) {
  434. if (L == NULL)
  435. return;
  436. MutexGuard locked(lock);
  437. EventListeners.push_back(L);
  438. }
  439. void JIT::UnregisterJITEventListener(JITEventListener *L) {
  440. if (L == NULL)
  441. return;
  442. MutexGuard locked(lock);
  443. std::vector<JITEventListener*>::reverse_iterator I=
  444. std::find(EventListeners.rbegin(), EventListeners.rend(), L);
  445. if (I != EventListeners.rend()) {
  446. std::swap(*I, EventListeners.back());
  447. EventListeners.pop_back();
  448. }
  449. }
  450. void JIT::NotifyFunctionEmitted(
  451. const Function &F,
  452. void *Code, size_t Size,
  453. const JITEvent_EmittedFunctionDetails &Details) {
  454. MutexGuard locked(lock);
  455. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  456. EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
  457. }
  458. }
  459. void JIT::NotifyFreeingMachineCode(const Function &F, void *OldPtr) {
  460. MutexGuard locked(lock);
  461. for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
  462. EventListeners[I]->NotifyFreeingMachineCode(F, OldPtr);
  463. }
  464. }
  465. /// runJITOnFunction - Run the FunctionPassManager full of
  466. /// just-in-time compilation passes on F, hopefully filling in
  467. /// GlobalAddress[F] with the address of F's machine code.
  468. ///
  469. void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
  470. MutexGuard locked(lock);
  471. class MCIListener : public JITEventListener {
  472. MachineCodeInfo *const MCI;
  473. public:
  474. MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
  475. virtual void NotifyFunctionEmitted(const Function &,
  476. void *Code, size_t Size,
  477. const EmittedFunctionDetails &) {
  478. MCI->setAddress(Code);
  479. MCI->setSize(Size);
  480. }
  481. };
  482. MCIListener MCIL(MCI);
  483. RegisterJITEventListener(&MCIL);
  484. runJITOnFunctionUnlocked(F, locked);
  485. UnregisterJITEventListener(&MCIL);
  486. }
  487. void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
  488. static bool isAlreadyCodeGenerating = false;
  489. assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
  490. // JIT the function
  491. isAlreadyCodeGenerating = true;
  492. jitstate->getPM(locked).run(*F);
  493. isAlreadyCodeGenerating = false;
  494. // If the function referred to another function that had not yet been
  495. // read from bitcode, but we are jitting non-lazily, emit it now.
  496. while (!jitstate->getPendingFunctions(locked).empty()) {
  497. Function *PF = jitstate->getPendingFunctions(locked).back();
  498. jitstate->getPendingFunctions(locked).pop_back();
  499. // JIT the function
  500. isAlreadyCodeGenerating = true;
  501. jitstate->getPM(locked).run(*PF);
  502. isAlreadyCodeGenerating = false;
  503. // Now that the function has been jitted, ask the JITEmitter to rewrite
  504. // the stub with real address of the function.
  505. updateFunctionStub(PF);
  506. }
  507. // If the JIT is configured to emit info so that dlsym can be used to
  508. // rewrite stubs to external globals, do so now.
  509. if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
  510. updateDlsymStubTable();
  511. }
  512. /// getPointerToFunction - This method is used to get the address of the
  513. /// specified function, compiling it if neccesary.
  514. ///
  515. void *JIT::getPointerToFunction(Function *F) {
  516. if (void *Addr = getPointerToGlobalIfAvailable(F))
  517. return Addr; // Check if function already code gen'd
  518. MutexGuard locked(lock);
  519. // Now that this thread owns the lock, check if another thread has already
  520. // code gen'd the function.
  521. if (void *Addr = getPointerToGlobalIfAvailable(F))
  522. return Addr;
  523. // Make sure we read in the function if it exists in this Module.
  524. if (F->hasNotBeenReadFromBitcode()) {
  525. // Determine the module provider this function is provided by.
  526. Module *M = F->getParent();
  527. ModuleProvider *MP = 0;
  528. for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
  529. if (Modules[i]->getModule() == M) {
  530. MP = Modules[i];
  531. break;
  532. }
  533. }
  534. assert(MP && "Function isn't in a module we know about!");
  535. std::string ErrorMsg;
  536. if (MP->materializeFunction(F, &ErrorMsg)) {
  537. cerr << "Error reading function '" << F->getName()
  538. << "' from bitcode file: " << ErrorMsg << "\n";
  539. abort();
  540. }
  541. // Now retry to get the address.
  542. if (void *Addr = getPointerToGlobalIfAvailable(F))
  543. return Addr;
  544. }
  545. if (F->isDeclaration()) {
  546. bool AbortOnFailure =
  547. !areDlsymStubsEnabled() && !F->hasExternalWeakLinkage();
  548. void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
  549. addGlobalMapping(F, Addr);
  550. return Addr;
  551. }
  552. runJITOnFunctionUnlocked(F, locked);
  553. void *Addr = getPointerToGlobalIfAvailable(F);
  554. assert(Addr && "Code generation didn't add function to GlobalAddress table!");
  555. return Addr;
  556. }
  557. /// getOrEmitGlobalVariable - Return the address of the specified global
  558. /// variable, possibly emitting it to memory if needed. This is used by the
  559. /// Emitter.
  560. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
  561. MutexGuard locked(lock);
  562. void *Ptr = getPointerToGlobalIfAvailable(GV);
  563. if (Ptr) return Ptr;
  564. // If the global is external, just remember the address.
  565. if (GV->isDeclaration()) {
  566. #if HAVE___DSO_HANDLE
  567. if (GV->getName() == "__dso_handle")
  568. return (void*)&__dso_handle;
  569. #endif
  570. Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
  571. if (Ptr == 0 && !areDlsymStubsEnabled()) {
  572. llvm_report_error("Could not resolve external global address: "
  573. +GV->getName());
  574. }
  575. addGlobalMapping(GV, Ptr);
  576. } else {
  577. // GlobalVariable's which are not "constant" will cause trouble in a server
  578. // situation. It's returned in the same block of memory as code which may
  579. // not be writable.
  580. if (isGVCompilationDisabled() && !GV->isConstant()) {
  581. cerr << "Compilation of non-internal GlobalValue is disabled!\n";
  582. abort();
  583. }
  584. // If the global hasn't been emitted to memory yet, allocate space and
  585. // emit it into memory. It goes in the same array as the generated
  586. // code, jump tables, etc.
  587. const Type *GlobalType = GV->getType()->getElementType();
  588. size_t S = getTargetData()->getTypeAllocSize(GlobalType);
  589. size_t A = getTargetData()->getPreferredAlignment(GV);
  590. if (GV->isThreadLocal()) {
  591. MutexGuard locked(lock);
  592. Ptr = TJI.allocateThreadLocalMemory(S);
  593. } else if (TJI.allocateSeparateGVMemory()) {
  594. if (A <= 8) {
  595. Ptr = malloc(S);
  596. } else {
  597. // Allocate S+A bytes of memory, then use an aligned pointer within that
  598. // space.
  599. Ptr = malloc(S+A);
  600. unsigned MisAligned = ((intptr_t)Ptr & (A-1));
  601. Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
  602. }
  603. } else {
  604. Ptr = JCE->allocateSpace(S, A);
  605. }
  606. addGlobalMapping(GV, Ptr);
  607. EmitGlobalVariable(GV);
  608. }
  609. return Ptr;
  610. }
  611. /// recompileAndRelinkFunction - This method is used to force a function
  612. /// which has already been compiled, to be compiled again, possibly
  613. /// after it has been modified. Then the entry to the old copy is overwritten
  614. /// with a branch to the new copy. If there was no old copy, this acts
  615. /// just like JIT::getPointerToFunction().
  616. ///
  617. void *JIT::recompileAndRelinkFunction(Function *F) {
  618. void *OldAddr = getPointerToGlobalIfAvailable(F);
  619. // If it's not already compiled there is no reason to patch it up.
  620. if (OldAddr == 0) { return getPointerToFunction(F); }
  621. // Delete the old function mapping.
  622. addGlobalMapping(F, 0);
  623. // Recodegen the function
  624. runJITOnFunction(F);
  625. // Update state, forward the old function to the new function.
  626. void *Addr = getPointerToGlobalIfAvailable(F);
  627. assert(Addr && "Code generation didn't add function to GlobalAddress table!");
  628. TJI.replaceMachineCodeForFunction(OldAddr, Addr);
  629. return Addr;
  630. }
  631. /// getMemoryForGV - This method abstracts memory allocation of global
  632. /// variable so that the JIT can allocate thread local variables depending
  633. /// on the target.
  634. ///
  635. char* JIT::getMemoryForGV(const GlobalVariable* GV) {
  636. const Type *ElTy = GV->getType()->getElementType();
  637. size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
  638. if (GV->isThreadLocal()) {
  639. MutexGuard locked(lock);
  640. return TJI.allocateThreadLocalMemory(GVSize);
  641. } else {
  642. return new char[GVSize];
  643. }
  644. }
  645. void JIT::addPendingFunction(Function *F) {
  646. MutexGuard locked(lock);
  647. jitstate->getPendingFunctions(locked).push_back(F);
  648. }
  649. JITEventListener::~JITEventListener() {}