Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/changes/2026-11-29-lazy-mc-context-reuse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Change: Reuse LLVM MC state between Lazy Multipass functions

- **Status**: Implemented
- **Date**: 2026-11-29
- **Tier**: Light

## Overview

Lazy Multipass emits a separate ELF object for each demand-compiled function.
The Linux JIT can reset and reuse the LLVM MC context and streamer after a
completed object of up to 64 KiB. A compile that stops before emitting a
complete object, a larger object, perf builds and automatic x86 branch
padding use fresh MC state.

## Motivation

Demand-compiling many small functions repeatedly initializes the assembler,
its backend, and the ELF writer. Reusing these allocations reduces work on the
first invocation path, while each emitted object gets its own symbols and
sections.

## Verification

The spec regression test calls two functions with separate jump tables and
relocations to the same callee. It checks every branch and the default arm.

- [x] Implementation complete
- [x] Spec regression test added
- [x] Compiler module spec updated
- [x] Release build and CTest passed
6 changes: 6 additions & 0 deletions docs/modules/compiler/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,12 @@ loader reads the emitted object from the context's byte buffer and resets
the buffer size after parsing, relocation extraction and code copying. It
releases backing allocations larger than 64 KiB.

On Linux without perf/JIT dump support, Lazy Multipass also reuses the
LLVM MC context and streamer after a completed object of up to 64 KiB.
The streamer releases its per-object references before the context resets
its symbols and sections. The next object starts with fresh sections.
Automatic x86 branch padding uses a fresh context and streamer.

### Opt-in private loop tiering

`EnableLazyPrivateTiering` permits demand-compiled private WASM helpers to
Expand Down
40 changes: 31 additions & 9 deletions src/compiler/cgir/mc_lowering.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,29 @@ template <typename T> class MCLowering : public NonCopyable {
ZEN_UNREACHABLE();
}
Streamer = std::move(*StreamerOrErr);
TM.getObjFileLowering()->Initialize(Context, TM);
Streamer->initSections(false, *STI);
#if defined(ZEN_ENABLE_LINUX_PERF) && defined(ZEN_ENABLE_EVM)
// Because actual dwarf source is evm bytecode, set to ./evm-bytecode
// as a placeholder whether or not this file exists.
// fileNo: 1, directive: ".", filename: "evm-bytecode"
Streamer->emitDwarfFileDirective(1, ".", "evm-bytecode");
#endif // ZEN_ENABLE_LINUX_PERF
initializeSections();
}

void finalize() {
Streamer->finish();
Streamer->reset();
// Reset retains some LLVM container capacity. Rebuild after large objects.
constexpr size_t MaxReusableObjectBytes = 64 * 1024;
// LLVM 15's x86 backend retains branch-padding state across reset().
Reusable =
!Streamer->getAllowAutoPadding() && OS.tell() <= MaxReusableObjectBytes;
}

bool tryReuseObject() {
if (!Reusable) {
return false;
}
Reusable = false;
// finalize() cleared streamer references before the sections are freed.
Context.reset();
MF = nullptr;
initializeSections();
return true;
}

void runOnCgFunction(CgFunction &MF) {
Expand All @@ -53,6 +63,17 @@ template <typename T> class MCLowering : public NonCopyable {
}

protected:
void initializeSections() {
TM.getObjFileLowering()->Initialize(Context, TM);
Streamer->initSections(false, *STI);
#if defined(ZEN_ENABLE_LINUX_PERF) && defined(ZEN_ENABLE_EVM)
// Because actual dwarf source is evm bytecode, set to ./evm-bytecode
// as a placeholder whether or not this file exists.
// fileNo: 1, directive: ".", filename: "evm-bytecode"
Streamer->emitDwarfFileDirective(1, ".", "evm-bytecode");
#endif // ZEN_ENABLE_LINUX_PERF
}

void emitFunctionBody() {
llvm::MCSymbol *FuncSym = MF->getSymbol();
Streamer->emitSymbolAttribute(FuncSym, llvm::MCSA_ELF_TypeFunction);
Expand Down Expand Up @@ -200,6 +221,7 @@ template <typename T> class MCLowering : public NonCopyable {
llvm::raw_svector_ostream OS;
std::unique_ptr<llvm::MCStreamer> Streamer;
const llvm::MCSubtargetInfo *STI = nullptr;
bool Reusable = false;

// Following fields are used for single function lowering
CgFunction *MF = nullptr;
Expand All @@ -209,4 +231,4 @@ template <typename T> class MCLowering : public NonCopyable {
#endif
};

} // namespace COMPILER
} // namespace COMPILER
15 changes: 7 additions & 8 deletions src/compiler/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,14 +175,14 @@ CgRegisterClassInfo &CompileContext::getFastRAClassInfo() {
void CompileContext::reinitialize() {
ZEN_ASSERT(MCL);
ZEN_ASSERT(MCCtx);
ZEN_ASSERT(ObjBuffer.empty());
#if defined(ZEN_BUILD_PLATFORM_LINUX) && !defined(ZEN_ENABLE_LINUX_PERF)
if (MCL->tryReuseObject()) {
return;
}
#endif
ThreadMemPool.deleteObject(MCL);
ThreadMemPool.deleteObject(MCCtx);

// Ensure ObjBuffer is empty for upcoming compilation
ZEN_ASSERT(ObjBuffer.empty());

// All sections in object files are created and stored in MCContext, so we
// need to create a new MCContext
initializeMC();
}

Expand Down Expand Up @@ -214,8 +214,7 @@ void CompileContext::initializeTargetMachine() {
void CompileContext::initializeMC() {
MCCtx = ThreadMemPool.newObject<llvm::MCContext>(
TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions,
false); // TODO: AutoReset?
TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);

MCCtx->setObjectFileInfo(TM->getObjFileLowering());

Expand Down
44 changes: 44 additions & 0 deletions tests/wast/multipass/lazy_mc_objects.wast
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
(module
(func $scale (param i32) (result i32)
(i32.mul (local.get 0) (i32.const 7)))

(func $first (param i32) (result i32)
(block $default
(block $four
(block $three
(block $two
(block $one
(block $zero
(br_table $zero $one $two $three $four $default (local.get 0)))
(return (call $scale (i32.const 10))))
(return (call $scale (i32.const 11))))
(return (call $scale (i32.const 12))))
(return (call $scale (i32.const 13))))
(return (call $scale (i32.const 14))))
(call $scale (i32.const 15)))

(func $second (param i32) (result i32)
(block $default
(block $four
(block $three
(block $two
(block $one
(block $zero
(br_table $zero $one $two $three $four $default (local.get 0)))
(return (call $scale (i32.const 20))))
(return (call $scale (i32.const 21))))
(return (call $scale (i32.const 22))))
(return (call $scale (i32.const 23))))
(return (call $scale (i32.const 24))))
(call $scale (i32.const 25)))

(func (export "run") (param i32) (result i32)
(i32.add (call $first (local.get 0)) (call $second (local.get 0)))))

(assert_return (invoke "run" (i32.const 0)) (i32.const 210))
(assert_return (invoke "run" (i32.const 1)) (i32.const 224))
(assert_return (invoke "run" (i32.const 2)) (i32.const 238))
(assert_return (invoke "run" (i32.const 3)) (i32.const 252))
(assert_return (invoke "run" (i32.const 4)) (i32.const 266))
(assert_return (invoke "run" (i32.const 5)) (i32.const 280))
(assert_return (invoke "run" (i32.const -1)) (i32.const 280))
Loading