diff --git a/docs/changes/2026-11-29-lazy-mc-elf/README.md b/docs/changes/2026-11-29-lazy-mc-elf/README.md new file mode 100644 index 000000000..f636718a5 --- /dev/null +++ b/docs/changes/2026-11-29-lazy-mc-elf/README.md @@ -0,0 +1,22 @@ +# Change: Reduce x86 emission and Lazy Wasm ELF loading overhead + +- **Status**: Implemented +- **Date**: 2026-11-29 +- **Tier**: Light + +## Overview + +Use temporary symbols for local x86 basic blocks and jump tables. Load the +single-function ELF object emitted by Lazy Wasm through typed LLVM views +after validating its section and relocation layout. + +## Impact + +Preserve the instruction stream, local branch relaxation, relocation arithmetic, +and executable publication. Generic object formats and diagnostic configurations +use the existing loader. + +## Checklist + +- [x] Measure emission and loading independently +- [x] Verify the combined patch in supported compilation modes diff --git a/docs/modules/compiler/spec.md b/docs/modules/compiler/spec.md index 548d05504..28da81763 100644 --- a/docs/modules/compiler/spec.md +++ b/docs/modules/compiler/spec.md @@ -568,6 +568,18 @@ dispatch, fallback, gas, and runtime ABI behavior are unchanged. - Entry point is the code pointer corresponding to FuncIdx 0 - Code section is protected via `mprotect(JITCode, size, PROT_READ | PROT_EXEC)` +On Linux, local basic-block and jump-table labels use LLVM temporary symbols +when perf and JIT logging are disabled. Function symbol names are retained for +external calls. Diagnostic builds retain their named local labels. + +The same Linux configuration can load the ELF64 little-endian x86-64 object +for one Lazy Wasm function through LLVM's typed ELF views. This path expects +one executable section and, when present, a RELA section linked to it. Only +in-range 32-bit call relocations to undefined internal function symbols are +collected. The caller binds them to stubs before making the code executable. +Other object layouts go through the generic loader. Discard partially collected +relocations when handing off to that loader. + ### JIT Statistics and perf - Compilation start/end times are recorded in `utils::StatisticPhase::JITCompilation` diff --git a/src/compiler/cgir/cg_basic_block.cpp b/src/compiler/cgir/cg_basic_block.cpp index 336057972..5a27d29d1 100644 --- a/src/compiler/cgir/cg_basic_block.cpp +++ b/src/compiler/cgir/cg_basic_block.cpp @@ -264,7 +264,6 @@ llvm::MCSymbol *CgBasicBlock::getSymbol() const { if (!BlockSymbol) { const CgFunction *MF = getParent(); MCContext &Ctx = MF->getMCContext(); - const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix(); #if defined(ZEN_ENABLE_EVM) && defined(ZEN_ENABLE_LINUX_PERF) std::string BlockComment = getSourceName().empty() @@ -272,7 +271,12 @@ llvm::MCSymbol *CgBasicBlock::getSymbol() const { : getSourceName() + "_" + std::to_string(getSourceOffset()); BlockSymbol = Ctx.getOrCreateSymbol( "EVMBB" + Twine(MF->getFunction().getFuncIdx()) + "_" + BlockComment); +#elif !defined(ZEN_ENABLE_LINUX_PERF) && \ + !defined(ZEN_ENABLE_MULTIPASS_JIT_LOGGING) && \ + defined(ZEN_BUILD_PLATFORM_LINUX) + BlockSymbol = Ctx.createTempSymbol(); #else + const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix(); BlockSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" + Twine(MF->getFunction().getFuncIdx()) + "_" + Twine(getNumber())); diff --git a/src/compiler/cgir/cg_function.cpp b/src/compiler/cgir/cg_function.cpp index bfc7b20c7..55212aa51 100644 --- a/src/compiler/cgir/cg_function.cpp +++ b/src/compiler/cgir/cg_function.cpp @@ -120,8 +120,14 @@ MCSymbol *CgFunction::getJTISymbol(uint32_t JTI) { } llvm::MCSymbol *&JTISymbol = JTISymbols[JTI]; if (!JTISymbol) { +#if !defined(ZEN_ENABLE_LINUX_PERF) && \ + !defined(ZEN_ENABLE_MULTIPASS_JIT_LOGGING) && \ + defined(ZEN_BUILD_PLATFORM_LINUX) + JTISymbol = getMCContext().createTempSymbol(); +#else std::string Name = ".LJTI" + getName() + '_' + std::to_string(JTI); JTISymbol = getContext().getOrCreateMCSymbol(Name); +#endif } return JTISymbol; } diff --git a/src/compiler/compiler.cpp b/src/compiler/compiler.cpp index 6a7e81b15..3b79faca1 100644 --- a/src/compiler/compiler.cpp +++ b/src/compiler/compiler.cpp @@ -166,7 +166,116 @@ void JITCompilerBase::compileMIRToCgIR(MModule &MMod, MFunction &MFunc, } } -void JITCompilerBase::emitObjectBuffer(CompileContext *Ctx) { +static void copyObjectText(CompileContext &Ctx, llvm::ArrayRef Text) { + Ctx.CodeSize = Text.size(); + const size_t Align = Ctx.Lazy ? common::CodeMemPool::PageSize + : common::CodeMemPool::DefaultAlign; + Ctx.CodePtr = reinterpret_cast( + Ctx.CodeMPool->allocate(TO_MPROTECT_CODE_SIZE(Ctx.CodeSize), Align)); + Ctx.CodeOffset = Ctx.CodePtr - Ctx.CodeMPool->getMemStart(); + std::memcpy(Ctx.CodePtr, Text.data(), Ctx.CodeSize); +} + +#if defined(ZEN_BUILD_PLATFORM_LINUX) && !defined(ZEN_ENABLE_LINUX_PERF) && \ + !defined(ZEN_ENABLE_MULTIPASS_JIT_LOGGING) +// A lazy WASM object defines one function at the start of .text. The caller +// already knows its entry offset and needs only the undefined call targets. +static bool loadLazyWasmELF(CompileContext &Ctx, llvm::StringRef Bytes, + uint32_t NumFunctions) { + using namespace llvm::ELF; + using ElfType = llvm::object::ELF64LE; + auto File = llvm::object::ELFFile::create(Bytes); + if (!File) { + llvm::consumeError(File.takeError()); + return false; + } + + const auto &Header = File->getHeader(); + if (!Header.checkMagic() || Header.getFileClass() != ELFCLASS64 || + Header.getDataEncoding() != ELFDATA2LSB || Header.e_type != ET_REL || + Header.e_machine != EM_X86_64) + return false; + + auto Sections = File->sections(); + if (!Sections) { + llvm::consumeError(Sections.takeError()); + return false; + } + + const ElfType::Shdr *Text = nullptr; + const ElfType::Shdr *Relocations = nullptr; + for (const auto &Section : *Sections) { + if (Section.sh_flags & SHF_EXECINSTR) { + if (Text || Section.sh_type != SHT_PROGBITS) + return false; + Text = &Section; + } else if (Section.sh_size && Section.sh_type == SHT_RELA) { + if (Relocations) + return false; + Relocations = &Section; + } else if (Section.sh_size && Section.sh_type == SHT_REL) { + return false; + } + } + if (!Text) + return false; + + auto Code = File->getSectionContents(*Text); + if (!Code) { + llvm::consumeError(Code.takeError()); + return false; + } + + auto &ExternRelocs = Ctx.ExternRelocs; + ZEN_ASSERT(Ctx.Lazy && ExternRelocs.empty()); + auto Discard = llvm::make_scope_exit([&] { ExternRelocs.clear(); }); + if (Relocations) { + if (Relocations->sh_info != + static_cast(Text - Sections->data()) || + Relocations->sh_link >= Sections->size()) + return false; + const auto &Symtab = (*Sections)[Relocations->sh_link]; + auto Symbols = File->symbols(&Symtab); + auto Strings = File->getStringTableForSymtab(Symtab, *Sections); + auto Relas = File->relas(*Relocations); + if (!Symbols || !Strings || !Relas) { + llvm::consumeError(Symbols.takeError()); + llvm::consumeError(Strings.takeError()); + llvm::consumeError(Relas.takeError()); + return false; + } + + ExternRelocs.reserve(Relas->size()); + constexpr llvm::StringLiteral Prefix(JIT_FUNCTION_NAME_PREFIX); + for (const auto &Rela : *Relas) { + const uint64_t Offset = Rela.r_offset; + const uint32_t Symbol = Rela.getSymbol(false); + if (Rela.getType(false) != R_X86_64_PLT32 || Offset > Code->size() || + Code->size() - Offset < sizeof(int32_t) || + Symbol >= Symbols->size() || (*Symbols)[Symbol].st_shndx != SHN_UNDEF) + return false; + + auto Name = (*Symbols)[Symbol].getName(*Strings); + if (!Name) { + llvm::consumeError(Name.takeError()); + return false; + } + uint32_t FuncIdx; + if (!Name->consume_front(Prefix) || Name->getAsInteger(10, FuncIdx) || + FuncIdx >= NumFunctions) + return false; + ExternRelocs.emplace_back(Offset, Rela.r_addend, FuncIdx); + } + } + + copyObjectText(Ctx, *Code); + Discard.release(); + return true; +} +#endif + +static void emitObjectBufferImpl(CompileContext *Ctx, + [[maybe_unused]] uint32_t LazyWasmFunctions) { ZEN_ASSERT(Ctx); // Do nothing if no function is compiled in current thread @@ -190,6 +299,12 @@ void JITCompilerBase::emitObjectBuffer(CompileContext *Ctx) { // Keep the backing capacity in this compilation context for the next object. const llvm::MemoryBufferRef ObjectToLoad( llvm::StringRef(Buffer.data(), Buffer.size()), ""); +#if defined(ZEN_BUILD_PLATFORM_LINUX) && !defined(ZEN_ENABLE_LINUX_PERF) && \ + !defined(ZEN_ENABLE_MULTIPASS_JIT_LOGGING) + if (LazyWasmFunctions && + loadLazyWasmELF(*Ctx, ObjectToLoad.getBuffer(), LazyWasmFunctions)) + return; +#endif auto LoadedObject = llvm::object::ObjectFile::createObjectFile(ObjectToLoad); if (!LoadedObject) { throw getError(ErrorCode::ObjectFileCreationFailed); @@ -373,19 +488,11 @@ void JITCompilerBase::emitObjectBuffer(CompileContext *Ctx) { dumpAsm(ObjectToLoad.getBufferStart(), ObjectToLoad.getBufferSize()); #endif - Ctx->CodeSize = TextSection->getSize(); - size_t Align = Ctx->Lazy ? common::CodeMemPool::PageSize - : common::CodeMemPool::DefaultAlign; - - Ctx->CodePtr = reinterpret_cast( - Ctx->CodeMPool->allocate(TO_MPROTECT_CODE_SIZE(Ctx->CodeSize), Align)); - Ctx->CodeOffset = Ctx->CodePtr - Ctx->CodeMPool->getMemStart(); - auto CodeOrErr = TextSection->getContents(); if (!CodeOrErr) { throw getError(ErrorCode::ObjectFileResolvingFailed); } - std::memcpy(Ctx->CodePtr, CodeOrErr->data(), Ctx->CodeSize); + copyObjectText(*Ctx, llvm::arrayRefFromStringRef(*CodeOrErr)); #if defined(ZEN_ENABLE_EVM) && defined(ZEN_ENABLE_LINUX_PERF) && \ !defined(ZEN_ENABLE_MULTIPASS_JIT_LOGGING) @@ -394,6 +501,10 @@ void JITCompilerBase::emitObjectBuffer(CompileContext *Ctx) { #endif } +void JITCompilerBase::emitObjectBuffer(CompileContext *Ctx) { + emitObjectBufferImpl(Ctx, 0); +} + bool WasmJITCompiler::compileWasmToMC( WasmFrontendContext &Ctx, MModule &Mod, uint32_t FuncIdx, bool DisableGreedyRA, uint8_t *LoopTick, bool AllowLoopGreedy, @@ -835,7 +946,7 @@ LazyJITCompiler::compileFunction(WasmFrontendContext &Ctx, uint32_t FuncIdx, AllowLoopGreedy, &BudgetTimer, CollectPrivateMetadata); if (SelectedLoopGreedy) *SelectedLoopGreedy = LoopGreedy; - emitObjectBuffer(&Ctx); + emitObjectBufferImpl(&Ctx, NumInternalFunctions); uint8_t *JITCode = const_cast(Ctx.CodeMPool->getMemStart()); for (const auto &Reloc : Ctx.ExternRelocs) { uint64_t RelOffset = Ctx.CodeOffset + Reloc.Offset; diff --git a/tests/wast/multipass/lazy_elf_relocations.wast b/tests/wast/multipass/lazy_elf_relocations.wast new file mode 100644 index 000000000..fd5d80e3c --- /dev/null +++ b/tests/wast/multipass/lazy_elf_relocations.wast @@ -0,0 +1,38 @@ +(module + ;; Keep the relocation targets past the first ten internal function IDs. + (func) + (func) + (func) + (func) + (func) + (func) + (func) + (func) + (func) + (func) + + (func $double (param i32) (result i32) + (i32.mul (local.get 0) (i32.const 2))) + + (func $increment (param i32) (result i32) + (i32.add (local.get 0) (i32.const 1))) + + (func (export "alternating_calls") (param i32) (result i32) + (call $increment + (call $double + (call $increment + (call $double (local.get 0)))))) + + (func $sum (export "sum") (param i32) (result i32) + (if (result i32) (i32.eqz (local.get 0)) + (then (i32.const 0)) + (else + (i32.add (local.get 0) + (call $sum (i32.sub (local.get 0) (i32.const 1))))))) + + (func (export "plain") (result i32) (i32.const 42))) + +(assert_return (invoke "alternating_calls" (i32.const 10)) (i32.const 43)) +(assert_return (invoke "plain") (i32.const 42)) +(assert_return (invoke "sum" (i32.const 6)) (i32.const 21)) +(assert_return (invoke "alternating_calls" (i32.const -1)) (i32.const -1))