Step 04 · ThreadSafeModule

LLVM Module and LLVMContext are not thread-safe. ORC wraps each (module, context) pair in ThreadSafeModule to enforce a single-thread access discipline.

llvm::orc::ThreadSafeModule tsm(std::move(mod), std::move(ctx));
jit->addIRModule(std::move(tsm));

Notice both unique_ptrs are moved in. After this:

  • Your local mod and ctx are empty.
  • LLJIT owns the module until it has been materialised; afterwards it drops the IR and keeps only the compiled object.

Why one context per module?

Sharing a context between modules forces a global lock around code generation. Giving each module its own context lets ORC's optional compile-threads work in parallel without contention.

In CodegenResult (cp-11) we already kept ctx and mod as unique_ptrs in the right destruction order for exactly this hand-off.