diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h index 3b3c7ac787..5c1c5a61df 100644 --- a/FEXCore/Source/Interface/Context/Context.h +++ b/FEXCore/Source/Interface/Context/Context.h @@ -379,6 +379,10 @@ class ContextImpl final : public FEXCore::Context::Context, public CPU::CodeBuff #endif FEXCore::Utils::WritePriorityMutex::Mutex CodeInvalidationMutex {}; +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) + // MADEIRA: [fexlock-stats] counters for CodeInvalidationMutex, attached in the constructor. + FEXCore::Utils::WritePriorityMutex::IosContentionStats CodeInvalidationStats {}; +#endif uint32_t StrictSplitLockMutex {}; diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp index 8884ec0628..d1500ca0c2 100644 --- a/FEXCore/Source/Interface/Core/Core.cpp +++ b/FEXCore/Source/Interface/Core/Core.cpp @@ -136,6 +136,10 @@ ContextImpl::ContextImpl(const FEXCore::HostFeatures& Features) : HostFeatures {Features} , CPUID {this} , CodeCache {*this} { +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) + CodeInvalidationStats.Name = "CodeInvalidationMutex"; + CodeInvalidationMutex.IosSetContentionStats(&CodeInvalidationStats); +#endif if (!Config.Is64BitMode()) { // When operating in 32-bit mode, the virtual memory we care about is only the lower 32-bits. Config.VirtualMemSize = 1ULL << 32; @@ -675,6 +679,11 @@ void ContextImpl::OnCodeBufferAllocated(const fextl::shared_ptr void ContextImpl::ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer) { FEXCORE_PROFILE_INSTANT("ClearCodeCache"); +#if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec) + if (FEXCore::Core::MadeiraJitMapHook) { // madeira-duo jit-map: host addresses get reused from here on + FEXCore::Core::MadeiraJitMapHook(0, NewCodeBuffer, 0, 0); + } +#endif if (NewCodeBuffer) { // Allocate new CodeBuffer + L3 LookupCache and clear L1+L2 caches @@ -982,10 +991,15 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue bool BlockInForceTSOValidRange = false; auto InstForceTSOIt = ForceTSOInstructions.end(); if (ForceTSOValidRanges.Contains({Block.Entry, Block.Entry + Block.Size})) { - if (auto It = ForceTSOInstructions.lower_bound(Block.Entry); *It < Block.Entry + Block.Size) { - InstForceTSOIt = It; - BlockInForceTSOValidRange = true; - } + // madeira-duo: a block inside a valid range drops TSO for every access the + // metadata does not list, whether or not it holds a listed one. Upstream set + // the flag only for blocks containing a listed instruction (and read *end() + // when there was none), so a block without volatile accesses -- nearly all + // code -- kept full TSO and a module-wide ExtendedVolatileMetadata entry + // changed nothing (PoE2's hot byte-copy loop at exe+0x102a480 still ran + // ldapurb/stlurb with the exe listed, prof1 log 5 Nov 2026). + InstForceTSOIt = ForceTSOInstructions.lower_bound(Block.Entry); + BlockInForceTSOValidRange = true; } // Set the block entry point @@ -1003,6 +1017,42 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue Thread->OpDispatcher->ExitFunction(Thread->OpDispatcher->_InlineEntrypointOffset(GPRSize, Block.Entry - GuestRIP)); } +#if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec) + // madeira-duo byte-copy-loop (OpDispatchBuilder::MatchByteCopyLoop): a block that is exactly a + // byte-at-a-time copy loop becomes one forward MemCpy. Only where TSO is off for the whole block + // (the TSO loop orders every byte store, MemCpy does not), not under full SMC checks or extended + // debug info (both want per-instruction state). MADEIRA_FEX_BYTELOOP=0 turns it off. + { + static int ByteLoopOn = -1; + if (ByteLoopOn < 0) { + const char* Env = getenv("MADEIRA_FEX_BYTELOOP"); + ByteLoopOn = !(Env && Env[0] == '0'); + } + const bool TSOOff = !IsAtomicTSOEnabled() || + (BlockInForceTSOValidRange && + (InstForceTSOIt == ForceTSOInstructions.end() || *InstForceTSOIt >= Block.Entry + Block.Size)); + IR::OpDispatchBuilder::ByteCopyLoop Loop; + if (ByteLoopOn && TSOOff && !ExtendedDebugInfo && Config.SMCChecks != FEXCore::Config::CONFIG_SMC_FULL && + !Block.ForceFullSMCDetection && !HotSMCBlock && + IR::OpDispatchBuilder::MatchByteCopyLoop(Block.DecodedInstructions, InstsInBlock, Block.Entry, &Loop)) { + static std::atomic Said {0}; + const auto* Jcc = &Block.DecodedInstructions[InstsInBlock - 1]; + const uint64_t Length = Jcc->PC + Jcc->InstSize - Block.Entry; + if (Said.fetch_add(1, std::memory_order_relaxed) < 16) { + LogMan::Msg::IFmt("[byteloop] madeira-duo {:#x}: byte copy loop (src r{}, dst r{}, count r{}, byte r{}) -> MemCpy", + Block.Entry, Loop.Src, Loop.Dst, Loop.Count, Loop.Byte); + } + Thread->OpDispatcher->FlushRegisterCache(true); + Thread->OpDispatcher->_GuestOpcode(Block.Entry - GuestRIP); + Thread->OpDispatcher->EmitByteCopyLoop(Loop, Jcc); + BlockInstructionsLength += Length; + TotalInstructionsLength += Length; + TotalInstructions += InstsInBlock; + Thread->OpDispatcher->FinishOp(Jcc->PC + Jcc->InstSize, true); + continue; + } + } +#endif for (size_t i = 0; i < InstsInBlock; ++i) { uint64_t InstAddress = Block.Entry + BlockInstructionsLength; @@ -1460,6 +1510,64 @@ static void IosMonoTryActivate(ContextImpl* CTX, FEXCore::Core::InternalThreadSt } #endif +/* MADEIRA: the CALLRET_SP check below, moved out of CompileBlock so its cache-hit fast path runs it too. */ +/* iOS-Madeira 2026-05-18: CALLRET_SP bounds-validation + RESET. + * + * Initial diagnostic showed callret_sp going 0x10..0x70 BELOW + * Thread->CallRetStackBase — underflow of the FEX prediction stack into + * the lower guard page. On iOS, Wine's VirtualAlloc(MEM_RESERVE, + * PAGE_NOACCESS) doesn't actually enforce NOACCESS on the guard, so the + * guard-page SEGV that would normally trigger CallRetStack::HandleAccessViolation + * never fires, and the existing reset-to-DefaultLocation logic doesn't kick + * in. Result: the stack drifts further into "guard" memory each iteration + * of Thumper's hot dispatch loop. + * + * GPT's Tier-1 fix: replicate HandleAccessViolation's reset proactively + * in C++, triggered at CompileBlock entry whenever we detect callret_sp + * outside the real [base, base+SIZE) range. The callret stack is a + * prediction/fast-return cache, not architectural state — resetting it + * degrades to slower lookup, doesn't change x86 semantics. + * + * Stack direction (per GPT): CALL push uses `stp [sp, -0x10]!`, so + * sp decreases. RET pop uses `ldp [sp], 0x10`, so sp increases. + * sp < base = too many CALL pushes (likely ARM64EC return paths that + * push via the dispatcher sentinel but bypass the FEX RET pop path). + * sp >= end = too many RET pops. Both reset to DefaultLocation. */ +static void CheckCallRetBounds(FEXCore::Core::CpuStateFrame* Frame, uint64_t GuestRIP) { + auto *Thread = Frame ? Frame->Thread : nullptr; + uint64_t crsp = Frame ? Frame->State.callret_sp : 0; + uint64_t crbase = Thread ? reinterpret_cast(Thread->CallRetStackBase) : 0; + uint64_t crend = crbase + FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE; + if (crbase != 0 && (crsp < crbase || crsp >= crend)) { + static volatile uint32_t oob_cnt = 0; + uint32_t n = __sync_add_and_fetch(&oob_cnt, 1); + uint64_t default_loc = crbase + FEXCore::Core::InternalThreadState::CALLRET_DEFAULT_OFFSET; + const char *kind = (crsp < crbase) ? "UNDERFLOW" : "OVERFLOW"; + if (n <= 16) { + LogMan::Msg::EFmt("[CALLRET_OOB #{}] {} callret_sp=0x{:x} " + "base=0x{:x} end=0x{:x} delta=0x{:x} " + "GuestRIP=0x{:x} State.rip=0x{:x} Frame=0x{:x} " + "RESET→0x{:x}", + n, kind, crsp, crbase, crend, + (crsp < crbase) ? (crbase - crsp) : (crsp - crend), + GuestRIP, Frame->State.rip, + reinterpret_cast(Frame), + default_loc); + /* Dump top 4 pseudo-entries before reset (mostly stale; useful to + * see if anyone wrote real callret pairs into the guard page). */ + if (crsp >= 0x10000) { + for (int i = 0; i < 4; i++) { + uint64_t *pair = reinterpret_cast(crsp + i * 0x10); + LogMan::Msg::EFmt("[CALLRET_OOB #{}] [+0x{:x}] = {{0x{:x}, 0x{:x}}}", + n, i * 0x10, pair[0], pair[1]); + } + } + } + /* Tier-1 reset to DefaultLocation, matching CallRetStack::HandleAccessViolation. */ + Frame->State.callret_sp = default_loc; + } +} + uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_t GuestRIP, uint64_t MaxInst) { if constexpr (BLOCK_DEBUGGING) { // Block debugging logic is hand-written and needs to be handled with care. @@ -1500,6 +1608,59 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ } #endif +#ifdef FEX_IOS_HOST + /* madeira-duo (20 Nov 2026): alias-first. A pool-copy alias never gets a block (ml315 below), so the + * fast path's FindBlock under CodeInvalidationMutex could only miss for one, and then ml315 redirected + * it. Path of Exile 2 calls x64 code in hybrid DLLs through pool-copy addresses (madeira_d3d12's + * list-journal methods and trampolines, ntdll's syscall entry) about 450K times a second per frame + * thread: the shared-lock round trips, the lookup read lock and the block-map probe were 27% of those + * threads' CPU (fexl1-run1 profile). The reverse translation takes no lock (its per-chunk answer + * cache hits), so check it first and go straight back to the dispatcher with the PE VA, exactly as + * ml315 does. Delivery-mode calls (ml455) redirect the same way there, so no condition on them here. + * The callret bounds check stays; PreCompile's cross-process work waits for the next real compile, + * as it does for every dispatcher L1 hit. MADEIRA_FEX_ALIAS_FIRST=0 turns it off. */ + { + static int AliasFirstOn = -1; + if (AliasFirstOn < 0) { + const char* Env = getenv("MADEIRA_FEX_ALIAS_FIRST"); + AliasFirstOn = !(Env && Env[0] == '0'); + } + if (AliasFirstOn && GuestRIP >= 0x10000) { + const uint64_t PeRIP = IosJitReverseTranslate(GuestRIP); + if (PeRIP != GuestRIP) { + CheckCallRetBounds(Frame, GuestRIP); + Thread->LookupCache->IosNoteAliasRedirect(PeRIP); + Frame->State.rip = PeRIP; + return Frame->Pointers.DispatcherLoopTop; + } + } + } + + /* MADEIRA: cache-hit fast path. Nearly every call here is a lookup that L3 answers (the emitted + * dispatcher only probes L1, and L2 is off on iOS), and the reports, RIP checks and telemetry below + * ran on every one of them: IosJitReverseTranslate, IsAddressInCodeBuffer, and shared counters + * (g_cb_total, the hot-RIP estimator, the per-thread callret slots) that every guest thread writes. + * A block in the cache already passed all of those when it was compiled, and a pool-copy alias never + * gets a block (see ml315 below), so a hit can return here. A miss falls through to the full path + * unchanged. Not taken while this thread holds emission locks (ml455). [CB_SUMMARY] now counts only + * the calls that miss here. MADEIRA_FEX_CB_FAST=0 turns it off. */ + { + static int CbFastOn = -1; + if (CbFastOn < 0) { + const char* Env = getenv("MADEIRA_FEX_CB_FAST"); + CbFastOn = !(Env && Env[0] == '0'); + } + if (CbFastOn && GuestRIP >= 0x10000 && !FEXCore::Utils::WritePriorityMutex::IosEmissionLocksHeldBySelf()) { + CheckCallRetBounds(Frame, GuestRIP); + static_cast(Thread->CTX)->SyscallHandler->PreCompile(); + std::shared_lock FastLk {CodeInvalidationMutex}; + if (auto HostCode = Thread->LookupCache->FindBlock(Thread, GuestRIP)) { + return HostCode; + } + } + } +#endif + #ifdef FEX_IOS_HOST /* The capture buffers reported below exist only in the FEX_IOS_HOST (Windows module) * builds, not in the native iOS FEXCore libraries that build/fex-ios makes. */ @@ -1601,6 +1762,7 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ "-- redirecting to PE VA and re-entering the dispatcher", N + 1, GuestRIP, PeRIP); } + Thread->LookupCache->IosNoteAliasRedirect(PeRIP); Frame->State.rip = PeRIP; return Frame->Pointers.DispatcherLoopTop; } @@ -1850,62 +2012,7 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ } } - /* iOS-Madeira 2026-05-18: CALLRET_SP bounds-validation + RESET. - * - * Initial diagnostic showed callret_sp going 0x10..0x70 BELOW - * Thread->CallRetStackBase — underflow of the FEX prediction stack into - * the lower guard page. On iOS, Wine's VirtualAlloc(MEM_RESERVE, - * PAGE_NOACCESS) doesn't actually enforce NOACCESS on the guard, so the - * guard-page SEGV that would normally trigger CallRetStack::HandleAccessViolation - * never fires, and the existing reset-to-DefaultLocation logic doesn't kick - * in. Result: the stack drifts further into "guard" memory each iteration - * of Thumper's hot dispatch loop. - * - * GPT's Tier-1 fix: replicate HandleAccessViolation's reset proactively - * in C++, triggered at CompileBlock entry whenever we detect callret_sp - * outside the real [base, base+SIZE) range. The callret stack is a - * prediction/fast-return cache, not architectural state — resetting it - * degrades to slower lookup, doesn't change x86 semantics. - * - * Stack direction (per GPT): CALL push uses `stp [sp, -0x10]!`, so - * sp decreases. RET pop uses `ldp [sp], 0x10`, so sp increases. - * sp < base = too many CALL pushes (likely ARM64EC return paths that - * push via the dispatcher sentinel but bypass the FEX RET pop path). - * sp >= end = too many RET pops. Both reset to DefaultLocation. */ - { - auto *Thread = Frame ? Frame->Thread : nullptr; - uint64_t crsp = Frame ? Frame->State.callret_sp : 0; - uint64_t crbase = Thread ? reinterpret_cast(Thread->CallRetStackBase) : 0; - uint64_t crend = crbase + FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE; - if (crbase != 0 && (crsp < crbase || crsp >= crend)) { - static volatile uint32_t oob_cnt = 0; - uint32_t n = __sync_add_and_fetch(&oob_cnt, 1); - uint64_t default_loc = crbase + FEXCore::Core::InternalThreadState::CALLRET_DEFAULT_OFFSET; - const char *kind = (crsp < crbase) ? "UNDERFLOW" : "OVERFLOW"; - if (n <= 16) { - LogMan::Msg::EFmt("[CALLRET_OOB #{}] {} callret_sp=0x{:x} " - "base=0x{:x} end=0x{:x} delta=0x{:x} " - "GuestRIP=0x{:x} State.rip=0x{:x} Frame=0x{:x} " - "RESET→0x{:x}", - n, kind, crsp, crbase, crend, - (crsp < crbase) ? (crbase - crsp) : (crsp - crend), - GuestRIP, Frame->State.rip, - reinterpret_cast(Frame), - default_loc); - /* Dump top 4 pseudo-entries before reset (mostly stale; useful to - * see if anyone wrote real callret pairs into the guard page). */ - if (crsp >= 0x10000) { - for (int i = 0; i < 4; i++) { - uint64_t *pair = reinterpret_cast(crsp + i * 0x10); - LogMan::Msg::EFmt("[CALLRET_OOB #{}] [+0x{:x}] = {{0x{:x}, 0x{:x}}}", - n, i * 0x10, pair[0], pair[1]); - } - } - } - /* Tier-1 reset to DefaultLocation, matching CallRetStack::HandleAccessViolation. */ - Frame->State.callret_sp = default_loc; - } - } + CheckCallRetBounds(Frame, GuestRIP); /* iOS-Madeira 2026-05-15: JIT-pool RIP detector — LOG-ONLY. * diff --git a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp index 21eadbef78..1ebe75b62c 100644 --- a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp +++ b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp @@ -210,8 +210,15 @@ void Dispatcher::EmitDispatcher() { ldrb(TMP1, STATE_PTR(CpuStateFrame, State.flags[X86State::RFLAG_TF_RAW_LOC])); (void)cbnz(ARMEmitter::Size::i32Bit, TMP1, &LoopTop); ldp(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer)); - and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, EC_CALL_CHECKER_PC_REG, ARMEmitter::ShiftType::LSL, - FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + if (LookupCache::L1HashEnabled()) { + // MADEIRA: hashed L1 index, as LookupCache::L1Index. TMP4 is reloaded by the ldp below. + eor(ARMEmitter::Size::i64Bit, TMP4, EC_CALL_CHECKER_PC_REG, EC_CALL_CHECKER_PC_REG, ARMEmitter::ShiftType::LSR, + LookupCache::L1_HASH_SHIFT); + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP4, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } else { + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, EC_CALL_CHECKER_PC_REG, ARMEmitter::ShiftType::LSL, + FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } add(TMP1, TMP1, TMP2); ldp(TMP4, TMP2, TMP1, 0); sub(TMP2, TMP2, EC_CALL_CHECKER_PC_REG); @@ -310,7 +317,13 @@ void Dispatcher::EmitDispatcher() { ARMEmitter::ForwardLabel L1Miss; ldp(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer)); // Entry address = L1Pointer + ((RIP << ilog2(entry size)) & pre-scaled mask) - and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + if (LookupCache::L1HashEnabled()) { + // MADEIRA: hashed L1 index, as LookupCache::L1Index. TMP4 is reloaded by the ldp below. + eor(ARMEmitter::Size::i64Bit, TMP4, RipReg, RipReg, ARMEmitter::ShiftType::LSR, LookupCache::L1_HASH_SHIFT); + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP4, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } else { + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } add(TMP1, TMP1, TMP2); ldp(TMP4, TMP2, TMP1, 0); sub(TMP2, TMP2, RipReg); @@ -367,11 +380,20 @@ void Dispatcher::EmitDispatcher() { // If we've made it here then we have a real compiled block { // update L1 cache - ldp(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer)); - - // Calculate (tmp1 + ((ripreg & L1_ENTRIES_MASK) << 4)) for the address - // L1Mask is pre-shifted. - and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg.R(), ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + if (LookupCache::L1HashEnabled()) { + // MADEIRA: hashed L1 index, as LookupCache::L1Index. TMP4 holds the host code here, so hash + // into TMP1 first and load the mask and pointer separately. + eor(ARMEmitter::Size::i64Bit, TMP1, RipReg.R(), RipReg.R(), ARMEmitter::ShiftType::LSR, LookupCache::L1_HASH_SHIFT); + ldr(TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Mask)); + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP1, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer)); + } else { + ldp(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer)); + + // Calculate (tmp1 + ((ripreg & L1_ENTRIES_MASK) << 4)) for the address + // L1Mask is pre-shifted. + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg.R(), ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } add(TMP1, TMP1, TMP2); stp(TMP4, RipReg, TMP1); diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp index 6a0d498954..9159df82f8 100644 --- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp @@ -363,7 +363,13 @@ DEF_OP(ExitFunction) { // Calculate (tmp1 + ((ripreg & L1_ENTRIES_MASK) << 4)) for the address // L1Mask is pre-shifted. - and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + if (LookupCache::L1HashEnabled()) { + // MADEIRA: hashed L1 index, (rip ^ rip >> 17) & mask, as LookupCache::L1Index. TMP3 is free here. + eor(ARMEmitter::Size::i64Bit, TMP3, RipReg, RipReg, ARMEmitter::ShiftType::LSR, LookupCache::L1_HASH_SHIFT); + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP3, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } else { + and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry))); + } add(TMP1, TMP1, TMP2); ldp(TMP2, TMP1, TMP1, 0); diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp index 24b4b1d691..ec10e9e295 100644 --- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp +++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp @@ -1402,6 +1402,13 @@ CPUBackend::CompiledCode Arm64JITCore::CompileCode(uint64_t Entry, uint64_t Size } #endif memcpy(WritePtr(GetCursorAddress()), TempCodeBuffer, TempSize); +#if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec) + if (FEXCore::Core::MadeiraJitMapHook) { // madeira-duo jit-map: where this block lives, for the CPU profile. + // After the memcpy: before it the final address still holds the pool's NOP fill, + // and MADEIRA_JITCODE dumps the bytes from there (prof8 got only NOPs). + FEXCore::Core::MadeiraJitMapHook(reinterpret_cast(CodeData.BlockBegin), CodeData.Size, Entry, Size); + } +#endif SetCursorOffset(CodeBuffers.LatestOffset + TempSize); CodeBuffers.LatestOffset = GetCursorOffset(); diff --git a/FEXCore/Source/Interface/Core/LookupCache.cpp b/FEXCore/Source/Interface/Core/LookupCache.cpp index 1b93edb44f..c405b2c738 100644 --- a/FEXCore/Source/Interface/Core/LookupCache.cpp +++ b/FEXCore/Source/Interface/Core/LookupCache.cpp @@ -188,6 +188,7 @@ void LookupCache::ClearThreadLocalCaches(const LookupCacheWriteLockToken&) { // TODO: Rename this member to avoid confusion with code caching CachedCodePages.clear(); + ResetCachedPageBounds(); } void LookupCache::ClearCache(const LookupCacheWriteLockToken& lk) { diff --git a/FEXCore/Source/Interface/Core/LookupCache.h b/FEXCore/Source/Interface/Core/LookupCache.h index 3a437854ec..cff879d2a0 100644 --- a/FEXCore/Source/Interface/Core/LookupCache.h +++ b/FEXCore/Source/Interface/Core/LookupCache.h @@ -14,11 +14,17 @@ #include #include +#include #include +#include #include #include #include +#ifdef FEX_IOS_HOST +extern "C" uint32_t IosTebTsdOffset; // ARM64EC/Module.cpp, see Arm64Emitter.h +#endif + namespace FEXCore { struct LookupCacheBaseLockToken { protected: @@ -187,6 +193,37 @@ class LookupCache { uintptr_t GuestCode; }; + /* MADEIRA: the L1 index is (rip ^ rip >> 17) & mask instead of rip & mask. 92% of x64 block entries + * are 16-byte aligned, so the plain mask used 1/16 of the slots and most L1 misses were conflicts + * between blocks that were already compiled (dig2 C2). Every site that indexes L1 must use the same + * expression: the C++ lookups and fills below (L1Index), and the emitted lookups in Dispatcher.cpp and + * BranchOps.cpp (L1HashEnabled at code-generation time). If an invalidation looked at a different slot + * from the fill, a stale translation would survive in L1. MADEIRA_FEX_L1_HASH=0 restores the plain + * mask; the variable is read once, the first time any of those sites asks. */ + static constexpr unsigned L1_HASH_SHIFT = 17; + static bool L1HashEnabled() { + static const bool Enabled = [] { + const char* Env = getenv("MADEIRA_FEX_L1_HASH"); + const bool On = !(Env && Env[0] == '0'); + LogMan::Msg::EFmt("[l1-hash] index={} (MADEIRA_FEX_L1_HASH={})", On ? "rip^rip>>17" : "rip", Env ? Env : "unset"); + return On; + }(); + return Enabled; + } + static uint64_t L1Index(uint64_t Address) { + return L1HashEnabled() ? (Address ^ (Address >> L1_HASH_SHIFT)) : Address; + } + + /* MADEIRA: MADEIRA_FEX_FREE_SKIP=0 turns off InvalidateCacheRange's cached-page bounds check (and, + * in InvalidationTracker, the skip for frees of never-executable memory). Read once. */ + static bool FreeSkipEnabled() { + static const bool Enabled = [] { + const char* Env = getenv("MADEIRA_FEX_FREE_SKIP"); + return !(Env && Env[0] == '0'); + }(); + return Enabled; + } + LookupCache(FEXCore::Context::ContextImpl* CTX); ~LookupCache(); @@ -199,10 +236,13 @@ class LookupCache { uintptr_t FindBlock(FEXCore::Core::InternalThreadState* Thread, uint64_t Address) { // Try L1, no lock needed - auto& L1Entry = reinterpret_cast(L1Pointer)[Address & L1PointerMask]; + auto& L1Entry = reinterpret_cast(L1Pointer)[L1Index(Address) & L1PointerMask]; if (L1Entry.GuestCode == Address) { return L1Entry.HostCode; } +#ifdef FEX_IOS_HOST + CountL1Miss(); +#endif // L2 and L3 need to be locked uintptr_t HostPtr {}; @@ -354,11 +394,12 @@ class LookupCache { // cache returned to that size and sent the address to its old translation (HotSpot, rewriting // code it runs, failed one launch in three). Entries past the current size were decommitted when // the cache shrank. + const uint64_t Index = L1Index(Address); for (size_t Entries = DynamicL1Cache() ? MIN_L1_ENTRIES : L1PointerMask + 1; Entries <= L1PointerMask + 1; Entries <<= 1) { - auto& L1Entry = reinterpret_cast(L1Pointer)[Address & (Entries - 1)]; + auto& L1Entry = reinterpret_cast(L1Pointer)[Index & (Entries - 1)]; #else { - auto& L1Entry = reinterpret_cast(L1Pointer)[Address & L1PointerMask]; + auto& L1Entry = reinterpret_cast(L1Pointer)[L1Index(Address) & L1PointerMask]; #endif if (L1Entry.GuestCode == Address) { L1Entry.GuestCode = 0; @@ -392,16 +433,52 @@ class LookupCache { bool InvalidateCacheRange(uint64_t Start, uint64_t Length) { auto lk = Shared->AcquireWriteLock(); - auto lower = CachedCodePages.lower_bound(Start >> 12); - auto upper = CachedCodePages.upper_bound((Start + Length - 1) >> 12); + if (Length == 0) { + return false; + } - for (auto it = lower; it != upper; it++) { - for (const auto& Entry : it->second) { - InvalidateCache(Entry, lk); + // CachedCodePages is a hash map (see its declaration), so there is no ordered range to erase. + // Walk whichever is shorter: the pages of the range, or the map's entries. + const uint64_t FirstPage = Start >> 12; + const uint64_t LastPage = (Start + Length - 1) >> 12; + bool ret = false; + + // MADEIRA: every thread's cache is walked for every invalidation, inside the exclusive + // CodeInvalidationMutex section, and most ranges (guest frees of heap memory) are nowhere near the + // pages this thread has cached. MinCachedPage/MaxCachedPage bound every page that was ever added + // since the map was last empty, so a range outside them has nothing here. + if (FreeSkipEnabled() && (CachedCodePages.empty() || LastPage < MinCachedPage || FirstPage > MaxCachedPage)) { + return false; + } + + if (LastPage - FirstPage < CachedCodePages.size()) { + for (uint64_t Page = FirstPage; Page <= LastPage; Page++) { + auto it = CachedCodePages.find(Page); + if (it == CachedCodePages.end()) { + continue; + } + for (const auto& Entry : it->second) { + InvalidateCache(Entry, lk); + } + CachedCodePages.erase(it); + ret = true; + } + } else { + for (auto it = CachedCodePages.begin(); it != CachedCodePages.end();) { + if (it->first < FirstPage || it->first > LastPage) { + ++it; + continue; + } + for (const auto& Entry : it->second) { + InvalidateCache(Entry, lk); + } + it = CachedCodePages.erase(it); + ret = true; } } - bool ret = upper != lower; - CachedCodePages.erase(lower, upper); + if (CachedCodePages.empty()) { + ResetCachedPageBounds(); + } return ret; } @@ -445,11 +522,14 @@ class LookupCache { private: void CacheBlockMapping(uint64_t Address, const GuestToHostMap::BlockEntry& Entry, bool L1Only, const LookupCacheBaseLockToken& lk) { for (const auto& CodePage : Entry.CodePages) { - CachedCodePages[CodePage >> 12].insert(Address); + const uint64_t Page = CodePage >> 12; + CachedCodePages[Page].insert(Address); + MinCachedPage = std::min(MinCachedPage, Page); + MaxCachedPage = std::max(MaxCachedPage, Page); } // Do L1 - auto& L1Entry = reinterpret_cast(L1Pointer)[Address & L1PointerMask]; + auto& L1Entry = reinterpret_cast(L1Pointer)[L1Index(Address) & L1PointerMask]; L1Entry.GuestCode = Address; L1Entry.HostCode = Entry.HostCode; @@ -501,7 +581,138 @@ class LookupCache { } // Maps from a page index to all blocks in the page that have at some point been fetched into L1/L2 - fextl::map> CachedCodePages; + // MADEIRA: a hash map, not fextl::map. With L2 disabled (the iOS default) every L1 miss that L3 + // answers lands in CacheBlockMapping, and the tree descent here was 1.25% of all CPU in a capped + // PoE2 profile (prof11, about 70k misses/s). InvalidateCacheRange no longer needs the ordering. + fextl::robin_map> CachedCodePages; + // MADEIRA: lowest and highest page added to CachedCodePages since it was last empty (see + // InvalidateCacheRange). Only widened while entries exist, reset when the map empties. + uint64_t MinCachedPage = UINT64_MAX; + uint64_t MaxCachedPage = 0; + void ResetCachedPageBounds() { + MinCachedPage = UINT64_MAX; + MaxCachedPage = 0; + } + +#ifdef FEX_IOS_HOST + /* MADEIRA: per-thread L1 miss rate. Every C++ lookup that misses L1 counts (the emitted lookups + * only come here after their own L1 probe missed), and about every 30 s the thread logs its rate. + * The clock is read once per 4096 misses and is the counter register, not a library call (see + * ml1059 below). */ + uint64_t IosL1Misses {}; + uint64_t IosL1MissesAtReport {}; + uint64_t IosL1ReportTicks {}; + void CountL1Miss() { + if ((++IosL1Misses & 0xfff) != 0) { + return; + } + uint64_t Now, Frequency; + __asm volatile("mrs %0, cntvct_el0" : "=r"(Now)); + __asm volatile("mrs %0, cntfrq_el0" : "=r"(Frequency)); + if (!IosL1ReportTicks) { + IosL1ReportTicks = Now; + IosL1MissesAtReport = IosL1Misses; + return; + } + const uint64_t Elapsed = Now - IosL1ReportTicks; + if (Elapsed < Frequency * 30) { + return; + } + // The TEB as the dispatcher finds it (x18 is not reliable on the iOS host): TPIDRRO_EL0 plus Wine's + // published TSD offset, then ClientId.UniqueThread at +0x48, the tid the [thr-name] lines use. + uint32_t Tid = 0; + if (IosTebTsdOffset) { + uint64_t Tpidrro; + __asm volatile("mrs %0, TPIDRRO_EL0" : "=r"(Tpidrro)); + const uint64_t Teb = *reinterpret_cast((Tpidrro & ~uint64_t(7)) + IosTebTsdOffset); + Tid = Teb ? *reinterpret_cast(Teb + 0x48) : 0; + } + LogMan::Msg::EFmt("[l1-miss-t] tid={:04x} {:.0f}/s over {:.1f}s, total={} l1-entries={} hash={}", Tid, + double(IosL1Misses - IosL1MissesAtReport) * double(Frequency) / double(Elapsed), + double(Elapsed) / double(Frequency), IosL1Misses, L1PointerMask + 1, L1HashEnabled() ? 1 : 0); + IosL1ReportTicks = Now; + IosL1MissesAtReport = IosL1Misses; + } + + +public: + /* madeira-duo (20 Nov 2026): pool-copy alias redirects on this thread (Core.cpp alias-first and + * ml315). About every 30 s the thread logs its rate and its heaviest PE targets, so the log names + * which DLL's code the game reaches through alias addresses (map a target to its module with the + * "Load module" lines). The target table is 16 slots, each a frequent-items counter: a different + * target landing on a held slot takes a count away and replaces the holder only at zero, so a + * target that dominates its slot stays. Thread-local state only; no atomics. */ + void IosNoteAliasRedirect(uint64_t PeRIP) { + const uint32_t Slot = static_cast((PeRIP >> 4) ^ (PeRIP >> 12)) & 15; + if (IosAliasTarget[Slot] == PeRIP) { + ++IosAliasHits[Slot]; + } else if (IosAliasHits[Slot] == 0) { + IosAliasTarget[Slot] = PeRIP; + IosAliasHits[Slot] = 1; + } else { + --IosAliasHits[Slot]; + } + if ((++IosAliasRedirects & 0xfff) != 0) { + return; + } + uint64_t Now, Frequency; + __asm volatile("mrs %0, cntvct_el0" : "=r"(Now)); + __asm volatile("mrs %0, cntfrq_el0" : "=r"(Frequency)); + if (!IosAliasReportTicks) { + IosAliasReportTicks = Now; + IosAliasRedirectsAtReport = IosAliasRedirects; + return; + } + const uint64_t Elapsed = Now - IosAliasReportTicks; + if (Elapsed < Frequency * 30) { + return; + } + const uint64_t Window = IosAliasRedirects - IosAliasRedirectsAtReport; + uint32_t Order[16]; + for (uint32_t i = 0; i < 16; i++) { + Order[i] = i; + } + for (uint32_t i = 0; i < 6; i++) { + for (uint32_t j = i + 1; j < 16; j++) { + if (IosAliasHits[Order[j]] > IosAliasHits[Order[i]]) { + const uint32_t Swap = Order[i]; + Order[i] = Order[j]; + Order[j] = Swap; + } + } + } + LogMan::Msg::EFmt("[alias-redir] tid={:04x} {:.0f}/s over {:.1f}s, total={}; top PE targets (approximate counts): " + "{:#x} {}, {:#x} {}, {:#x} {}, {:#x} {}, {:#x} {}, {:#x} {}", + IosCurrentTid(), double(Window) * double(Frequency) / double(Elapsed), double(Elapsed) / double(Frequency), + IosAliasRedirects, IosAliasTarget[Order[0]], IosAliasHits[Order[0]], IosAliasTarget[Order[1]], + IosAliasHits[Order[1]], IosAliasTarget[Order[2]], IosAliasHits[Order[2]], IosAliasTarget[Order[3]], + IosAliasHits[Order[3]], IosAliasTarget[Order[4]], IosAliasHits[Order[4]], IosAliasTarget[Order[5]], + IosAliasHits[Order[5]]); + for (uint32_t i = 0; i < 16; i++) { + IosAliasHits[i] = 0; + IosAliasTarget[i] = 0; + } + IosAliasReportTicks = Now; + IosAliasRedirectsAtReport = IosAliasRedirects; + } + +private: + uint64_t IosAliasRedirects {}; + uint64_t IosAliasRedirectsAtReport {}; + uint64_t IosAliasReportTicks {}; + uint64_t IosAliasTarget[16] {}; + uint64_t IosAliasHits[16] {}; + + static uint32_t IosCurrentTid() { + if (!IosTebTsdOffset) { + return 0; + } + uint64_t Tpidrro; + __asm volatile("mrs %0, TPIDRRO_EL0" : "=r"(Tpidrro)); + const uint64_t Teb = *reinterpret_cast((Tpidrro & ~uint64_t(7)) + IosTebTsdOffset); + return Teb ? *reinterpret_cast(Teb + 0x48) : 0; + } +#endif uintptr_t PagePointer; uintptr_t PageMemory; diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp index fec669f508..ecb1b083e5 100644 --- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp @@ -5230,3 +5230,187 @@ void OpDispatchBuilder::NoExecOp(OpcodeArgs) { #undef OpcodeArgs } // namespace FEXCore::IR + +/* madeira-duo byte-copy-loop. + * + * MSVC emits byte-at-a-time copy loops for copies whose size it cannot see, + * e.g. Path of Exile 2's hottest function (exe+0x1029bb0, ~9% of all CPU): + * + * loop: movzx eax, byte [r14] ; lea r14, [r14+1] + * mov [rcx], al ; lea rcx, [rcx+1] + * sub rdx, 1 ; jne loop + * + * Translated one guest instruction at a time that is eight host instructions + * per byte. When a decoded block is exactly such a loop (the block starts at + * the loop head and ends at the backward jne), it is emitted as one forward + * MemCpy, which has REP MOVSB's semantics: bytes in ascending order, so an + * overlapping copy gives the same result as the loop. The registers and flags + * left behind are the loop's: + * Src += n, Dst += n, Count = 0 + * Byte = the last byte copied, zero-extended (read back from Dst[n-1], which is + * what the loop's last load returned and stored; with n == 0 the loop + * would run 2^64 times, so that case only reads Src[0] like its first + * iteration does) + * flags = SUB 1, 1 (ZF, PF set; CF, OF, SF, AF clear) + * Accepted forms (64-bit mode, REX the only prefix, no SIB/RIP bases): + * load movzx r32/r64, byte [S] (0F B6, mod 00) + * store mov byte [D], r8 (88, mod 00) + * step lea R, [R+1] | inc R | add R, 1 for S after the load, D after the store + * count sub C, 1 (83 /5 ib 1), fifth + * branch jne back to the block entry (75 rel8 or 0F 85 rel32), last + * The caller applies it only where TSO is off for the block: MemCpy does not + * order its stores the way the TSO byte loop does. */ +namespace FEXCore::IR { +namespace { +struct ByteLoopInsn { + enum Kind { NONE, LOAD, STORE, STEP, COUNT, BRANCH } Kind {NONE}; + uint8_t Reg {}, Base {}; + int64_t Target {}; +}; + +ByteLoopInsn DecodeByteLoopInsn(const X86Tables::DecodedInst& I) { + ByteLoopInsn R; + const uint8_t* B = I.InstBytes; + const uint8_t Len = I.InstSize; + uint8_t P = 0, Rex = 0; + if (Len && (B[0] & 0xF0) == 0x40) { + Rex = B[0]; + P = 1; + } + const uint8_t RexW = (Rex >> 3) & 1, RexR = (Rex >> 2) & 1, RexB = Rex & 1; + auto ModRM = [&](uint8_t At, uint8_t& Mod, uint8_t& RegF, uint8_t& Rm) { + Mod = B[At] >> 6; + RegF = ((B[At] >> 3) & 7) | (RexR << 3); + Rm = (B[At] & 7) | (RexB << 3); + }; + uint8_t Mod, RegF, Rm; + if (Len == P + 3 && B[P] == 0x0F && B[P + 1] == 0xB6) { // movzx r, byte [base] + ModRM(P + 2, Mod, RegF, Rm); + if (Mod == 0 && (Rm & 7) != 4 && (Rm & 7) != 5) { + R.Kind = ByteLoopInsn::LOAD; + R.Reg = RegF; + R.Base = Rm; + } + } else if (Len == P + 2 && B[P] == 0x88) { // mov byte [base], r8 + ModRM(P + 1, Mod, RegF, Rm); + if (Mod == 0 && (Rm & 7) != 4 && (Rm & 7) != 5 && (Rex || RegF < 4)) { + R.Kind = ByteLoopInsn::STORE; + R.Reg = RegF; + R.Base = Rm; + } + } else if (RexW && Len == P + 3 && B[P] == 0x8D) { // lea R, [R+1] + ModRM(P + 1, Mod, RegF, Rm); + if (Mod == 1 && (Rm & 7) != 4 && RegF == Rm && B[P + 2] == 1) { + R.Kind = ByteLoopInsn::STEP; + R.Reg = RegF; + } + } else if (RexW && Len == P + 2 && B[P] == 0xFF) { // inc R + ModRM(P + 1, Mod, RegF, Rm); + if (Mod == 3 && (RegF & 7) == 0) { + R.Kind = ByteLoopInsn::STEP; + R.Reg = Rm; + } + } else if (RexW && Len == P + 3 && B[P] == 0x83 && B[P + 2] == 1) { // add R, 1 / sub R, 1 + ModRM(P + 1, Mod, RegF, Rm); + if (Mod == 3 && (RegF & 7) == 0) { + R.Kind = ByteLoopInsn::STEP; + R.Reg = Rm; + } else if (Mod == 3 && (RegF & 7) == 5) { + R.Kind = ByteLoopInsn::COUNT; + R.Reg = Rm; + } + } else if (!Rex && Len == 2 && B[0] == 0x75) { // jne rel8 + R.Kind = ByteLoopInsn::BRANCH; + R.Target = static_cast(I.PC + Len) + static_cast(B[1]); + } else if (!Rex && Len == 6 && B[0] == 0x0F && B[1] == 0x85) { // jne rel32 + int32_t Rel; + memcpy(&Rel, B + 2, 4); + R.Kind = ByteLoopInsn::BRANCH; + R.Target = static_cast(I.PC + Len) + Rel; + } + return R; +} +} // namespace + +bool OpDispatchBuilder::MatchByteCopyLoop(const X86Tables::DecodedInst* Insts, size_t NumInsts, uint64_t Entry, ByteCopyLoop* Out) { + if (NumInsts != 6) { + return false; + } + ByteLoopInsn D[6]; + for (size_t i = 0; i < 6; i++) { + if (Insts[i].PC != (i ? Insts[i - 1].PC + Insts[i - 1].InstSize : Entry)) { + return false; + } + D[i] = DecodeByteLoopInsn(Insts[i]); + if (D[i].Kind == ByteLoopInsn::NONE) { + return false; + } + } + if (D[4].Kind != ByteLoopInsn::COUNT || D[5].Kind != ByteLoopInsn::BRANCH || D[5].Target != static_cast(Entry)) { + return false; + } + int Load = -1, Store = -1, StepA = -1, StepB = -1; + for (int i = 0; i < 4; i++) { + switch (D[i].Kind) { + case ByteLoopInsn::LOAD: if (Load >= 0) return false; Load = i; break; + case ByteLoopInsn::STORE: if (Store >= 0) return false; Store = i; break; + case ByteLoopInsn::STEP: if (StepA < 0) StepA = i; else if (StepB < 0) StepB = i; else return false; break; + default: return false; + } + } + if (Load < 0 || Store < 0 || StepB < 0 || Store < Load) { + return false; + } + const uint8_t S = D[Load].Base, Dst = D[Store].Base, T = D[Load].Reg, C = D[4].Reg; + if (D[Store].Reg != T || S == Dst || T == S || T == Dst || C == S || C == Dst || C == T) { + return false; + } + // One step per pointer, the source's after the load, the destination's after the store. + int StepS = D[StepA].Reg == S ? StepA : D[StepB].Reg == S ? StepB : -1; + int StepD = D[StepA].Reg == Dst ? StepA : D[StepB].Reg == Dst ? StepB : -1; + if (StepS < 0 || StepD < 0 || StepS == StepD || StepS < Load || StepD < Store) { + return false; + } + // The load must read S before its step; the store must write D before its step (checked above), and + // the store must come after the load that produced T. + Out->Src = S; + Out->Dst = Dst; + Out->Count = C; + Out->Byte = T; + return true; +} + +void OpDispatchBuilder::EmitByteCopyLoop(const ByteCopyLoop& Loop, X86Tables::DecodedOp Jcc) { + BlockSetRIP = true; + + Ref Src = LoadGPRRegister(Loop.Src); + Ref Dst = LoadGPRRegister(Loop.Dst); + Ref Count = LoadGPRRegister(Loop.Count); + + Ref Result_Src = _AllocateGPR(false); + Ref Result_Dst = _AllocateGPR(false); + _MemCpy(false, OpSize::i8Bit, Dst, Src, Count, Constant(1), Result_Dst, Result_Src); + + // The last byte copied: Dst[n-1] after the copy (n == 0: Src[0], see above). + Ref LastAddr = _Sub(OpSize::i64Bit, _Add(OpSize::i64Bit, Dst, Count), Constant(1)); + LastAddr = _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Count, Constant(0), Src, LastAddr); + Ref Byte = _LoadMem(RegClass::GPR, OpSize::i8Bit, LastAddr, Invalid(), OpSize::i8Bit, MemOffsetType::SXTX, 1); + + StoreGPRRegister(Loop.Byte, Byte); + StoreGPRRegister(Loop.Src, Result_Src); + StoreGPRRegister(Loop.Dst, Result_Dst); + StoreGPRRegister(Loop.Count, Constant(0)); + + // Flags of the final `sub Count, 1` (1 - 1). + CalculateFlags_SUB(OpSize::i64Bit, Constant(1), Constant(1)); + CalculateDeferredFlags(); + + FlushRegisterCache(); + const uint64_t Next = Jcc->PC + Jcc->InstSize; + if (auto Fall = JumpTargets.find(Next); Fall != JumpTargets.end()) { + Jump(Fall->second.BlockEntry); + } else { + ExitRelocatedPC(Jcc); + } +} +} // namespace FEXCore::IR diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h index 621ec1a3dd..30c09c2675 100644 --- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h @@ -437,6 +437,13 @@ class OpDispatchBuilder final : public IREmitter { void IMULOp(OpcodeArgs); void STOSOp(OpcodeArgs); void MOVSOp(OpcodeArgs); + // madeira-duo byte-copy-loop (OpcodeDispatcher.cpp): a whole guest block that copies + // one byte per iteration, replaced by one forward MemCpy. + struct ByteCopyLoop { + uint8_t Src, Dst, Count, Byte; + }; + static bool MatchByteCopyLoop(const X86Tables::DecodedInst* Insts, size_t NumInsts, uint64_t Entry, ByteCopyLoop* Out); + void EmitByteCopyLoop(const ByteCopyLoop& Loop, X86Tables::DecodedOp Jcc); void CMPSOp(OpcodeArgs); void LODSOp(OpcodeArgs); void SCASOp(OpcodeArgs); diff --git a/FEXCore/include/FEXCore/Core/CoreState.h b/FEXCore/include/FEXCore/Core/CoreState.h index bd11b42ca8..b9cfb44d30 100644 --- a/FEXCore/include/FEXCore/Core/CoreState.h +++ b/FEXCore/include/FEXCore/Core/CoreState.h @@ -517,6 +517,10 @@ struct CpuStateFrame { #if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec) extern uint32_t IosGuestBranchTraceEnabled; +/* madeira-duo jit-map (MADEIRA_JITMAP): called under the code buffer write lock for + * every block placed in the code buffer (host begin, host size, guest entry RIP, + * guest size), and with guest RIP 0 when the code cache is cleared. Null = off. */ +extern void (*MadeiraJitMapHook)(uint64_t HostBegin, uint64_t HostSize, uint64_t GuestRIP, uint64_t GuestSize); static_assert(sizeof(CpuStateFrame::IosGuestBranchHistoryType) == 272); static_assert(offsetof(CpuStateFrame, IosGuestBranchHistory) % 8 == 0); static_assert(offsetof(CpuStateFrame, IosGuestBranchHistory) + 272 <= 32760); diff --git a/FEXCore/include/FEXCore/Utils/WritePriorityMutex.h b/FEXCore/include/FEXCore/Utils/WritePriorityMutex.h index c4a6dd4a66..ecc2495bda 100644 --- a/FEXCore/include/FEXCore/Utils/WritePriorityMutex.h +++ b/FEXCore/include/FEXCore/Utils/WritePriorityMutex.h @@ -24,6 +24,70 @@ namespace FEXCore::Utils::WritePriorityMutex { +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) +/* MADEIRA: contention counters for one mutex (attached to CodeInvalidationMutex, see ContextImpl), + * reported from unlock() about every 30 s: exclusive acquisitions, exclusive hold time (and the longest + * hold), shared acquisitions that could not take the lock at once and how long they waited, and the + * same for exclusive acquisitions. The uncontended paths only pay a null check, the exclusive path two + * counter reads. Times are counter-register ticks (cntvct_el0), never a library clock (ml1059). */ +struct IosContentionStats { + const char* Name {}; + std::atomic ExclusiveAcquisitions {}; + std::atomic ExclusiveHoldTicks {}; + std::atomic ExclusiveMaxHoldTicks {}; + std::atomic ReaderBlocks {}; + std::atomic ReaderBlockedTicks {}; + std::atomic WriterWaits {}; + std::atomic WriterWaitTicks {}; + std::atomic LastReportTicks {}; + // Values at the last report; touched only by the thread that won LastReportTicks. + uint64_t Reported[7] {}; + + static uint64_t Now() { + uint64_t Ticks; + __asm volatile("mrs %0, cntvct_el0" : "=r"(Ticks)); + return Ticks; + } + static uint64_t Frequency() { + uint64_t Hz; + __asm volatile("mrs %0, cntfrq_el0" : "=r"(Hz)); + return Hz; + } + + void MaybeReport(uint64_t NowTicks) { + uint64_t Last = LastReportTicks.load(std::memory_order_relaxed); + const uint64_t Hz = Frequency(); + if (Last == 0) { + LastReportTicks.compare_exchange_strong(Last, NowTicks, std::memory_order_relaxed); + return; + } + if (NowTicks - Last < Hz * 30 || !LastReportTicks.compare_exchange_strong(Last, NowTicks, std::memory_order_relaxed)) { + return; + } + const uint64_t Values[7] = { + ExclusiveAcquisitions.load(std::memory_order_relaxed), ExclusiveHoldTicks.load(std::memory_order_relaxed), + ReaderBlocks.load(std::memory_order_relaxed), ReaderBlockedTicks.load(std::memory_order_relaxed), + WriterWaits.load(std::memory_order_relaxed), WriterWaitTicks.load(std::memory_order_relaxed), + ExclusiveMaxHoldTicks.exchange(0, std::memory_order_relaxed), + }; + const double Seconds = double(NowTicks - Last) / double(Hz); + const auto PerSecond = [&](int i) { + return double(Values[i] - Reported[i]) / Seconds; + }; + const auto MsPerSecond = [&](int i) { + return double(Values[i] - Reported[i]) * 1000.0 / double(Hz) / Seconds; + }; + LogMan::Msg::EFmt("[fexlock-stats] {} over {:.1f}s: exclusive {:.1f}/s hold {:.2f} ms/s (max {:.2f} ms), " + "reader-blocked {:.2f} ms/s ({:.1f}/s), writer-wait {:.2f} ms/s ({:.1f}/s)", + Name ? Name : "mutex", Seconds, PerSecond(0), MsPerSecond(1), double(Values[6]) * 1000.0 / double(Hz), + MsPerSecond(3), PerSecond(2), MsPerSecond(5), PerSecond(4)); + for (int i = 0; i < 6; i++) { + Reported[i] = Values[i]; + } + } +}; +#endif + // A custom mutex that prioritizes exclusive locks. // In highly contested scenarios, this can help minimize overall contention time. // @@ -61,6 +125,57 @@ class Mutex final { return; } +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) + if (Stats) { + const uint64_t Start = IosContentionStats::Now(); + lock_slow(); + Stats->WriterWaits.fetch_add(1, std::memory_order_relaxed); + Stats->WriterWaitTicks.fetch_add(IosContentionStats::Now() - Start, std::memory_order_relaxed); + return; + } +#endif + lock_slow(); + } + + void lock_shared() { + /* iOS-Madeira ml442 (#74 ROOT FIX): the class forbids recursive locking, + * but the invalidation paths hold this WRITE-locked while a fault taken + * on the same thread re-enters the compiler, which asks for SHARED — the + * thread then parks forever behind itself (ml441 run: tid 00e4 write-owned + * 0x7ca7173500 and read-waited on it; the whole webhelper cascaded behind + * that one park). A write owner already has exclusive access, which is a + * strict superset of shared — grant it with a nest counter instead. */ + if (IosWriterSelfShared()) { + return; + } + + // Try an uncontended lock first. + if (try_lock_shared()) { + return; + } + +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) + if (Stats) { + const uint64_t Start = IosContentionStats::Now(); + lock_shared_slow(); + Stats->ReaderBlocks.fetch_add(1, std::memory_order_relaxed); + Stats->ReaderBlockedTicks.fetch_add(IosContentionStats::Now() - Start, std::memory_order_relaxed); + return; + } +#endif + lock_shared_slow(); + } + +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) + /* MADEIRA: attach contention counters (see IosContentionStats). Set once, before the mutex is used. */ + void IosSetContentionStats(IosContentionStats* NewStats) { + Stats = NewStats; + } +#endif + +private: + // lock() after its non-blocking attempt failed. + void lock_slow() { // Try a quick WFE write-lock. if (Attempt_WFE_WriteLock()) { NoteWriteAcquired(); @@ -134,23 +249,8 @@ class Mutex final { } } - void lock_shared() { - /* iOS-Madeira ml442 (#74 ROOT FIX): the class forbids recursive locking, - * but the invalidation paths hold this WRITE-locked while a fault taken - * on the same thread re-enters the compiler, which asks for SHARED — the - * thread then parks forever behind itself (ml441 run: tid 00e4 write-owned - * 0x7ca7173500 and read-waited on it; the whole webhelper cascaded behind - * that one park). A write owner already has exclusive access, which is a - * strict superset of shared — grant it with a nest counter instead. */ - if (IosWriterSelfShared()) { - return; - } - - // Try an uncontended lock first. - if (try_lock_shared()) { - return; - } - + // lock_shared() after its non-blocking attempt failed. + void lock_shared_slow() { // Try a quick WFE read-lock. if (Attempt_WFE_ReadLock()) { return; @@ -196,6 +296,7 @@ class Mutex final { } } +public: void unlock() { auto AtomicFutex = std::atomic_ref(Futex); @@ -227,6 +328,13 @@ class Mutex final { // Handle write-reader handoff. FutexWakeReaders(); } + +#if defined(_WIN32) && defined(ARCHITECTURE_arm64) + // MADEIRA: after the release, so the log write never extends a hold. + if (Stats) { + Stats->MaybeReport(IosContentionStats::Now()); + } +#endif } void unlock_shared() { @@ -586,6 +694,11 @@ class Mutex final { /* MADEIRA: return addresses of the write owner's frames when it took the lock, so a stuck * waiter can say which path holds it. */ uint64_t OwnerRa[4] {}; +#if defined(ARCHITECTURE_arm64) + /* MADEIRA: contention counters, null unless attached; when the current exclusive hold began. */ + IosContentionStats* Stats {}; + uint64_t ExclusiveSinceTicks {}; +#endif /* Walks the frame-record chain from the caller's frame. ARM64EC maps the guest's RBP to x29, * so a host function called from JIT code saved a guest value as its parent frame: stop at @@ -609,6 +722,12 @@ class Mutex final { } void NoteWriteAcquired() { +#if defined(ARCHITECTURE_arm64) + if (Stats) { + ExclusiveSinceTicks = IosContentionStats::Now(); + Stats->ExclusiveAcquisitions.fetch_add(1, std::memory_order_relaxed); + } +#endif uint64_t Teb = 0; #ifdef ARCHITECTURE_arm64 __asm volatile("mov %0, x18" : "=r"(Teb)); @@ -624,6 +743,16 @@ class Mutex final { } void NoteWriteReleased() { +#if defined(ARCHITECTURE_arm64) + if (Stats && ExclusiveSinceTicks) { + const uint64_t Held = IosContentionStats::Now() - ExclusiveSinceTicks; + ExclusiveSinceTicks = 0; + Stats->ExclusiveHoldTicks.fetch_add(Held, std::memory_order_relaxed); + if (Held > Stats->ExclusiveMaxHoldTicks.load(std::memory_order_relaxed)) { + Stats->ExclusiveMaxHoldTicks.store(Held, std::memory_order_relaxed); + } + } +#endif if (OwnerSharedNest) { /* Badly-nested release order (write-unlock before nested shared-unlock). * Scoped RAII guards can't produce this; log loudly if something does. */ diff --git a/Source/Windows/ARM64EC/IosJitAlias.cpp b/Source/Windows/ARM64EC/IosJitAlias.cpp index 892901aa85..44c0a99818 100644 --- a/Source/Windows/ARM64EC/IosJitAlias.cpp +++ b/Source/Windows/ARM64EC/IosJitAlias.cpp @@ -70,6 +70,47 @@ void WidenJitBounds(uint64_t JitBase, uint64_t Size) { !__atomic_compare_exchange_n(&g_JitHigh, &High, JitBase + Size, true, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) { } } + +/* madeira-duo (5 Nov 2026): a per-page answer cache for IosJitReverseTranslate. + * + * Guest PE images sit inside [g_JitLow, g_JitHigh), so the bounds test above lets + * PoE2's own exe addresses through and every one of them walked all ~160 entries to + * answer "not an alias" (CompileBlock, QueryGuestExecutableRange, IsHotSMCCodePage and + * LookupExecutableFileSection all ask): 7.5% of the process's CPU, 16% of its Main + * thread, in the [prof] capture of 5 Nov. + * + * Keyed by 64 KB chunk, not page: PoE2's 49 MB of code is ~750 chunks, so its whole + * text fits the 4096 slots (a page key thrashed past ~4000 pages and was slower than + * the walk). One 64-bit word per slot, so a reader never sees a torn answer: + * bits 63..33 chunk (Addr >> 16; user addresses are below 2^47) + * bits 32..9 table generation (low 24 bits) + * bits 8..1 entry index (a hit) + * bit 0 1 = hit, 0 = no entry touches this chunk + * g_AliasGen is a sequence count: BTCpu64IosAddAliasMapping makes it odd before it + * changes the table and even again after, so a cached answer from an older table never + * matches, and a reader that raced a change takes the walk instead. A hit is re-checked + * against its entry every time, so a retired or reused slot can never give a wrong + * address. */ +constexpr int kRevCacheBits = 12; +uint64_t g_RevCache[1 << kRevCacheBits]; +uint64_t g_AliasGen = 0; + +constexpr int kRevChunkShift = 16; + +uint64_t RevCacheKey(uint64_t Chunk, uint64_t Gen) { + return (Chunk << 33) | ((Gen & 0xffffff) << 9); +} + +/* Brackets every change BTCpu64IosAddAliasMapping makes to the table. */ +struct AliasWriteScope { + AliasWriteScope() { + __atomic_fetch_add(&g_AliasGen, 1, __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_SEQ_CST); + } + ~AliasWriteScope() { + __atomic_fetch_add(&g_AliasGen, 1, __ATOMIC_RELEASE); + } +}; } // namespace extern "C" { @@ -420,6 +461,7 @@ void BTCpu64IosAddAliasMapping(uint64_t PeBase, uint64_t JitBase, uint64_t Size) } WidenJitBounds(JitBase, Size); + const AliasWriteScope WriteScope; // Retire every entry whose PE range overlaps the incoming image: a live // image proves any overlapping entry is dead (two images cannot share a VA). @@ -485,13 +527,56 @@ uint64_t IosJitReverseTranslate(uint64_t Addr) { if (Addr < __atomic_load_n(&g_JitLow, __ATOMIC_ACQUIRE) || Addr >= __atomic_load_n(&g_JitHigh, __ATOMIC_ACQUIRE)) { return Addr; } + const uint64_t Gen = __atomic_load_n(&g_AliasGen, __ATOMIC_ACQUIRE); + const uint64_t Chunk = Addr >> kRevChunkShift; + const bool Cacheable = (Gen & 1) == 0 && Chunk < (1ULL << 31); + uint64_t* const Slot = &g_RevCache[(Chunk ^ (Chunk >> kRevCacheBits)) & ((1 << kRevCacheBits) - 1)]; + const uint64_t Key = RevCacheKey(Chunk, Gen); + + if (Cacheable) { + const uint64_t Cached = __atomic_load_n(Slot, __ATOMIC_RELAXED); + if ((Cached & ~0x1ffULL) == Key) { + if ((Cached & 1) == 0) { + return Addr; + } + const IosAliasEntry& Entry = g_Entries[(Cached >> 1) & 0xff]; + const uint64_t EntrySize = __atomic_load_n(&Entry.Size, __ATOMIC_ACQUIRE); + const uint64_t EntryJitBase = __atomic_load_n(&Entry.JitBase, __ATOMIC_RELAXED); + const uint64_t EntryPeBase = __atomic_load_n(&Entry.PeBase, __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (EntrySize != 0 && Addr >= EntryJitBase && Addr - EntryJitBase < EntrySize && + __atomic_load_n(&g_AliasGen, __ATOMIC_RELAXED) == Gen) { + return EntryPeBase + (Addr - EntryJitBase); + } + } + } + + const uint64_t ChunkStart = Chunk << kRevChunkShift; + const uint64_t ChunkEnd = ChunkStart + (1ULL << kRevChunkShift); + bool ChunkTouched = false; int count = g_EntryCount; for (int i = 0; i < count; i++) { uint64_t jb = g_Entries[i].JitBase; uint64_t sz = g_Entries[i].Size; if (Addr >= jb && Addr < jb + sz) { + if (Cacheable) { + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (__atomic_load_n(&g_AliasGen, __ATOMIC_RELAXED) == Gen) { + __atomic_store_n(Slot, Key | ((uint64_t)i << 1) | 1, __ATOMIC_RELAXED); + } + } return g_Entries[i].PeBase + (Addr - jb); } + if (sz && jb < ChunkEnd && ChunkStart < jb + sz) { + ChunkTouched = true; + } + } + /* "No entry" is cached only for a chunk no entry touches, so it holds for every address in it. */ + if (Cacheable && !ChunkTouched) { + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (__atomic_load_n(&g_AliasGen, __ATOMIC_RELAXED) == Gen) { + __atomic_store_n(Slot, Key, __ATOMIC_RELAXED); + } } return Addr; } diff --git a/Source/Windows/ARM64EC/Module.cpp b/Source/Windows/ARM64EC/Module.cpp index 2a76ec203f..0d345b94dc 100644 --- a/Source/Windows/ARM64EC/Module.cpp +++ b/Source/Windows/ARM64EC/Module.cpp @@ -935,6 +935,94 @@ static bool IosSmcStoreFastPath(FEXCore::Core::InternalThreadState* Thread, ARM6 /* madeira-bcd: guest branch history v1. DATA, never a native-callable thunk. */ /* Keep a word-sized global, matching the module's iOS relocation guards. */ namespace FEXCore::Core { uint32_t IosGuestBranchTraceEnabled = 0; } +/* madeira-duo jit-map. Madeira's CPU sampler sees host PCs; inside JIT code a + * host PC says nothing about the game until it is mapped back to the guest + * code that was compiled there. With MADEIRA_JITMAP= set, that executable writes one 32-byte record per block placed + * in the code buffer to %LOCALAPPDATA%\fex-jitmap-.bin: + * u64 host begin, u64 guest entry RIP, u32 host size, u32 guest size, u32 ms, u32 seq + * A record with guest RIP 0 marks a code cache clear (host addresses are reused + * after it). The hook runs under the code buffer write lock, so writes are + * serialised; the stream is flushed every 2048 records. */ +namespace FEXCore::Core { void (*MadeiraJitMapHook)(uint64_t, uint64_t, uint64_t, uint64_t) = nullptr; } +namespace { +FILE* MadeiraJitMapFile; +uint32_t MadeiraJitMapSeq; +/* MADEIRA_JITCODE=[,...], each "0x" or "+0x" + * (module looked up once at start, so it must already be loaded): blocks compiled + * at those guest entries also get their host code bytes written, after a copy of + * their jit-map record, to %LOCALAPPDATA%\fex-jitcode-.bin. For reading + * what the profile's hot host offsets inside a block actually execute. */ +FILE* MadeiraJitCodeFile; +uint64_t MadeiraJitCodeRIPs[128]; /* madeira-duo: was 16; the hottest functions of a whole profile in one run */ +uint32_t MadeiraJitCodeCount; +void MadeiraJitMapWrite(uint64_t HostBegin, uint64_t HostSize, uint64_t GuestRIP, uint64_t GuestSize) { + struct { + uint64_t HostBegin, GuestRIP; + uint32_t HostSize, GuestSize, Ms, Seq; + } Record {HostBegin, GuestRIP, static_cast(HostSize), static_cast(GuestSize), + static_cast(GetTickCount64()), MadeiraJitMapSeq++}; + fwrite(&Record, sizeof(Record), 1, MadeiraJitMapFile); + if (GuestRIP && MadeiraJitCodeFile) { + for (uint32_t Idx = 0; Idx != MadeiraJitCodeCount; ++Idx) { + if (MadeiraJitCodeRIPs[Idx] == GuestRIP) { + fwrite(&Record, sizeof(Record), 1, MadeiraJitCodeFile); + fwrite(reinterpret_cast(HostBegin), 1, static_cast(HostSize), MadeiraJitCodeFile); + fflush(MadeiraJitCodeFile); + break; + } + } + } + if (!GuestRIP) { + LogMan::Msg::IFmt("[jit-map] madeira-duo code cache cleared (new buffer {}) after {} records", HostSize, MadeiraJitMapSeq); + } + if (!GuestRIP || (MadeiraJitMapSeq & 2047) == 0) { + fflush(MadeiraJitMapFile); + } +} +void MadeiraJitMapInit(const fextl::string& ExecutableName) { + const char* Want = getenv("MADEIRA_JITMAP"); + const char* AppData = getenv("LOCALAPPDATA"); + if (!Want || !Want[0] || !AppData || !strstr(ExecutableName.c_str(), Want)) { + return; + } + const auto Path = fextl::fmt::format("{}\\fex-jitmap-{}.bin", AppData, GetCurrentProcessId()); + MadeiraJitMapFile = fopen(Path.c_str(), "wb"); + if (MadeiraJitMapFile) { + setvbuf(MadeiraJitMapFile, nullptr, _IOFBF, 1 << 18); + FEXCore::Core::MadeiraJitMapHook = MadeiraJitMapWrite; + } + LogMan::Msg::IFmt("[jit-map] madeira-duo MADEIRA_JITMAP={} exe={}: {} {}", Want, ExecutableName, + MadeiraJitMapFile ? "writing" : "COULD NOT OPEN", Path); + const char* CodeWant = getenv("MADEIRA_JITCODE"); + if (!MadeiraJitMapFile || !CodeWant || !CodeWant[0]) { + return; + } + for (const char* Entry = CodeWant; *Entry && MadeiraJitCodeCount < 128;) { + const char* End = strchr(Entry, ','); + const fextl::string Item(Entry, End ? End - Entry : strlen(Entry)); + const auto Plus = Item.find('+'); + uint64_t RIP = 0; + if (Plus == fextl::string::npos) { + RIP = strtoull(Item.c_str(), nullptr, 16); + } else { + const auto Base = reinterpret_cast(GetModuleHandleA(Item.substr(0, Plus).c_str())); + RIP = Base ? Base + strtoull(Item.c_str() + Plus + 1, nullptr, 16) : 0; + } + LogMan::Msg::IFmt("[jit-map] madeira-duo MADEIRA_JITCODE {} -> {:#x}", Item, RIP); + if (RIP) { + MadeiraJitCodeRIPs[MadeiraJitCodeCount++] = RIP; + } + Entry = End ? End + 1 : Entry + Item.size(); + } + const auto CodePath = fextl::fmt::format("{}\\fex-jitcode-{}.bin", AppData, GetCurrentProcessId()); + if (MadeiraJitCodeCount) { + MadeiraJitCodeFile = fopen(CodePath.c_str(), "wb"); + } + LogMan::Msg::IFmt("[jit-map] madeira-duo MADEIRA_JITCODE {} entries: {} {}", MadeiraJitCodeCount, + MadeiraJitCodeFile ? "writing" : "not writing", CodePath); +} +} // namespace extern "C" const uint64_t IosGuestBranchTraceLayout[3] = { 0x314744454742444dULL, offsetof(FEXCore::Core::CpuStateFrame, IosGuestBranchHistory) | @@ -991,6 +1079,7 @@ NTSTATUS ProcessInit() { FEX::Windows::Logging::Init(); #ifdef FEX_IOS_HOST + MadeiraJitMapInit(fextl::string {ExecutableName}); // madeira-duo jit-map /* Recorder emitted only for this executable, before CTX/JIT creation. */ const auto HistoryName = fextl::string {ExecutableName}; const char* HistoryOpt = getenv("MADEIRA_FEX_BRANCH_HISTORY"); diff --git a/Source/Windows/Common/InvalidationTracker.cpp b/Source/Windows/Common/InvalidationTracker.cpp index 09149a6aaa..e740d6b3ec 100644 --- a/Source/Windows/Common/InvalidationTracker.cpp +++ b/Source/Windows/Common/InvalidationTracker.cpp @@ -45,6 +45,18 @@ uint64_t InvalidationTracker::OwnedSharedMutex::Self() { static std::atomic NestedNotificationSkips {0}; static std::atomic NestedNotificationSkipsReported {0}; +// madeira-duo: MADEIRA_FEX_FREE_SKIP=0 turns off the skip for frees of never-executable memory in +// InvalidateAlignedInterval (and the cached-page bounds check in LookupCache). Read once. +static bool FreeSkipEnabled() { + static const bool Enabled = [] { + const char* Env = getenv("MADEIRA_FEX_FREE_SKIP"); + const bool On = !(Env && Env[0] == '0'); + LogMan::Msg::EFmt("[iOS-xrem] free-skip={} (MADEIRA_FEX_FREE_SKIP={})", On ? 1 : 0, Env ? Env : "unset"); + return On; + }(); + return Enabled; +} + #if !defined(ARCHITECTURE_arm64ec) InvalidationTracker::InvalidationTracker(FEXCore::Context::Context& CTX, const std::unordered_map& Threads, uint64_t GuestBase) @@ -458,6 +470,30 @@ InvalidationTracker::InvalidateContainingSectionResult InvalidationTracker::Inva SectionSize += Info.RegionSize; } + /* madeira-duo: Path of Exile 2 streams assets through file views and unmaps ~60 a + * second (4 Nov logs: ~23,000 "[iOS-xrem] via=section" lines in a 6-minute run). Each + * unmap took the exclusive code-invalidation lock, walked every thread's lookup cache + * and wrote a log line, for data that was never executable. Nothing is compiled from a + * range outside XIntervals (code is only translated from executable memory, and + * removing a range from XIntervals invalidates it first), so such a section has nothing + * to invalidate. Executable sections take the full path as before. */ + if (Free) { + bool Executable; + { + std::unique_lock Lock(IntervalsLock); + Executable = XIntervals.Intersect({SectionBase, SectionBase + SectionSize}); + } + if (!Executable) { + static std::atomic DataUnmaps; + const auto N = DataUnmaps.fetch_add(1, std::memory_order_relaxed) + 1; + if (N <= 8 || !(N & 1023)) { + LogMan::Msg::EFmt("[iOS-xrem] via=section-data #{} {:#x}-{:#x}: never executable, no invalidation", N, SectionBase, + SectionBase + SectionSize); + } + return {SectionBase, SectionSize}; + } + } + InvalidateIntervalInternal(SectionBase, SectionSize); if (Free) { @@ -486,6 +522,46 @@ void InvalidationTracker::InvalidateAlignedInterval(uint64_t Address, uint64_t S const auto AlignedBase = Address & FEXCore::Utils::FEX_PAGE_MASK; const auto AlignedSize = std::max(Size, (Address - AlignedBase + Size + FEXCore::Utils::FEX_PAGE_SIZE - 1) & FEXCore::Utils::FEX_PAGE_MASK); + /* madeira-duo: every guest VirtualFree/decommit lands here (NotifyMemoryFree), about 49 a second in + * a PoE2 run (dig2 C1), nearly all of it heap data. Each took the exclusive code-invalidation lock and + * walked every thread's lookup cache while frame threads that missed L1 queued behind it. The rule + * InvalidateContainingSection already uses for unmapped sections applies here: nothing is compiled + * from outside XIntervals, and a range leaves XIntervals only after it is invalidated, so a freed range + * that overlaps no X interval has nothing to invalidate. A range that touches a sub-floor image's + * window (either of its names, ml1207) takes the full path regardless. MADEIRA_FEX_FREE_SKIP=0 turns + * the skip off. */ + if (Free && FreeSkipEnabled()) { + const uint64_t End = AlignedSize > std::numeric_limits::max() - AlignedBase ? std::numeric_limits::max() + : AlignedBase + AlignedSize; + bool Executable; + { + std::unique_lock Lock(IntervalsLock); + Executable = XIntervals.Intersect({AlignedBase, End}); + } +#if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec) + uint64_t Low, Real, WinSize; + for (int i = 0; !Executable && IosSubfloorEnum(i, &Low, &Real, &WinSize); i++) { + if (WinSize && ((AlignedBase < Low + WinSize && End > Low) || (Real && AlignedBase < Real + WinSize && End > Real))) { + Executable = true; + } + } +#endif + if (!Executable) { + static std::atomic DataFrees; + const auto N = DataFrees.fetch_add(1, std::memory_order_relaxed) + 1; + if (N <= 40 || !(N & 63)) { + LogMan::Msg::EFmt("[iOS-xrem] via=free-data #{} tracker={} {:#x}-{:#x}: never executable, no invalidation", N, + static_cast(this), AlignedBase, End); + } + // Nothing to remove from XIntervals; keep the rest of the bookkeeping as before (RWX ranges are a + // subset of X ranges, so this is a no-op in practice). + std::unique_lock Lock(IntervalsLock); + RWXIntervals.Remove({AlignedBase, End}); + ForgetHotSMCPages(AlignedBase, End); + return; + } + } + InvalidateIntervalInternal(AlignedBase, AlignedSize); if (Free) {