<div dir="ltr">Hi All,<div><br></div><div>ORC's new concurrent compilation model generates some interesting lifetime and thread safety questions around LLVMContext: We need multiple LLVMContexts (one per module in the simplest case, but at least one per thread), and the lifetime of each context depends on the execution path of the JIT'd code. We would like to deallocate contexts once all modules associated with them have been compiled, but there is no safe or easy way to check that condition at the moment as LLVMContext does not expose how many modules are associated with it.</div><div><br></div><div>One way to fix this would be to add a mutex to LLVMContext, and expose this and the module count. Then in the IR-compiling layer of the JIT we could have something like:</div><div><br></div><div><font face="monospace, monospace">// Compile finished, time to deallocate the module.</font></div><div><font face="monospace, monospace">// Explicit deletes used for clarity, we would use unique_ptrs in practice.</font></div><div><font face="monospace, monospace">auto &Ctx = Mod->getContext();</font></div><div><font face="monospace, monospace">delete Mod;</font></div><div><font face="monospace, monospace">std::lock_guard<std::mutex> Lock(Ctx->getMutex());</font></div><div><font face="monospace, monospace">if (Ctx.getNumModules())</font></div><div><font face="monospace, monospace">  delete Ctx;</font></div><div><br></div><div>Another option would be to invert the ownership model and say that each Module shares ownership of its LLVMContext. That way LLVMContexts would be automatically deallocated when the last module using them is destructed (providing no other shared_ptrs to the context are held elsewhere).</div><div><br></div><div>There are other possible approaches (e.g. side tables for the mutex and module count) but before I spent too much time on it I wanted to see whether anyone else has encountered these issues or has opinions on solutions.</div><div><br></div><div>Cheers,</div><div>Lang.</div></div>