Moritz Angermann pushed to branch wip/angerman/rts-simd-memcmp at Glasgow Haskell Compiler / GHC Commits: a6692172 by Moritz Angermann at 2026-11-12T17:02:54-07:00 Provide RTS hs_memcmp and route MO_Memcmp to it musl libc implements memcmp as a scalar 1-byte loop, making large compareByteArrays# (ByteArray, ShortByteString, Data.Text) and C FFI memcmp calls ~21x slower than glibc on x86_64 and AArch64 Linux. This patch adds hs_memcmp to the RTS and lowers MO_Memcmp to it: - rts/HsMemcmp.c + rts/memcmp/memcmp-{x86_64,aarch64}.S: * On non-glibc Linux x86_64: SSE2 baseline with runtime-cached CPUID+XGETBV AVX2 fast path (4x32B loop + vzeroupper, no IFUNC), exposed internally as hidden hs_memcmp_simd. * On non-glibc Linux little-endian AArch64: ARMv8-A baseline NEON implementation (64B ldp q loop + cmeq/shrn nibble mask, no IFUNC). * On other non-glibc Linux architectures: strictly bounded 64-bit word-at-a-time fallback (memcpy loads + byte tail). * Elsewhere: returns 0 without dereferencing on n == 0 (avoiding ISO C nonnull UB on empty ByteArray# slices) and delegates to platform memcmp. * All SIMD and fallback reads are strictly bounded to [0, n). - rts/MuslMemcmp.c: provides a static-way (!DYNAMIC && !SHARED) memcmp forwarder to hs_memcmp in libHSrts*.a on non-glibc Linux so static C FFI callers (such as bytestring) resolve to hs_memcmp before libc.a without interposing dynamic shared libraries. - rts/include/rts/Utils.h, rts/RtsSymbols.c, rts/rts.cabal: declare, export, and wire hs_memcmp. - compiler/: route MO_Memcmp to hs_memcmp in the X86, AArch64, PPC, RV64, and LA64 NCGs and the LLVM backend (including Base.hs external declaration handling). The C, Wasm, and JS backends are unchanged. - testsuite/tests/primops/should_run/HsMemcmp: regression test covering compareByteArrays# (pinned/unpinned, unaligned offsets 0..31, sizes 0..65536, unsigned high-bit bytes, first/middle/last diffs) and the hs_memcmp FFI entry point. Measured on AMD Ryzen 5 3600 (x86_64 Linux, static musl vs glibc, 13,466 x 64 KiB comparisons, -O2): - ShortByteString (compareByteArrays# / MO_Memcmp): 299.35 ms (unpatched musl) -> 13.83 ms (patched musl), vs 13.78 ms glibc (21.6x speedup) - Data.ByteString (static memcmp -> hs_memcmp): 298.49 ms (unpatched musl) -> 14.15 ms (patched musl), vs 14.06 ms glibc (21.1x speedup) Inline small constant-size MO_Memcmp in the X86_64 and AArch64 NCGs: - New -fmax-inline-memcmp-insns=<n> flag (default 32, mirroring -fmax-inline-memcpy-insns/-fmax-inline-memset-insns), wired through DynFlags into NCGConfig (ncgInlineThresholdMemcmp) and documented in the user's guide. - X86_64 NCG: constant sizes lower inline (branchless single chunk for n = 1, 2, 4, 8 with byte-reversed unsigned comparison; an equality scan with one shared mismatch block for n = 3, 5..7 and n >= 9, all reads strictly within [0, n)). Multi-chunk sequences thread the X86 CFG explicitly, keeping -dasm-lint clean. Larger or dynamic sizes still call the RTS hs_memcmp. - AArch64 NCG: the same chunking lowered with LDR/REV/CSET/SUB, with register-offset loads for the at-most-one unaligned tail offset and no xzr/wzr references in pre-RA code. - LLVM backend: n == 0 stores 0 with no call; non-Linux targets and constant sizes 1..32 on Linux call "memcmp" so LLVM inlines them, while larger or dynamic sizes on Linux keep calling "hs_memcmp". - rts/HsMemcmp.c and rts/MuslMemcmp.c: exclude Android Bionic and uClibc from the non-glibc Linux override. - HsMemcmp test: constant-length compareByteArrays# coverage for 0..9, 12, 15..17, 24, 28, 31..33, 48 and 63..65 (INLINE wrappers so the NCG sees literal lengths), including back-to-back comparisons sharing one Cmm block. - - - - - 23 changed files: - compiler/GHC/CmmToAsm/AArch64/CodeGen.hs - compiler/GHC/CmmToAsm/Config.hs - compiler/GHC/CmmToAsm/LA64/CodeGen.hs - compiler/GHC/CmmToAsm/PPC/CodeGen.hs - compiler/GHC/CmmToAsm/RV64/CodeGen.hs - compiler/GHC/CmmToAsm/X86/CodeGen.hs - compiler/GHC/CmmToLlvm/Base.hs - compiler/GHC/CmmToLlvm/CodeGen.hs - compiler/GHC/Driver/Config/CmmToAsm.hs - compiler/GHC/Driver/DynFlags.hs - compiler/GHC/Driver/Session.hs - compiler/GHC/StgToCmm/Prim.hs - docs/users_guide/using-optimisation.rst - + rts/HsMemcmp.c - + rts/MuslMemcmp.c - rts/RtsSymbols.c - rts/include/rts/Utils.h - + rts/memcmp/memcmp-aarch64.S - + rts/memcmp/memcmp-x86_64.S - rts/rts.cabal - + testsuite/tests/primops/should_run/HsMemcmp.hs - + testsuite/tests/primops/should_run/HsMemcmp.stdout - testsuite/tests/primops/should_run/all.T Changes: ===================================== compiler/GHC/CmmToAsm/AArch64/CodeGen.hs ===================================== @@ -25,6 +25,7 @@ import GHC.CmmToAsm.Monad ( NatM, getNewRegNat , getPicBaseMaybeNat, getPlatform, getConfig , getDebugBlock, getFileId, getNewLabelNat, getThisModuleNat + , getBlockIdNat ) -- import GHC.CmmToAsm.Instr import GHC.CmmToAsm.PIC @@ -51,7 +52,7 @@ import GHC.Types.Unique.DSM import GHC.Data.OrdList import GHC.Utils.Outputable -import Control.Monad ( mapAndUnzipM ) +import Control.Monad ( mapAndUnzipM, replicateM ) import GHC.Float import GHC.Types.Basic @@ -2744,7 +2745,15 @@ genCCall target dest_regs arg_regs = do MO_Memcpy _align -> mkCCall "memcpy" MO_Memset _align -> mkCCall "memset" MO_Memmove _align -> mkCCall "memmove" - MO_Memcmp _align -> mkCCall "memcmp" + MO_Memcmp _align + | [p1, p2, CmmLit (CmmInt n _)] <- arg_regs + , [dst_reg] <- dest_regs + , n >= 0 -> do + mcode <- genMemCmpInlineMaybe dst_reg p1 p2 n + case mcode of + Just code -> return code + Nothing -> mkCCall "hs_memcmp" + | otherwise -> mkCCall "hs_memcmp" MO_SuspendThread -> mkCCall "suspendThread" MO_ResumeThread -> mkCCall "resumeThread" @@ -2976,6 +2985,151 @@ genCCall target dest_regs arg_regs = do let code = code_fx `appOL` op (OpReg w dst) (OpReg w reg_fx) return code +-- | Inline a constant-size memcmp. +-- +-- Unroll memcmp calls with a constant size when the generated pseudo +-- instructions fit under ncgInlineThresholdMemcmp, otherwise return +-- Nothing so the caller emits a call to the RTS hs_memcmp. +genMemCmpInlineMaybe + :: CmmFormal -> CmmActual -> CmmActual -> Integer -> NatM (Maybe InstrBlock) +genMemCmpInlineMaybe dst_reg p1 p2 n = do + config <- getConfig + platform <- getPlatform + let threshold = ncgInlineThresholdMemcmp config + isBE = platformByteOrder platform == BigEndian + res_r = getRegisterReg platform (CmmLocal dst_reg) + resFmt = cmmTypeFormat (cmmRegType (CmmLocal dst_reg)) + moveRes r32 + | resFmt == II64 = unitOL (SXTW (OpReg W64 res_r) (OpReg W32 r32)) + | otherwise = unitOL (MOV (OpReg W32 res_r) (OpReg W32 r32)) + revW w t + | isBE = nilOL + | otherwise = unitOL (REV (OpReg w t) (OpReg w t)) + if n == 0 + then + if 1 <= threshold + then return (Just (unitOL (MOV (OpReg W32 res_r) (OpImm (ImmInt 0))))) + else return Nothing + else if n == 1 + then + if 3 <= threshold + then do + (p1_r, _, code_p1) <- getSomeReg p1 + (p2_r, _, code_p2) <- getSomeReg p2 + t1 <- getNewRegNat II8 + t2 <- getNewRegNat II8 + r32 <- getNewRegNat II32 + let code = code_p1 `appOL` code_p2 `appOL` toOL + [ LDR II8 (OpReg W8 t1) (OpAddr (AddrReg p1_r)) + , LDR II8 (OpReg W8 t2) (OpAddr (AddrReg p2_r)) + , SUB II32 (OpReg W32 r32) (OpReg W32 t1) (OpReg W32 t2) + ] + `appOL` moveRes r32 + return (Just code) + else return Nothing + else if n == 2 || n == 4 || n == 8 + then + if 8 <= threshold + then do + (p1_r, _, code_p1) <- getSomeReg p1 + (p2_r, _, code_p2) <- getSomeReg p2 + let (loadFmt, chunkW) = case n of + 2 -> (II16, W32) + 4 -> (II32, W32) + _ -> (II64, W64) + t1 <- getNewRegNat loadFmt + t2 <- getNewRegNat loadFmt + hi <- getNewRegNat II32 + lo <- getNewRegNat II32 + r32 <- getNewRegNat II32 + let code = code_p1 `appOL` code_p2 `appOL` toOL + [ LDR loadFmt (OpReg chunkW t1) (OpAddr (AddrReg p1_r)) + , LDR loadFmt (OpReg chunkW t2) (OpAddr (AddrReg p2_r)) + ] + `appOL` revW chunkW t1 `appOL` revW chunkW t2 `appOL` toOL + [ CMP (OpReg chunkW t1) (OpReg chunkW t2) + , CSET (OpReg W32 hi) UGT + , CSET (OpReg W32 lo) ULT + , SUB II32 (OpReg W32 r32) (OpReg W32 hi) (OpReg W32 lo) + ] + `appOL` moveRes r32 + return (Just code) + else return Nothing + else do + let numChunks :: Integer + numChunks + | n == 3 = 2 + | n >= 5 && n <= 7 = 2 + | otherwise = (n + 7) `div` 8 + insns :: Integer + insns = 4 * numChunks + -- Compute chunk count in O(1) Integer arithmetic before constructing + -- offsets, and cap n <= 32768 so every aligned 8-byte chunk offset + -- (<= 32760) fits AArch64's 12-bit scaled unsigned LDR immediate. + if insns <= toInteger threshold && n <= 32768 + then do + let k = n `div` 8 + (loadFmt, chunkW, loadW, offsets) = case n of + 3 -> (II16, W32, W16, [0, 1]) + _ | n >= 5 && n <= 7 -> (II32, W32, W32, [0, n - 4]) + | otherwise -> (II64, W64, W64, [0, 8 .. (k - 1) * 8] ++ [n - 8 | n `mod` 8 /= 0]) + chunkBytes = toInteger (widthInBytes loadW) + canUseImm off = off `mod` chunkBytes == 0 && isOffsetImm (fromInteger off) loadW + (p1_r, _, code_p1) <- getSomeReg p1 + (p2_r, _, code_p2) <- getSomeReg p2 + t1 <- getNewRegNat loadFmt + t2 <- getNewRegNat loadFmt + hi <- getNewRegNat II32 + lo <- getNewRegNat II32 + r32 <- getNewRegNat II32 + lblDiff <- getBlockIdNat + lblEq <- getBlockIdNat + lblDone <- getBlockIdNat + nextLbls <- replicateM (length offsets - 1) getBlockIdNat + let lastOff = last offsets + needOffReg = not (canUseImm lastOff) + immAddr base off = OpAddr (AddrRegImm base (ImmInt (fromInteger off))) + (offCode, addr1, addr2) <- + if needOffReg + then do + (off_r, _, c) <- getSomeReg (CmmLit (CmmInt lastOff W64)) + let a1 off + | canUseImm off = immAddr p1_r off + | otherwise = OpAddr (AddrRegReg p1_r off_r) + a2 off + | canUseImm off = immAddr p2_r off + | otherwise = OpAddr (AddrRegReg p2_r off_r) + return (c, a1, a2) + else return (nilOL, immAddr p1_r, immAddr p2_r) + let nexts = nextLbls ++ [lblEq] + chunk off next = toOL + [ LDR loadFmt (OpReg chunkW t1) (addr1 off) + , LDR loadFmt (OpReg chunkW t2) (addr2 off) + , CMP (OpReg chunkW t1) (OpReg chunkW t2) + , BCOND NE (TBlock lblDiff) + , B (TBlock next) + , NEWBLOCK next + ] + chunks = concatOL [chunk off next | (off, next) <- zip offsets nexts] + code = code_p1 `appOL` code_p2 `appOL` offCode `appOL` chunks `appOL` toOL + [ MOV (OpReg W32 res_r) (OpImm (ImmInt 0)) + , B (TBlock lblDone) + , NEWBLOCK lblDiff + ] + `appOL` revW chunkW t1 `appOL` revW chunkW t2 `appOL` toOL + [ CMP (OpReg chunkW t1) (OpReg chunkW t2) + , CSET (OpReg W32 hi) UGT + , CSET (OpReg W32 lo) ULT + , SUB II32 (OpReg W32 r32) (OpReg W32 hi) (OpReg W32 lo) + ] + `appOL` moveRes r32 + `appOL` toOL + [ B (TBlock lblDone) + , NEWBLOCK lblDone + ] + return (Just code) + else return Nothing + {- Note [AArch64 far jumps] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ AArch conditional jump instructions can only encode an offset of +/-1MB ===================================== compiler/GHC/CmmToAsm/Config.hs ===================================== @@ -27,6 +27,7 @@ data NCGConfig = NCGConfig , ncgPIC :: !Bool -- ^ Enable Position-Independent Code , ncgInlineThresholdMemcpy :: !Word -- ^ If inlining `memcpy` produces less than this threshold (in pseudo-instruction unit), do it , ncgInlineThresholdMemset :: !Word -- ^ Ditto for `memset` + , ncgInlineThresholdMemcmp :: !Word -- ^ Ditto for `memcmp` , ncgSplitSections :: !Bool -- ^ Split sections , ncgRegsIterative :: !Bool , ncgRegsGraph :: !Bool ===================================== compiler/GHC/CmmToAsm/LA64/CodeGen.hs ===================================== @@ -1686,7 +1686,7 @@ genPrim (MO_Pext width) [dst] [src,mask] = genLibCCall (pextLabel wid genPrim (MO_UF_Conv width) [dst] [src] = genLibCCall (word2FloatLabel width) [dst] [src] genPrim (MO_Memcpy _align) [] [dst,src,n] = genLibCCall (fsLit "memcpy") [] [dst,src,n] genPrim (MO_Memmove _align) [] [dst,src,n] = genLibCCall (fsLit "memmove") [] [dst,src,n] -genPrim (MO_Memcmp _align) [rst] [dst,src,n] = genLibCCall (fsLit "memcmp") [rst] [dst,src,n] +genPrim (MO_Memcmp _align) [rst] [dst,src,n] = genLibCCall (fsLit "hs_memcmp") [rst] [dst,src,n] genPrim (MO_Memset _align) [] [dst,cnt,n] = genLibCCall (fsLit "memset") [] [dst,cnt,n] genPrim MO_F32_Sin [dst] [src] = genLibCCall (fsLit "sinf") [dst] [src] genPrim MO_F32_Cos [dst] [src] = genLibCCall (fsLit "cosf") [dst] [src] ===================================== compiler/GHC/CmmToAsm/PPC/CodeGen.hs ===================================== @@ -2144,7 +2144,7 @@ genCCall' config gcp target dest_regs args MO_Memcpy _ -> (fsLit "memcpy", False) MO_Memset _ -> (fsLit "memset", False) MO_Memmove _ -> (fsLit "memmove", False) - MO_Memcmp _ -> (fsLit "memcmp", False) + MO_Memcmp _ -> (fsLit "hs_memcmp", False) MO_SuspendThread -> (fsLit "suspendThread", False) MO_ResumeThread -> (fsLit "resumeThread", False) ===================================== compiler/GHC/CmmToAsm/RV64/CodeGen.hs ===================================== @@ -1816,7 +1816,7 @@ genCCall (PrimTarget mop) dest_regs arg_regs = do MO_Memcpy _align -> mkCCall "memcpy" MO_Memset _align -> mkCCall "memset" MO_Memmove _align -> mkCCall "memmove" - MO_Memcmp _align -> mkCCall "memcmp" + MO_Memcmp _align -> mkCCall "hs_memcmp" MO_SuspendThread -> mkCCall "suspendThread" MO_ResumeThread -> mkCCall "resumeThread" MO_PopCnt w -> mkCCall (popCntLabel w) ===================================== compiler/GHC/CmmToAsm/X86/CodeGen.hs ===================================== @@ -4340,6 +4340,8 @@ genPrim bid (MO_AtomicRMW width amop) [dst] [addr, n] = genAtomicRMW bid width amop dst addr n genPrim bid (MO_Ctz width) [dst] [src] = genCtz bid width dst src +genPrim bid (MO_Memcmp align) [res] [dst, src, n] + = genMemCmp bid align res dst src n -- Then we deal with cases which not introducing new blocks in the stream. genPrim bid prim dst args @@ -4353,7 +4355,6 @@ genSimplePrim -> NatM InstrBlock genSimplePrim bid (MO_Memcpy align) [] [dst,src,n] = genMemCpy bid align dst src n genSimplePrim bid (MO_Memmove align) [] [dst,src,n] = genMemMove bid align dst src n -genSimplePrim bid (MO_Memcmp align) [res] [dst,src,n] = genMemCmp bid align res dst src n genSimplePrim bid (MO_Memset align) [] [dst,c,n] = genMemSet bid align dst c n genSimplePrim _ MO_AcquireFence [] [] = return nilOL -- barriers compile to no code on x86/x86-64; genSimplePrim _ MO_ReleaseFence [] [] = return nilOL -- we keep it this long in order to prevent earlier optimisations. @@ -6638,11 +6639,157 @@ genMemMove bid _align dst src n = do -- memcpy and memset) genLibCCall bid (fsLit "memmove") [] [dst,src,n] -genMemCmp :: BlockId -> p -> CmmFormal -> CmmActual -> CmmActual -> CmmActual -> NatM InstrBlock -genMemCmp bid _align res dst src n = do - -- TODO: generate inline assembly when under a given threshold (similarly to - -- memcpy and memset) - genLibCCall bid (fsLit "memcmp") [res] [dst,src,n] +-- | Compare memory +-- +-- Unroll memcmp calls with a constant size when the generated pseudo +-- instructions fit under ncgInlineThresholdMemcmp. Otherwise call the +-- RTS hs_memcmp. See Note [Keeping track of the current block] for why +-- this returns the new block. +genMemCmp :: BlockId -> p -> CmmFormal -> CmmActual -> CmmActual -> CmmActual + -> NatM (InstrBlock, Maybe BlockId) +genMemCmp bid _align res dst src n_arg = do + is32Bit <- is32BitPlatform + case n_arg of + CmmLit (CmmInt n _) | not is32Bit, n >= 0 -> do + config <- getConfig + platform <- getPlatform + let threshold = ncgInlineThresholdMemcmp config + res_r = getRegisterReg platform (CmmLocal res) + resFmt = cmmTypeFormat (localRegType res) + fallback = (,Nothing) <$> genLibCCall bid (fsLit "hs_memcmp") [res] [dst,src,n_arg] + moveRes r32 + | resFmt == II64 = unitOL (MOVSxL II32 (OpReg r32) (OpReg res_r)) + | otherwise = unitOL (MOV II32 (OpReg r32) (OpReg res_r)) + if n == 0 + then + if 1 <= threshold + then return (unitOL (XOR II32 (OpReg res_r) (OpReg res_r)), Nothing) + else fallback + else if n == 1 + then + if 3 <= threshold + then do + code_p1 <- getAnyReg dst + p1_r <- getNewRegNat II64 + code_p2 <- getAnyReg src + p2_r <- getNewRegNat II64 + t1 <- getNewRegNat II32 + t2 <- getNewRegNat II32 + let code = code_p1 p1_r `appOL` code_p2 p2_r `appOL` toOL + [ MOVZxL II8 (OpAddr (AddrBaseIndex (EABaseReg p1_r) EAIndexNone (ImmInt 0))) (OpReg t1) + , MOVZxL II8 (OpAddr (AddrBaseIndex (EABaseReg p2_r) EAIndexNone (ImmInt 0))) (OpReg t2) + , SUB II32 (OpReg t2) (OpReg t1) + ] + `appOL` moveRes t1 + return (code, Nothing) + else fallback + else if n == 2 || n == 4 || n == 8 + then + if 8 <= threshold + then do + code_p1 <- getAnyReg dst + p1_r <- getNewRegNat II64 + code_p2 <- getAnyReg src + p2_r <- getNewRegNat II64 + let cmpFmt = if n == 8 then II64 else II32 + t1 <- getNewRegNat cmpFmt + t2 <- getNewRegNat cmpFmt + hi8 <- getNewRegNat II8 + lo8 <- getNewRegNat II8 + r32 <- getNewRegNat II32 + lo32 <- getNewRegNat II32 + let mkAddr base = OpAddr (AddrBaseIndex (EABaseReg base) EAIndexNone (ImmInt 0)) + load1 = case n of + 2 -> MOVZxL II16 (mkAddr p1_r) (OpReg t1) + 4 -> MOV II32 (mkAddr p1_r) (OpReg t1) + _ -> MOV II64 (mkAddr p1_r) (OpReg t1) + load2 = case n of + 2 -> MOVZxL II16 (mkAddr p2_r) (OpReg t2) + 4 -> MOV II32 (mkAddr p2_r) (OpReg t2) + _ -> MOV II64 (mkAddr p2_r) (OpReg t2) + code = code_p1 p1_r `appOL` code_p2 p2_r `appOL` toOL + [ load1 + , load2 + , BSWAP cmpFmt t1 + , BSWAP cmpFmt t2 + , CMP cmpFmt (OpReg t2) (OpReg t1) + , SETCC GU (OpReg hi8) + , SETCC LU (OpReg lo8) + , MOVZxL II8 (OpReg hi8) (OpReg r32) + , MOVZxL II8 (OpReg lo8) (OpReg lo32) + , SUB II32 (OpReg lo32) (OpReg r32) + ] + `appOL` moveRes r32 + return (code, Nothing) + else fallback + else do + let numChunks :: Integer + numChunks + | n == 3 = 2 + | n >= 5 && n <= 7 = 2 + | otherwise = (n + 7) `div` 8 + insns :: Integer + insns = 4 * numChunks + -- Compute chunk count in O(1) Integer arithmetic before building + -- offsets, and cap displacement at 32-bit signed immediate range. + if insns <= toInteger threshold && is32BitInteger n + then do + let k = n `div` 8 + (loadFmt, cmpFmt, offsets) = case n of + 3 -> (II16, II32, [0, 1]) + _ | n >= 5 && n <= 7 -> (II32, II32, [0, n - 4]) + | otherwise -> (II64, II64, [0, 8 .. (k - 1) * 8] ++ [n - 8 | n `mod` 8 /= 0]) + mkLoad off base tmp = case loadFmt of + II16 -> MOVZxL II16 (OpAddr (AddrBaseIndex (EABaseReg base) EAIndexNone (ImmInt (fromInteger off)))) (OpReg tmp) + II32 -> MOV II32 (OpAddr (AddrBaseIndex (EABaseReg base) EAIndexNone (ImmInt (fromInteger off)))) (OpReg tmp) + _ -> MOV II64 (OpAddr (AddrBaseIndex (EABaseReg base) EAIndexNone (ImmInt (fromInteger off)))) (OpReg tmp) + code_p1 <- getAnyReg dst + p1_r <- getNewRegNat II64 + code_p2 <- getAnyReg src + p2_r <- getNewRegNat II64 + t1 <- getNewRegNat cmpFmt + t2 <- getNewRegNat cmpFmt + r32 <- getNewRegNat II32 + one32 <- getNewRegNat II32 + lblDiff <- getBlockIdNat + lblEq <- getBlockIdNat + lblDone <- getBlockIdNat + nextLbls <- replicateM (length offsets - 1) getBlockIdNat + let blks = bid : nextLbls + nexts = tail blks ++ [lblEq] + chunk _blk nxt off = toOL + [ mkLoad off p1_r t1 + , mkLoad off p2_r t2 + , CMP cmpFmt (OpReg t2) (OpReg t1) + , JXX NE lblDiff + , JXX ALWAYS nxt + , NEWBLOCK nxt + ] + chunks = concatOL [chunk blk nxt off | ((blk, nxt), off) <- zip (zip blks nexts) offsets] + code = code_p1 p1_r `appOL` code_p2 p2_r `appOL` chunks `appOL` toOL + [ XOR II32 (OpReg res_r) (OpReg res_r) + , JXX ALWAYS lblDone + , NEWBLOCK lblDiff + , BSWAP cmpFmt t1 + , BSWAP cmpFmt t2 + , CMP cmpFmt (OpReg t2) (OpReg t1) + , MOV II32 (OpImm (ImmInt (-1))) (OpReg r32) + , MOV II32 (OpImm (ImmInt 1)) (OpReg one32) + , CMOV GU II32 (OpReg one32) r32 + ] + `appOL` moveRes r32 + `appOL` toOL + [ JXX ALWAYS lblDone + , NEWBLOCK lblDone + ] + addImmediateSuccessorNat bid lblDone + updateCfgNat $ \cfg -> + let cfg1 = delEdge bid lblDone cfg + cfg2 = foldr (\(blk, nxt) c -> addWeightEdge blk nxt 80 (addWeightEdge blk lblDiff 20 c)) cfg1 (zip blks nexts) + in addWeightEdge lblEq lblDone 100 (addWeightEdge lblDiff lblDone 100 cfg2) + return (code, Just lblDone) + else fallback + _ -> (,Nothing) <$> genLibCCall bid (fsLit "hs_memcmp") [res] [dst,src,n_arg] genPrefetchData :: Int -> CmmExpr -> NatM (OrdList Instr) genPrefetchData n src = do ===================================== compiler/GHC/CmmToLlvm/Base.hs ===================================== @@ -447,6 +447,7 @@ ghcInternalFunctions = do let w = llvmWord platform cint = LMInt $ widthInBits $ cIntWidth platform mk "memcmp" cint [i8Ptr, i8Ptr, w] + mk "hs_memcmp" cint [i8Ptr, i8Ptr, w] mk "memcpy" i8Ptr [i8Ptr, i8Ptr, w] mk "memmove" i8Ptr [i8Ptr, i8Ptr, w] mk "memset" i8Ptr [i8Ptr, w, w] @@ -486,7 +487,7 @@ getGlobalPtr llvmLbl = do case m_ty of -- Directly reference if we have seen it already Just ty -> do - if llvmLbl `elem` (map fsLit ["newSpark", "memmove", "memcpy", "memcmp", "memset"]) + if llvmLbl `elem` (map fsLit ["newSpark", "memmove", "memcpy", "memcmp", "hs_memcmp", "memset"]) then return $ mkGlbVar (llvmLbl) ty Global else return $ mkGlbVar (llvmDefLabel llvmLbl) ty Global -- Otherwise use a forward alias of it ===================================== compiler/GHC/CmmToLlvm/CodeGen.hs ===================================== @@ -269,6 +269,37 @@ genCall (PrimTarget op@(MO_Pext w)) [dst] args = do then genCallMinimumTruncationCast W32 w op dst args else genCallSimpleCast w op dst args +-- Route constant-size memcmp through "memcmp" (rather than the RTS +-- "hs_memcmp") when LLVM can inline and unroll it: all comparisons on +-- non-Linux platforms, and comparisons of 1 to 32 bytes on Linux. +-- A zero length stores 0 directly without any call. +genCall (PrimTarget (MO_Memcmp _)) [dst] [_p1, _p2, CmmLit (CmmInt 0 _)] = do + (dstV, dstTy) <- getCmmReg (CmmLocal dst) + return (unitOL (Store (mkIntLit dstTy 0) dstV Nothing []), []) +genCall (PrimTarget mop@(MO_Memcmp _)) [dst] [p1, p2, n] = do + platform <- getPlatform + let useMemcmp = platformOS platform /= OSLinux || + case n of + CmmLit (CmmInt k _) -> 1 <= k && k <= 32 + _ -> False + fname = if useMemcmp then fsLit "memcmp" else fsLit "hs_memcmp" + w = llvmWord platform + cint = LMInt (widthInBits (cIntWidth platform)) + argsW = [i8Ptr, i8Ptr, w] + dstType = cmmToLlvmType (localRegType dst) + signage = cmmPrimOpRetValSignage mop + (fptr, _, top3) <- getInstrinct fname cint argsW + (dstV, _dst_ty) <- getCmmReg (CmmLocal dst) + let (_, arg_hints) = foreignTargetHints (PrimTarget mop) + args_hints = zip [p1, p2, n] arg_hints + (argsV, stmts2, top2) <- arg_vars args_hints ([], nilOL, []) + (argsV', stmts4) <- castVars signage (zip argsV argsW) + (retV, s1) <- doExpr cint (Call StdCall fptr argsV' []) + (retV', stmts5) <- castVar signage retV dstType + let s2 = Store retV' dstV Nothing [] + stmts = stmts2 `appOL` stmts4 `snocOL` s1 `snocOL` stmts5 `snocOL` s2 + return (stmts, top2 ++ top3) + genCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = runStmtsDecls $ do addrVar <- exprToVarW addr nVar <- exprToVarW n @@ -928,7 +959,7 @@ cmmPrimOpFunctions mop = do MO_Memset _ | is32bit -> fsLit "llvm.memset.p0i8.i32" | otherwise -> fsLit "llvm.memset.p0i8.i64" - MO_Memcmp _ -> fsLit "memcmp" + MO_Memcmp _ -> fsLit "hs_memcmp" MO_SuspendThread -> fsLit "suspendThread" MO_ResumeThread -> fsLit "resumeThread" ===================================== compiler/GHC/Driver/Config/CmmToAsm.hs ===================================== @@ -24,6 +24,7 @@ initNCGConfig dflags this_mod = NCGConfig , ncgPIC = positionIndependent dflags , ncgInlineThresholdMemcpy = fromIntegral $ maxInlineMemcpyInsns dflags , ncgInlineThresholdMemset = fromIntegral $ maxInlineMemsetInsns dflags + , ncgInlineThresholdMemcmp = fromIntegral $ maxInlineMemcmpInsns dflags , ncgSplitSections = gopt Opt_SplitSections dflags , ncgRegsIterative = gopt Opt_RegsIterative dflags , ncgRegsGraph = gopt Opt_RegsGraph dflags ===================================== compiler/GHC/Driver/DynFlags.hs ===================================== @@ -463,6 +463,10 @@ data DynFlags = DynFlags { -- pseudo (roughly: Cmm) instructions. maxInlineMemsetInsns :: Int, + -- | Only inline memcmp if it generates no more than this many + -- pseudo (roughly: Cmm) instructions. + maxInlineMemcmpInsns :: Int, + -- | Reverse the order of error messages in GHC/GHCi reverseErrors :: Bool, @@ -734,6 +738,7 @@ defaultDynFlags mySettings = maxInlineAllocSize = 128, maxInlineMemcpyInsns = 32, maxInlineMemsetInsns = 32, + maxInlineMemcmpInsns = 32, initialUnique = 0, uniqueIncrement = 1, ===================================== compiler/GHC/Driver/Session.hs ===================================== @@ -1881,6 +1881,8 @@ dynamic_flags_deps = [ (intSuffix (\n d -> d { maxInlineMemcpyInsns = n })) , make_ord_flag defGhcFlag "fmax-inline-memset-insns" (intSuffix (\n d -> d { maxInlineMemsetInsns = n })) + , make_ord_flag defGhcFlag "fmax-inline-memcmp-insns" + (intSuffix (\n d -> d { maxInlineMemcmpInsns = n })) , make_ord_flag defGhcFlag "dinitial-unique" (word64Suffix (\n d -> d { initialUnique = n })) , make_ord_flag defGhcFlag "dunique-increment" ===================================== compiler/GHC/StgToCmm/Prim.hs ===================================== @@ -3651,8 +3651,9 @@ emitMemsetCall dst c n align = emitMemcmpCall :: LocalReg -> CmmExpr -> CmmExpr -> CmmExpr -> Int -> FCode () emitMemcmpCall res ptr1 ptr2 n align = do - -- 'MO_Memcmp' is assumed to return an 32bit 'CInt' because all - -- code-gens currently call out to the @memcmp(3)@ C function. + -- 'MO_Memcmp' is assumed to return an 32bit 'CInt' because NCG and LLVM + -- code-gens call the RTS @hs_memcmp@ function (while C and Wasm code-gens + -- call @__builtin_memcmp@ / @memcmp@), all with memcmp(3) return semantics. -- This was easier than moving the sign-extensions into -- all the code-gens. platform <- getPlatform ===================================== docs/users_guide/using-optimisation.rst ===================================== @@ -885,6 +885,19 @@ as such you shouldn't need to set any of them explicitly. A flag Inline ``memset`` calls if they would generate no more than n pseudo instructions. +.. ghc-flag:: -fmax-inline-memcmp-insns=⟨n⟩ + :shortdesc: *default: 32.* Inline ``memcmp`` calls whose heuristic scan cost + is no more than ⟨n⟩ pseudo instructions. + :type: dynamic + :category: + + :default: 32 + + Inline constant-size ``memcmp`` calls whose heuristic scan cost (roughly 4 + pseudo instructions per word-sized comparison chunk, excluding shared + result setup) is no more than ⟨n⟩ pseudo instructions. At the default of 32, + comparisons up to 64 bytes are unrolled inline. + .. ghc-flag:: -fmax-relevant-binds=⟨n⟩ :shortdesc: *default: 6.* Set the maximum number of bindings to display in type error messages. ===================================== rts/HsMemcmp.c ===================================== @@ -0,0 +1,114 @@ +/* ----------------------------------------------------------------------------- + * + * (c) 2026 Moritz Angermann <moritz.angermann@iohk.io>, Input Output Group + * + * SPDX-License-Identifier: BSD-3-Clause + * + * Fast memcmp for the GHC RTS. + * + * 'hs_memcmp' has memcmp(3) semantics: it compares the first 'n' bytes of + * the areas starting at 's1' and 's2' as unsigned bytes and returns the + * difference of the first differing pair, or 0 if the areas compare equal. + * Unlike ISO C memcmp, 'hs_memcmp(s1, s2, 0)' is well-defined for any + * pointers (including NULL or dangling ones from empty 'ByteArray#' + * slices) and returns 0 without dereferencing either pointer. + * + * Dispatch: + * - On non-glibc Linux on x86_64 or little-endian AArch64, the + * hand-written SIMD implementation 'hs_memcmp_simd' (rts/memcmp/) is + * used. Its reads are strictly bounded to [0, n), so no read ever + * crosses the object bounds. + * - On other non-glibc Linux architectures a portable 64-bit + * word-at-a-time loop with byte tail is used. Words are loaded with + * memcpy so there are no alignment or aliasing issues; only word + * equality is tested, so the result is endianness independent and + * the exact unsigned byte difference is produced by the tail. + * - Everywhere else (glibc, Darwin, Windows, BSD, wasm, ...) the + * platform memcmp is used. + * + * --------------------------------------------------------------------------*/ + +#include "rts/PosixSource.h" +#include "Rts.h" + +#if defined(__has_include) +#if __has_include(<features.h>) +#include <features.h> +#endif +#endif + +#include <stddef.h> +#include <stdint.h> +#include <string.h> + +#if (defined(linux_HOST_OS) || defined(__linux__)) && !defined(__GLIBC__) && \ + !defined(__BIONIC__) && !defined(__ANDROID__) && !defined(__UCLIBC__) && \ + (defined(x86_64_HOST_ARCH) || \ + (defined(aarch64_HOST_ARCH) && !defined(WORDS_BIGENDIAN)) || \ + (defined(__ELF__) && \ + (defined(__x86_64__) || (defined(__aarch64__) && !defined(__AARCH64EB__))))) +#define HS_MEMCMP_HAVE_SIMD 1 +extern int hs_memcmp_simd(const void *s1, const void *s2, size_t n); +#endif + +/* Prevent GCC from synthesising recursive memcmp calls out of the portable + * byte-comparison loop when MuslMemcmp.c forwards memcmp -> hs_memcmp. */ +#if defined(__GNUC__) && !defined(__clang__) +#define HS_MEMCMP_NO_DISTRIBUTE \ + __attribute__((optimize("no-tree-loop-distribute-patterns"))) +#else +#define HS_MEMCMP_NO_DISTRIBUTE +#endif + +HS_MEMCMP_NO_DISTRIBUTE +int hs_memcmp(const void *s1, const void *s2, size_t n) +{ +#if (defined(linux_HOST_OS) || defined(__linux__)) && !defined(__GLIBC__) && \ + !defined(__BIONIC__) && !defined(__ANDROID__) && !defined(__UCLIBC__) +#if defined(HS_MEMCMP_HAVE_SIMD) + return hs_memcmp_simd(s1, s2, n); +#else + /* Portable strictly-bounded fallback for other non-glibc Linux targets + * (e.g. riscv64, i386, arm, big-endian aarch64). */ + const unsigned char *a = (const unsigned char *)s1; + const unsigned char *b = (const unsigned char *)s2; + + while (n >= 8) + { + uint64_t w1; + uint64_t w2; + memcpy(&w1, a, 8); + memcpy(&w2, b, 8); + if (w1 != w2) + { + break; + } + a += 8; + b += 8; + n -= 8; + } + + while (n > 0) + { + if (*a != *b) + { + return (int)*a - (int)*b; + } + a++; + b++; + n--; + } + + return 0; +#endif +#else + /* n == 0 must not dereference the pointers: empty ByteArray# slices may + * pass NULL or dangling pointers, for which ISO C memcmp is undefined + * behaviour (glibc marks its arguments nonnull). */ + if (n == 0) + { + return 0; + } + return memcmp(s1, s2, n); +#endif +} ===================================== rts/MuslMemcmp.c ===================================== @@ -0,0 +1,50 @@ +/* ----------------------------------------------------------------------------- + * + * (c) 2026 Moritz Angermann <moritz.angermann@iohk.io>, Input Output Group + * + * SPDX-License-Identifier: BSD-3-Clause + * + * Static-archive memcmp interposer for non-glibc Linux. + * + * When the RTS is built for static ways (no -DDYNAMIC) on non-glibc Linux, + * libHSrts*.a includes this archive member defining a strong 'memcmp' that + * forwards to 'hs_memcmp'. Because GHC places -lHSrts after Haskell package + * archives and before -lc, any still-undefined 'memcmp' reference from + * third-party Haskell/C packages extracts this member before libc.a(memcmp.lo) + * is scanned. Dynamic RTS shared objects (-DDYNAMIC) compile an empty TU so + * they never interpose libc's dynamic 'memcmp'. + * + * Both 'hs_memcmp' (where the portable C fallback loop lives) and this + * forwarder carry no-tree-loop-distribute-patterns on GCC so loop distribution + * cannot turn the fallback back into a recursive memcmp call. + * + * --------------------------------------------------------------------------*/ + +#include "rts/PosixSource.h" +#include "Rts.h" + +#include <stddef.h> +#include <string.h> + +#if defined(__linux__) && !defined(__GLIBC__) && !defined(__BIONIC__) && \ + !defined(__ANDROID__) && !defined(__UCLIBC__) && !defined(DYNAMIC) && \ + !defined(SHARED) + +#if defined(__GNUC__) && !defined(__clang__) +#define HS_MEMCMP_NO_DISTRIBUTE \ + __attribute__((optimize("no-tree-loop-distribute-patterns"))) +#else +#define HS_MEMCMP_NO_DISTRIBUTE +#endif + +HS_MEMCMP_NO_DISTRIBUTE +int memcmp(const void *s1, const void *s2, size_t n) +{ + return hs_memcmp(s1, s2, n); +} + +#else + +typedef int hs_musl_memcmp_unused_tu; + +#endif ===================================== rts/RtsSymbols.c ===================================== @@ -602,6 +602,7 @@ extern char **environ; SymI_HasProto(ghc_unique_counter64) \ SymI_HasProto(ghc_unique_inc) \ SymI_HasProto(genericRaise) \ + SymI_HasProto(hs_memcmp) \ SymI_HasProto(getProgArgv) \ SymI_HasProto(getFullProgArgv) \ SymI_HasProto(setFullProgArgv) \ ===================================== rts/include/rts/Utils.h ===================================== @@ -12,5 +12,12 @@ #pragma once +#include <stddef.h> + /* Alternate to raise(3) for threaded rts, for BSD-based OSes */ int genericRaise(int sig); + +/* Fast memcmp with memcmp(3) semantics, implemented by the RTS + * (rts/HsMemcmp.c). Unlike ISO C memcmp, hs_memcmp(s1, s2, 0) returns 0 + * without dereferencing either pointer. */ +int hs_memcmp(const void *s1, const void *s2, size_t n); ===================================== rts/memcmp/memcmp-aarch64.S ===================================== @@ -0,0 +1,257 @@ +/* HS_MEMCMP_INTRO_BEGIN */ +/* */ +/* Copyright (c) 2026 Moritz Angermann <moritz.angermann@iohk.io>, Input Output Group */ +/* SPDX-License-Identifier: BSD-3-Clause */ +/* */ +/* AArch64 little-endian memcmp implementation for the GHC RTS */ +/* (hs_memcmp_simd). */ +/* */ +/* Adapted from a musl libc memcmp patch by the same author (original MIT */ +/* notice retained below); RTS renaming and guards under BSD-3-Clause. */ +/* NEON, ARMv8-A baseline, no IFUNC. All reads are strictly bounded to */ +/* [0, n); n == 0 returns 0 without dereferencing either pointer. Returns the */ +/* exact unsigned byte difference of the first differing bytes. */ +/* HS_MEMCMP_INTRO_END */ + +#include "ghcconfig.h" + +#if (defined(linux_HOST_OS) && defined(aarch64_HOST_ARCH) && !defined(WORDS_BIGENDIAN)) || (defined(__ELF__) && defined(__aarch64__) && !defined(__AARCH64EB__)) + .text +/* MIT License */ +/* */ +/* Copyright (c) 2026 Moritz Angermann <moritz.angermann@iohk.io>, Input Output Group */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining a copy */ +/* of this software and associated documentation files (the "Software"), to deal */ +/* in the Software without restriction, including without limitation the rights */ +/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ +/* copies of the Software, and to permit persons to whom the Software is */ +/* furnished to do so, subject to the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be included in all */ +/* copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */ +/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */ +/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */ +/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */ +/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */ +/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ +/* SOFTWARE. */ +/* */ +/* memcmp for musl libc, AArch64 (NEON, ARMv8-A baseline). */ +/* */ +/* No IFUNC, no target_clones: one straight-line NEON implementation valid on */ +/* every ARMv8-A core. */ +/* */ +/* Safety invariants: */ +/* - n == 0 returns 0 without dereferencing either pointer. */ +/* - 1 <= n < 16 uses overlapping bounded scalar loads (64/32/16/8-bit pairs */ +/* at offsets 0 and n-width, rev for unsigned order, clz for the first */ +/* differing byte), so every load satisfies offset + width <= n. */ +/* - n >= 16 processes 64B blocks (ldp q pairs) and 16B blocks with */ +/* offset + width <= n plus one final overlapping 16B vector, so no read */ +/* ever crosses the object bounds (and therefore no page-crossing fault */ +/* is possible on mapped inputs). */ +/* The result is the exact unsigned lexicographic difference of the first */ +/* differing bytes (*s1 - *s2), matching the generic C memcmp. */ +/* */ +/* Calling convention (AAPCS64): X0 = s1, X1 = s2, X2 = n. */ +/* Returns W0 = sign-correct unsigned byte difference, or 0. */ + + .arch armv8-a + .text + .p2align 2 + .globl hs_memcmp_simd + .hidden hs_memcmp_simd + .type hs_memcmp_simd, %function +hs_memcmp_simd: + cbz x2, .Lret0 + cmp x2, #16 + b.lo .Lsmall + /* x0 = s1 cursor, x1 = s2 cursor, x2 = remaining */ + b .Ltest64 +.Lloop64: /* 64B per iteration via ldp q pairs */ + ldp q0, q1, [x0, #0] + ldp q2, q3, [x0, #32] + ldp q4, q5, [x1, #0] + ldp q6, q7, [x1, #32] + cmeq v0.16b, v0.16b, v4.16b + shrn v0.8b, v0.8h, #4 /* nibble mask: 0xf per equal source byte */ + fmov x4, d0 + cmp x4, #-1 + b.ne .Lres0 + cmeq v1.16b, v1.16b, v5.16b + shrn v1.8b, v1.8h, #4 + fmov x4, d1 + cmp x4, #-1 + b.ne .Lres16 + cmeq v2.16b, v2.16b, v6.16b + shrn v2.8b, v2.8h, #4 + fmov x4, d2 + cmp x4, #-1 + b.ne .Lres32 + cmeq v3.16b, v3.16b, v7.16b + shrn v3.8b, v3.8h, #4 + fmov x4, d3 + cmp x4, #-1 + b.ne .Lres48 + add x0, x0, #64 + add x1, x1, #64 + sub x2, x2, #64 +.Ltest64: + cmp x2, #64 + b.hs .Lloop64 + b .Ltest16 +.Lloop16: + ldr q0, [x0] + ldr q1, [x1] + cmeq v0.16b, v0.16b, v1.16b + shrn v0.8b, v0.8h, #4 + fmov x4, d0 + cmp x4, #-1 + b.ne .Lres0 + add x0, x0, #16 + add x1, x1, #16 + sub x2, x2, #16 +.Ltest16: + cmp x2, #16 + b.hs .Lloop16 + cbz x2, .Lret0 + /* Overlapping final 16B at (cursor + remaining - 16) covers the tail. */ + sub x4, x2, #16 + add x0, x0, x4 + add x1, x1, x4 + ldr q0, [x0] + ldr q1, [x1] + cmeq v0.16b, v0.16b, v1.16b + shrn v0.8b, v0.8h, #4 + fmov x4, d0 + cmp x4, #-1 + b.ne .Lresolve +.Lret0: + mov w0, #0 + ret +.Lres16: + add x0, x0, #16 + add x1, x1, #16 + b .Lresolve +.Lres32: + add x0, x0, #32 + add x1, x1, #32 + b .Lresolve +.Lres48: + add x0, x0, #48 + add x1, x1, #48 + b .Lresolve +.Lres0: + b .Lresolve +.Lresolve: /* x0/x1 = 16B chunk base, x4 = nibble mask */ + mvn x4, x4 + rbit x4, x4 + clz x4, x4 + lsr x4, x4, #2 /* first differing byte index 0..15 */ + ldrb w5, [x0, x4] + ldrb w6, [x1, x4] + sub w0, w5, w6 + ret + +/* ---- Small sizes, 1 <= n < 16: overlapping bounded scalar loads ---- */ +.Lsmall: + cmp x2, #8 + b.lo .Ls4 + ldr x4, [x0] + ldr x5, [x1] + cmp x4, x5 + b.ne .Ls8_d0 + cmp x2, #8 + b.eq .Lret0 + sub x6, x2, #8 /* pair offset n-8 */ + ldr x4, [x0, x6] + ldr x5, [x1, x6] + cmp x4, x5 + b.eq .Lret0 + b .Ls8_res +.Ls8_d0: + mov x6, #0 /* pair offset 0 */ +.Ls8_res: /* x4/x5 = u64 pair, x6 = pair offset */ + rev x4, x4 + rev x5, x5 + eor x4, x4, x5 + clz x4, x4 + lsr x4, x4, #3 /* first differing byte index 0..7 */ + add x4, x4, x6 + ldrb w5, [x0, x4] + ldrb w6, [x1, x4] + sub w0, w5, w6 + ret +.Ls4: /* 1 <= n <= 7 */ + cmp x2, #4 + b.lo .Ls2 + ldr w4, [x0] + ldr w5, [x1] + cmp w4, w5 + b.ne .Ls4_d0 + cmp x2, #4 + b.eq .Lret0 + sub x6, x2, #4 /* pair offset n-4 */ + ldr w4, [x0, x6] + ldr w5, [x1, x6] + cmp w4, w5 + b.eq .Lret0 + b .Ls4_res +.Ls4_d0: + mov x6, #0 +.Ls4_res: /* w4/w5 = u32 pair, x6 = pair offset */ + rev w4, w4 + rev w5, w5 + eor w4, w4, w5 + clz w4, w4 + lsr w4, w4, #3 /* first differing byte index 0..3 */ + add x4, x4, x6 + ldrb w5, [x0, x4] + ldrb w6, [x1, x4] + sub w0, w5, w6 + ret +.Ls2: /* 1 <= n <= 3 */ + cmp x2, #2 + b.lo .Ls1 + ldrh w4, [x0] + ldrh w5, [x1] + cmp w4, w5 + b.ne .Ls2_d0 + cmp x2, #2 + b.eq .Lret0 + sub x6, x2, #2 /* pair offset n-2 */ + ldrh w4, [x0, x6] + ldrh w5, [x1, x6] + cmp w4, w5 + b.eq .Lret0 + b .Ls2_res +.Ls2_d0: + mov x6, #0 +.Ls2_res: /* w4/w5 = u16 pair, x6 = pair offset */ + rev16 w4, w4 + rev16 w5, w5 + eor w4, w4, w5 + clz w4, w4 + sub w4, w4, #16 + lsr w4, w4, #3 /* first differing byte index 0..1 */ + add x4, x4, x6 + ldrb w5, [x0, x4] + ldrb w6, [x1, x4] + sub w0, w5, w6 + ret +.Ls1: /* n == 1 */ + ldrb w4, [x0] + ldrb w5, [x1] + sub w0, w4, w5 + ret + + .size hs_memcmp_simd,.-hs_memcmp_simd + +#endif /* aarch64-le ELF / Linux */ + +#if defined(linux_HOST_OS) || defined(__ELF__) + .section .note.GNU-stack,"",%progbits +#endif ===================================== rts/memcmp/memcmp-x86_64.S ===================================== @@ -0,0 +1,527 @@ +/* HS_MEMCMP_INTRO_BEGIN */ +/* */ +/* Copyright (c) 2026 Moritz Angermann <moritz.angermann@iohk.io>, Input Output Group */ +/* SPDX-License-Identifier: BSD-3-Clause */ +/* */ +/* x86_64 memcmp implementation for the GHC RTS (hs_memcmp_simd). */ +/* */ +/* Adapted from a musl libc memcmp patch by the same author (original MIT */ +/* notice retained below); RTS renaming and guards under BSD-3-Clause. */ +/* SSE2 baseline with a runtime-dispatched AVX2 fast path, no IFUNC, */ +/* thread-safe one-byte dispatch cache. All reads are strictly bounded to */ +/* [0, n); n == 0 returns 0 without dereferencing either pointer. Returns the */ +/* exact unsigned byte difference of the first differing bytes. */ +/* HS_MEMCMP_INTRO_END */ + +#include "ghcconfig.h" + +#if (defined(linux_HOST_OS) && defined(x86_64_HOST_ARCH)) || (defined(__ELF__) && defined(__x86_64__)) +.text +/* MIT License */ +/* */ +/* Copyright (c) 2026 Moritz Angermann <moritz.angermann@iohk.io>, Input Output Group */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining a copy */ +/* of this software and associated documentation files (the "Software"), to deal */ +/* in the Software without restriction, including without limitation the rights */ +/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ +/* copies of the Software, and to permit persons to whom the Software is */ +/* furnished to do so, subject to the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be included in all */ +/* copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */ +/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */ +/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */ +/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */ +/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */ +/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ +/* SOFTWARE. */ +/* */ +/* memcmp for musl libc, x86_64. */ +/* */ +/* SSE2 baseline with an AVX2 fast path selected at run time. No IFUNC, no */ +/* target_clones: a single thread-safe .bss cache byte (0 = unknown, */ +/* 1 = SSE2 only, 2 = AVX2) records CPUID/XGETBV detection, so the common */ +/* case is one cached branch. Every AVX2-path return executes vzeroupper. */ +/* */ +/* Safety invariants: */ +/* - n == 0 returns 0 without dereferencing either pointer. */ +/* - 1 <= n < 16 uses overlapping bounded loads (8/4/2/1 byte pairs at */ +/* offsets 0 and n-width) with bswap + unsigned compare, so every load */ +/* satisfies offset + width <= n. */ +/* - n >= 16/32/128 processes full blocks with offset + width <= n plus one */ +/* final overlapping vector, so no read ever crosses the object bounds */ +/* (and therefore no page-crossing fault is possible on mapped inputs). */ +/* The result is the exact unsigned lexicographic difference of the first */ +/* differing bytes (*s1 - *s2), matching the generic C memcmp. */ +/* */ +/* Calling convention (System V AMD64): RDI = s1, RSI = s2, RDX = n. */ +/* Returns EAX = sign-correct unsigned byte difference, or 0. */ + +.text +.p2align 4 +.globl hs_memcmp_simd +.hidden hs_memcmp_simd +.type hs_memcmp_simd, @function +hs_memcmp_simd: + test %rdx,%rdx + jz .Lret0 + movzbl hs_memcmp_simd_avx2_cache(%rip),%eax + test %al,%al + jnz .Lchecked + /* Cold path: detect AVX2 support once. Byte-sized cache access is */ + /* atomic; concurrent threads may repeat detection but always store a */ + /* valid result, so no lock is needed. */ + push %rbx + push %rdx /* save n: cpuid writes ebx/ecx/edx, xgetbv writes edx:eax. */ + /* rdi/s1, rsi/s2 survive (untouched); r8 is caller-saved scratch. */ + xorl %eax,%eax + cpuid /* leaf 0: eax = max basic leaf (CPUID(1).EAX is the */ + /* processor signature, NOT the max leaf!) */ + mov %eax,%r8d /* save max basic leaf in caller-saved r8d */ + mov $1,%eax + cpuid /* ecx: bit 27 OSXSAVE, bit 28 AVX */ + bt $27,%ecx + jnc .Lnoavx + bt $28,%ecx + jnc .Lnoavx + xor %ecx,%ecx + xgetbv /* xcr0 -> edx:eax; need SSE+AVX state */ + and $6,%eax + cmp $6,%eax + jne .Lnoavx + cmp $7,%r8d /* leaf 7 (AVX2 bit) must exist */ + jb .Lnoavx + mov $7,%eax + xor %ecx,%ecx + cpuid /* ebx bit 5 = AVX2 */ + bt $5,%ebx + jnc .Lnoavx + pop %rdx + pop %rbx + movb $2,hs_memcmp_simd_avx2_cache(%rip) + jmp .Lavx2 +.Lnoavx: + pop %rdx + pop %rbx + movb $1,hs_memcmp_simd_avx2_cache(%rip) + jmp .Lsse +.Lchecked: + cmp $2,%al + je .Lavx2 + +/* ---- SSE2 baseline (no tzcnt, no AVX) ---- */ +.Lsse: + cmp $16,%rdx + jb .Lsmall + xor %eax,%eax /* i = block offset */ + mov %rdx,%rcx + sub $16,%rcx /* rcx = max full-block offset (n-16) */ + jmp .Lsse_test +.Lsse_loop: + movdqu (%rdi,%rax),%xmm0 + movdqu (%rsi,%rax),%xmm1 + pcmpeqb %xmm1,%xmm0 + pmovmskb %xmm0,%r8d + xor $0xffff,%r8d /* diff mask, bit set = differing byte */ + jnz .Lsse_diff /* (mask in r8d: rcx holds the n-16 bound) */ + add $16,%rax +.Lsse_test: + cmp %rcx,%rax + jbe .Lsse_loop + cmp %rdx,%rax + je .Lret0 + /* Overlapping final 16B at offset n-16 covers the tail. */ + mov %rcx,%rax + movdqu (%rdi,%rax),%xmm0 + movdqu (%rsi,%rax),%xmm1 + pcmpeqb %xmm1,%xmm0 + pmovmskb %xmm0,%r8d + xor $0xffff,%r8d + jnz .Lsse_diff +.Lret0: + xor %eax,%eax + ret +.Lsse_diff: /* r8d = diff mask (!=0), rax = block offset */ + bsfl %r8d,%r8d /* first differing byte index (no tzcnt) */ + add %rax,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + ret + +/* ---- Small sizes, 1 <= n < 16: overlapping bounded loads + bswap ---- */ +.Lsmall: + cmp $8,%rdx + jae .Lsmall8 + cmp $4,%rdx + jae .Lsmall4 + cmp $2,%rdx + jae .Lsmall2 + movzbl (%rdi),%eax + movzbl (%rsi),%edx + sub %edx,%eax + ret +.Lsmall8: /* 8 <= n <= 15 */ + mov (%rdi),%rax + mov (%rsi),%rcx + cmp %rcx,%rax + jne .Lsmall8_d0 + cmp $8,%rdx + je .Lret0 + mov %rdx,%r8 + sub $8,%r8 /* pair offset n-8 */ + mov (%rdi,%r8),%rax + mov (%rsi,%r8),%rcx + cmp %rcx,%rax + je .Lret0 + jmp .Lsmall8_res +.Lsmall8_d0: + xor %r8d,%r8d /* pair offset 0 */ +.Lsmall8_res: /* rax/rcx = u64 pair, r8 = pair offset */ + bswap %rax + bswap %rcx + xor %rcx,%rax + bsr %rax,%rax /* top differing bit (pair differs) */ + shr $3,%rax /* byte position from top */ + xor $7,%rax /* byte index 0..7 */ + add %r8,%rax + movzbl (%rdi,%rax),%ecx + movzbl (%rsi,%rax),%eax + sub %eax,%ecx + mov %ecx,%eax + ret +.Lsmall4: /* 4 <= n <= 7 */ + mov (%rdi),%eax + mov (%rsi),%ecx + cmp %ecx,%eax + jne .Lsmall4_d0 + cmp $4,%rdx + je .Lret0 + mov %rdx,%r8 + sub $4,%r8 /* pair offset n-4 */ + mov (%rdi,%r8),%eax + mov (%rsi,%r8),%ecx + cmp %ecx,%eax + je .Lret0 + jmp .Lsmall4_res +.Lsmall4_d0: + xor %r8d,%r8d +.Lsmall4_res: /* eax/ecx = u32 pair, r8 = pair offset */ + bswap %eax + bswap %ecx + xor %ecx,%eax + bsr %eax,%eax + shr $3,%eax + xor $3,%eax /* byte index 0..3 */ + add %r8,%rax + movzbl (%rdi,%rax),%ecx + movzbl (%rsi,%rax),%eax + sub %eax,%ecx + mov %ecx,%eax + ret +.Lsmall2: /* 2 <= n <= 3 */ + movzwl (%rdi),%eax + movzwl (%rsi),%ecx + cmp %cx,%ax + jne .Lsmall2_d0 + cmp $2,%rdx + je .Lret0 + mov %rdx,%r8 + sub $2,%r8 /* pair offset n-2 */ + movzwl (%rdi,%r8),%eax + movzwl (%rsi,%r8),%ecx + cmp %cx,%ax + je .Lret0 + jmp .Lsmall2_res +.Lsmall2_d0: + xor %r8d,%r8d +.Lsmall2_res: /* ax/cx = u16 pair, r8 = pair offset */ + xchg %al,%ah + xchg %cl,%ch + xor %ecx,%eax + test $0xff00,%eax /* first byte differs? */ + jnz .Lsmall2_first + add $1,%r8 /* else second byte differs */ +.Lsmall2_first: + movzbl (%rdi,%r8),%ecx + movzbl (%rsi,%r8),%eax + sub %eax,%ecx + mov %ecx,%eax + ret + +/* ---- AVX2 fast path ---- */ +.Lavx2: + cmp $32,%rdx + jb .Lavx_small + xor %eax,%eax /* i = block offset */ + mov %rdx,%rcx + sub $32,%rcx /* rcx = max full-block offset (n-32) */ + cmp $128,%rdx + jb .Lavx32_test +.Lavx128_loop: /* 4x32B per iteration */ + vmovdqu (%rdi,%rax),%ymm0 + vmovdqu (%rsi,%rax),%ymm1 + vpcmpeqb %ymm1,%ymm0,%ymm0 + vpmovmskb %ymm0,%r8d + xor $-1,%r8d + jnz .Lavx_diff0 + vmovdqu 32(%rdi,%rax),%ymm0 + vmovdqu 32(%rsi,%rax),%ymm1 + vpcmpeqb %ymm1,%ymm0,%ymm0 + vpmovmskb %ymm0,%r8d + xor $-1,%r8d + jnz .Lavx_diff32 + vmovdqu 64(%rdi,%rax),%ymm0 + vmovdqu 64(%rsi,%rax),%ymm1 + vpcmpeqb %ymm1,%ymm0,%ymm0 + vpmovmskb %ymm0,%r8d + xor $-1,%r8d + jnz .Lavx_diff64 + vmovdqu 96(%rdi,%rax),%ymm0 + vmovdqu 96(%rsi,%rax),%ymm1 + vpcmpeqb %ymm1,%ymm0,%ymm0 + vpmovmskb %ymm0,%r8d + xor $-1,%r8d + jnz .Lavx_diff96 + add $128,%rax + mov %rdx,%r8 + sub %rax,%r8 + cmp $128,%r8 + jae .Lavx128_loop + jmp .Lavx32_test +.Lavx32_loop: + vmovdqu (%rdi,%rax),%ymm0 + vmovdqu (%rsi,%rax),%ymm1 + vpcmpeqb %ymm1,%ymm0,%ymm0 + vpmovmskb %ymm0,%r8d + xor $-1,%r8d + jnz .Lavx32_diff + add $32,%rax +.Lavx32_test: + cmp %rcx,%rax + jbe .Lavx32_loop + cmp %rdx,%rax + je .Lavx_ret0 + /* Overlapping final 32B at offset n-32 covers the tail. */ + vmovdqu (%rdi,%rcx),%ymm0 + vmovdqu (%rsi,%rcx),%ymm1 + vpcmpeqb %ymm1,%ymm0,%ymm0 + vpmovmskb %ymm0,%r8d + xor $-1,%r8d + jnz .Lavx_final_diff +.Lavx_ret0: + vzeroupper + xor %eax,%eax + ret +.Lavx32_diff: /* r8d = diff mask, rax = block offset */ + bsfl %r8d,%r8d + add %rax,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_final_diff: /* r8d = diff mask, rcx = n-32 */ + bsfl %r8d,%r8d + add %rcx,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_diff0: /* r8d = diff mask, rax = block offset */ + bsfl %r8d,%r8d + add %rax,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_diff32: + bsfl %r8d,%r8d + add %rax,%r8 + add $32,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_diff64: + bsfl %r8d,%r8d + add %rax,%r8 + add $64,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_diff96: + bsfl %r8d,%r8d + add %rax,%r8 + add $96,%r8 + movzbl (%rdi,%r8),%eax + movzbl (%rsi,%r8),%edx + sub %edx,%eax + vzeroupper + ret + +/* ---- Small sizes on the AVX2 path (SSE insns, vzeroupper on return) ---- */ +.Lavx_small: /* 1 <= n < 32 */ + cmp $16,%rdx + jae .Lavx_small16 + cmp $8,%rdx + jae .Lavx_sm8 + cmp $4,%rdx + jae .Lavx_sm4 + cmp $2,%rdx + jae .Lavx_sm2 + movzbl (%rdi),%eax + movzbl (%rsi),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_small16: /* 16 <= n <= 31 */ + movdqu (%rdi),%xmm0 + movdqu (%rsi),%xmm1 + pcmpeqb %xmm1,%xmm0 + pmovmskb %xmm0,%ecx + xor $0xffff,%ecx + jnz .Lavx_s16_diff0 + mov %rdx,%rax + sub $16,%rax /* rax = n-16, overlapping final block */ + movdqu (%rdi,%rax),%xmm0 + movdqu (%rsi,%rax),%xmm1 + pcmpeqb %xmm1,%xmm0 + pmovmskb %xmm0,%ecx + xor $0xffff,%ecx + jnz .Lavx_s16_difff + vzeroupper + xor %eax,%eax + ret +.Lavx_s16_diff0: + bsfl %ecx,%ecx + movzbl (%rdi,%rcx),%eax + movzbl (%rsi,%rcx),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_s16_difff: + bsfl %ecx,%ecx + add %rax,%rcx + movzbl (%rdi,%rcx),%eax + movzbl (%rsi,%rcx),%edx + sub %edx,%eax + vzeroupper + ret +.Lavx_sm8: /* 8 <= n <= 15 */ + mov (%rdi),%rax + mov (%rsi),%rcx + cmp %rcx,%rax + jne .Lavx_sm8_d0 + cmp $8,%rdx + je .Lavx_sm_ret0 + mov %rdx,%r8 + sub $8,%r8 + mov (%rdi,%r8),%rax + mov (%rsi,%r8),%rcx + cmp %rcx,%rax + je .Lavx_sm_ret0 + jmp .Lavx_sm8_res +.Lavx_sm8_d0: + xor %r8d,%r8d +.Lavx_sm8_res: + bswap %rax + bswap %rcx + xor %rcx,%rax + bsr %rax,%rax + shr $3,%rax + xor $7,%rax + add %r8,%rax + movzbl (%rdi,%rax),%ecx + movzbl (%rsi,%rax),%eax + sub %eax,%ecx + mov %ecx,%eax + vzeroupper + ret +.Lavx_sm4: /* 4 <= n <= 7 */ + mov (%rdi),%eax + mov (%rsi),%ecx + cmp %ecx,%eax + jne .Lavx_sm4_d0 + cmp $4,%rdx + je .Lavx_sm_ret0 + mov %rdx,%r8 + sub $4,%r8 + mov (%rdi,%r8),%eax + mov (%rsi,%r8),%ecx + cmp %ecx,%eax + je .Lavx_sm_ret0 + jmp .Lavx_sm4_res +.Lavx_sm4_d0: + xor %r8d,%r8d +.Lavx_sm4_res: + bswap %eax + bswap %ecx + xor %ecx,%eax + bsr %eax,%eax + shr $3,%eax + xor $3,%eax + add %r8,%rax + movzbl (%rdi,%rax),%ecx + movzbl (%rsi,%rax),%eax + sub %eax,%ecx + mov %ecx,%eax + vzeroupper + ret +.Lavx_sm2: /* 2 <= n <= 3 */ + movzwl (%rdi),%eax + movzwl (%rsi),%ecx + cmp %cx,%ax + jne .Lavx_sm2_d0 + cmp $2,%rdx + je .Lavx_sm_ret0 + mov %rdx,%r8 + sub $2,%r8 + movzwl (%rdi,%r8),%eax + movzwl (%rsi,%r8),%ecx + cmp %cx,%ax + je .Lavx_sm_ret0 + jmp .Lavx_sm2_res +.Lavx_sm2_d0: + xor %r8d,%r8d +.Lavx_sm2_res: + xchg %al,%ah + xchg %cl,%ch + xor %ecx,%eax + test $0xff00,%eax + jnz .Lavx_sm2_first + add $1,%r8 +.Lavx_sm2_first: + movzbl (%rdi,%r8),%ecx + movzbl (%rsi,%r8),%eax + sub %eax,%ecx + mov %ecx,%eax + vzeroupper + ret +.Lavx_sm_ret0: + vzeroupper + xor %eax,%eax + ret + +.size hs_memcmp_simd,.-hs_memcmp_simd + +.section .bss +hs_memcmp_simd_avx2_cache: + .zero 1 + .type hs_memcmp_simd_avx2_cache,@object + .size hs_memcmp_simd_avx2_cache,1 + + +#endif /* x86_64 ELF / Linux */ + +#if defined(linux_HOST_OS) || defined(__ELF__) +.section .note.GNU-stack,"",@progbits +#endif ===================================== rts/rts.cabal ===================================== @@ -396,6 +396,15 @@ library if arch(ppc) || arch(ppc64) || arch(s390x) || arch(riscv64) || arch(loongarch64) asm-sources: StgCRunAsm.S + -- Hand-written SIMD memcmp used by hs_memcmp (rts/HsMemcmp.c) on + -- non-glibc Linux; the .S files expose only the hidden symbol + -- hs_memcmp_simd. + if os(linux) + if arch(x86_64) + asm-sources: memcmp/memcmp-x86_64.S + if arch(aarch64) + asm-sources: memcmp/memcmp-aarch64.S + c-sources: Adjustor.c AllocArray.c adjustor/AdjustorPool.c @@ -418,6 +427,7 @@ library Heap.c Hpc.c HsFFI.c + HsMemcmp.c Inlines.c Interpreter.c IOManager.c @@ -427,6 +437,7 @@ library Linker.c ReportMemoryMap.c Messages.c + MuslMemcmp.c OldARMAtomic.c PathUtils.c Pool.c ===================================== testsuite/tests/primops/should_run/HsMemcmp.hs ===================================== @@ -0,0 +1,388 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE MagicHash #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE UnboxedTuples #-} + +-- Exercise 'compareByteArrays#' (lowered to the RTS 'hs_memcmp' by the +-- native and LLVM code generators) and the 'hs_memcmp' C function +-- directly, over pinned and unpinned 'ByteArray#' slices, unaligned +-- offsets, a spread of sizes, unsigned high-bit bytes and +-- first/middle/last differences. + +module Main (main) where + +import Control.Monad (unless, when) +import Control.Monad.ST (runST) +import GHC.Exts +import GHC.ST (ST (..)) +import GHC.Word (Word8 (..)) + +#ifndef javascript_HOST_ARCH +import Control.Monad (forM_) +import Foreign.C.Types (CInt (..), CSize (..)) +import Foreign.Marshal.Alloc (free, mallocBytes) +import Foreign.Ptr (nullPtr, plusPtr) +import Foreign.Storable (poke) +#endif + +data BA = BA ByteArray# + +data MBA s = MBA (MutableByteArray# s) + +newByteArray :: Int -> ST s (MBA s) +newByteArray (I# n#) = + ST $ \s -> case newByteArray# n# s of + (# s', mba# #) -> (# s', MBA mba# #) + +newPinnedByteArray :: Int -> ST s (MBA s) +newPinnedByteArray (I# n#) = + ST $ \s -> case newPinnedByteArray# n# s of + (# s', mba# #) -> (# s', MBA mba# #) + +writeWord8Array :: MBA s -> Int -> Word8 -> ST s () +writeWord8Array (MBA mba#) (I# i#) (W8# w#) = + ST $ \s -> case writeWord8Array# mba# i# w# s of + s' -> (# s', () #) + +unsafeFreezeByteArray :: MBA s -> ST s BA +unsafeFreezeByteArray (MBA mba#) = + ST $ \s -> case unsafeFreezeByteArray# mba# s of + (# s', ba# #) -> (# s', BA ba# #) + +-- 'compareByteArrays#', normalised to an 'Ordering'. +compareSlices :: BA -> Int -> BA -> Int -> Int -> Ordering +compareSlices (BA ba1#) (I# o1#) (BA ba2#) (I# o2#) (I# n#) = + compare (I# (compareByteArrays# ba1# o1# ba2# o2# n#)) 0 + +createByteArray :: Bool -> Int -> (forall s. MBA s -> ST s ()) -> BA +createByteArray pinned n go = runST $ do + mba <- (if pinned then newPinnedByteArray else newByteArray) n + go mba + unsafeFreezeByteArray mba + +pack :: Bool -> [Word8] -> BA +pack pinned xs = createByteArray pinned (length xs) $ \mba -> go mba 0 xs + where + go _ _ [] = return () + go mba i (y : ys) = writeWord8Array mba i y >> go mba (i + 1) ys + +-- Deterministic byte pattern covering the whole 0x00..0xff range +-- (31 is coprime to 256, so every value occurs), including the +-- unsigned-comparison traps 0x7f/0x80. +pat :: Int -> Word8 +pat i = fromIntegral ((i * 31 + 7) `mod` 256) + +-- Reference model: unsigned lexicographic comparison. +cmpRef :: [Word8] -> Int -> [Word8] -> Int -> Int -> Ordering +cmpRef xs o1 ys o2 n = compare (take n (drop o1 xs)) (take n (drop o2 ys)) + +checkPrim :: String -> [Word8] -> BA -> Int -> [Word8] -> BA -> Int -> Int -> Maybe String +checkPrim tag xs ba1 o1 ys ba2 o2 n = + let want = cmpRef xs o1 ys o2 n + got = compareSlices ba1 o1 ba2 o2 n + in if got == want + then Nothing + else Just (tag ++ " n=" ++ show n ++ " o1=" ++ show o1 ++ " o2=" ++ show o2 + ++ " want=" ++ show want ++ " got=" ++ show got) + +-- Replace the element at index k. +replace :: Int -> Word8 -> [Word8] -> [Word8] +replace k w xs = take k xs ++ [w] ++ drop (k + 1) xs + +-- Constant-length comparison with a literal length, so the NCG sees +-- @CmmLit (CmmInt n _)@ and exercises the inline memcmp lowering. +{-# INLINE cmpConst #-} +cmpConst :: ByteArray# -> Int# -> ByteArray# -> Int# -> Int# -> Int +cmpConst ba1# o1# ba2# o2# n# = I# (compareByteArrays# ba1# o1# ba2# o2# n#) + +-- Two back-to-back constant-size comparisons in the same unboxed +-- expression, so two 'MO_Memcmp' nodes share a Cmm block. +{-# INLINE pairConst #-} +pairConst + :: ByteArray# -> Int# -> ByteArray# -> Int# + -> ByteArray# -> Int# -> ByteArray# -> Int# -> Int# -> (# Int#, Int# #) +pairConst ba1# o1# ba2# o2# ba3# o3# ba4# o4# n# = + (# compareByteArrays# ba1# o1# ba2# o2# n# + , compareByteArrays# ba3# o3# ba4# o4# n# #) + +{-# INLINE checkConstLen #-} +checkConstLen :: Int -> Int# -> [String] +checkConstLen n n# = + -- Equal slices at every unaligned offset pair in [0..7]. + [ f + | o1 <- [0 .. 7] + , o2 <- [0 .. 7] + , let b1 = replicate o1 0xaa ++ slice ++ replicate 8 0xbb + b2 = replicate o2 0xcc ++ slice ++ replicate 8 0xdd + BA ba1# = pack False b1 + BA ba2# = pack False b2 + I# o1# = o1 + I# o2# = o2 + got = compare (cmpConst ba1# o1# ba2# o2# n#) 0 + , got /= EQ + , let f = "const-eq n=" ++ show n ++ " o1=" ++ show o1 ++ " o2=" ++ show o2 + ++ " got=" ++ show got + ] + ++ + -- Every mismatch position, both signs, with unsigned high-bit pairs. + [ f + | (o1, o2) <- [(0, 0), (3, 5)] + , pos <- [0 .. n - 1] + , (x, y, want) <- directedPairs + , let b1 = replicate o1 0xaa ++ replace pos x slice ++ replicate 8 0xbb + b2 = replicate o2 0xcc ++ replace pos y slice ++ replicate 8 0xdd + BA ba1# = pack False b1 + BA ba2# = pack False b2 + I# o1# = o1 + I# o2# = o2 + got = compare (cmpConst ba1# o1# ba2# o2# n#) 0 + , got /= want + , let f = "const-diff n=" ++ show n ++ " o1=" ++ show o1 ++ " o2=" ++ show o2 + ++ " pos=" ++ show pos ++ " x=" ++ show x ++ " y=" ++ show y + ++ " want=" ++ show want ++ " got=" ++ show got + ] + ++ + -- Two back-to-back constant-size comparisons sharing one expression. + [ f + | (o1, o2, o3) <- [(0, 2, 1), (7, 5, 0)] + , let b1 = replicate o1 0xaa ++ slice ++ replicate 8 0xbb + b2 = replicate o2 0xcc ++ slice ++ replicate 8 0xdd + b3 = replicate o3 0xee ++ bump ++ replicate 8 0xff + BA ba1# = pack False b1 + BA ba2# = pack False b2 + BA ba3# = pack False b3 + I# q1# = o1 + I# q2# = o2 + I# q3# = o3 + (# r1#, r2# #) = pairConst ba1# q1# ba2# q2# ba1# q1# ba3# q3# n# + got1 = compare (I# r1#) 0 + got2 = compare (I# r2#) 0 + , got1 /= EQ || got2 /= wantPair + , let f = "const-pair n=" ++ show n + ++ " got1=" ++ show got1 ++ " got2=" ++ show got2 + ++ " wantPair=" ++ show wantPair + ] + where + slice = take n (map pat [0 ..]) + directedPairs = + [ (0x00, 0x80, LT), (0x7f, 0x80, LT), (0x80, 0xff, LT), (0x01, 0x02, LT) + , (0x80, 0x00, GT), (0x80, 0x7f, GT), (0xff, 0x80, GT), (0x02, 0x01, GT) + ] + -- Last byte bumped up (or down from 0xff), so b1 vs bump differs. + (bump, wantPair) = case slice of + [] -> (slice, EQ) + _ -> let old = last slice + in if old < 0xff + then (init slice ++ [old + 1], LT) + else (init slice ++ [old - 1], GT) + +-- Compile-time-constant lengths exercising the inline memcmp lowering. +-- Each call passes a literal length so the NCG sees @CmmLit (CmmInt n _)@. +constChecks :: [String] +constChecks = + checkConstLen 0 0# ++ + checkConstLen 1 1# ++ + checkConstLen 2 2# ++ + checkConstLen 3 3# ++ + checkConstLen 4 4# ++ + checkConstLen 5 5# ++ + checkConstLen 6 6# ++ + checkConstLen 7 7# ++ + checkConstLen 8 8# ++ + checkConstLen 9 9# ++ + checkConstLen 12 12# ++ + checkConstLen 15 15# ++ + checkConstLen 16 16# ++ + checkConstLen 17 17# ++ + checkConstLen 24 24# ++ + checkConstLen 28 28# ++ + checkConstLen 31 31# ++ + checkConstLen 32 32# ++ + checkConstLen 33 33# ++ + checkConstLen 48 48# ++ + checkConstLen 63 63# ++ + checkConstLen 64 64# ++ + checkConstLen 65 65# + +primChecks :: [String] +primChecks = + [ f + | pinned <- [False, True] + , let ba1 = pack pinned xs + ba2 = pack pinned ys + , o1 <- offs smallMax + , o2 <- offs smallMax + , n <- smallSizes + , o1 + n <= bufLen + , o2 + n <= bufLen + , Just f <- [checkPrim (if pinned then "pinned" else "unpinned") xs ba1 o1 ys ba2 o2 n] + ] + ++ + [ f + | pinned <- [False, True] + , let ba1 = pack pinned xs + ba2 = pack pinned ys + , o1 <- bigOffs + , o2 <- bigOffs + , n <- bigSizes + , o1 + n <= bufLen + , o2 + n <= bufLen + , Just f <- [checkPrim (if pinned then "pinned-big" else "unpinned-big") xs ba1 o1 ys ba2 o2 n] + ] + ++ + -- Mixed pinned/unpinned operands. + [ f + | (o1, o2) <- [(0, 1), (7, 8), (31, 30)] + , n <- mixedSizes + , o1 + n <= bufLen + , o2 + n <= bufLen + , Just f <- [checkPrim "mixed" xs baP o1 ys baU o2 n] + ] + ++ + -- First/middle/last byte differences, both signs, on otherwise-identical + -- slices at possibly distinct unaligned offsets (with distinct surrounding + -- guard bytes so out-of-bounds reads fail). + [ f + | n <- diffSizes + , (o1, o2) <- [(0, 0), (3, 5), (16, 7), (31, 0)] + , pos <- nub [0, n `div` 2, n - 1] + , let slice = take n xs + old = slice !! pos + , (new, want) <- + [ (old + 1, LT) | old < 0xff ] ++ [ (old - 1, GT) | old > 0x00 ] + , let b1 = replicate o1 0xaa ++ slice ++ replicate 16 0xbb + b2 = replicate o2 0xcc ++ replace pos new slice ++ replicate 16 0xdd + got = compareSlices (pack False b1) o1 (pack False b2) o2 n + , got /= want + , let f = "diff n=" ++ show n ++ " o1=" ++ show o1 ++ " o2=" ++ show o2 + ++ " pos=" ++ show pos ++ " want=" ++ show want ++ " got=" ++ show got + ] + ++ + -- Multi-iteration SIMD equal & late-mismatch checks (4 KiB and 64 KiB). + [ f + | n <- bigSizes + , (o1, o2) <- [(0, 0), (3, 19), (16, 31)] + , let slice = take n xs + b1 = replicate o1 0xaa ++ slice ++ replicate 16 0xbb + ba1 = pack False b1 + bEq = replicate o2 0xcc ++ slice ++ replicate 16 0xdd + gotEq = compareSlices ba1 o1 (pack False bEq) o2 n + lastIdx = n - 1 + old = slice !! lastIdx + (new, wantLast) = if old < 0xff then (old + 1, LT) else (old - 1, GT) + bLast = replicate o2 0xcc ++ replace lastIdx new slice ++ replicate 16 0xdd + gotLast = compareSlices ba1 o1 (pack False bLast) o2 n + , (tag, got, want) <- + [ ("big-eq", gotEq, EQ) + , ("big-last-diff", gotLast, wantLast) + ] + , got /= want + , let f = tag ++ " n=" ++ show n ++ " o1=" ++ show o1 ++ " o2=" ++ show o2 + ++ " want=" ++ show want ++ " got=" ++ show got + ] + ++ + -- Unsigned high-bit traps. + [ f + | (x, y, want) <- [ ([0x80], [0x7f], GT) + , ([0x7f], [0x80], LT) + , ([0xff], [0x00], GT) + , ([0x00], [0xff], LT) + , ([0x00], [0x00], EQ) + ] + , let got = compareSlices (pack False x) 0 (pack False y) 0 1 + , got /= want + , let f = "high-bit " ++ show x ++ " vs " ++ show y ++ " got=" ++ show got + ] + ++ + -- Equal pointers short-circuit, and n == 0 on empty arrays. + [ f + | (tag, got, want) <- + [ ("self-eq", compareSlices baU 0 baU 0 bufLen, EQ) + , ("empty", compareSlices (pack False []) 0 (pack True []) 0 0, EQ) + , ("zero-n", compareSlices baU 0 baU2 0 0, EQ) + ] + , got /= want + , let f = tag ++ " got=" ++ show got + ] + ++ + -- Compile-time-constant lengths (inline memcmp lowering). + constChecks + where + bufLen = 65536 + 32 + xs = map pat [0 .. bufLen - 1] + -- A few flipped bytes so most overlapping slices differ somewhere. + ys = replace 100 0x00 . replace 10000 0xff . replace 60000 0x80 $ xs + baU = pack False xs + baU2 = pack False xs + baP = pack True xs + smallMax = 31 + offs m = [0 .. m] + smallSizes = [0 .. 65] ++ [127, 128, 255, 256] + bigSizes = [4096, 65536] + bigOffs = [0, 1, 7, 16, 31] + mixedSizes = [1, 2, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33, 64, 65, 128, 256] + diffSizes = [1 .. 65] ++ [128, 256] + nub [] = [] + nub (z : zs) = z : nub [w | w <- zs, w /= z] + +#ifndef javascript_HOST_ARCH + +foreign import ccall unsafe "hs_memcmp" + c_hs_memcmp :: Ptr Word8 -> Ptr Word8 -> CSize -> IO CInt + +ffiChecks :: IO [String] +ffiChecks = do + let total = 4096 + 64 + xs = map pat [0 .. total - 1] + ys = replace 100 0x00 . replace 3000 0xff $ xs + p <- mallocBytes total + q <- mallocBytes total + forM_ (zip [0 ..] xs) $ \(i, w) -> poke (p `plusPtr` i) w + forM_ (zip [0 ..] ys) $ \(i, w) -> poke (q `plusPtr` i) w + fails <- fmap concat . sequence $ + [ do + r <- c_hs_memcmp (p `plusPtr` o1) (q `plusPtr` o2) (fromIntegral n) + let want = cmpRef xs o1 ys o2 n + got = compare r 0 + return [ "ffi n=" ++ show n ++ " o1=" ++ show o1 ++ " o2=" ++ show o2 + ++ " want=" ++ show want ++ " got=" ++ show got + | got /= want + ] + | o1 <- [0 .. 31] + , o2 <- [0 .. 31] + , n <- ffiSizes + , o1 + n <= total + , o2 + n <= total + ] + -- Pointer equality and n == 0 edges, including NULL pointers. + r1 <- c_hs_memcmp p p (fromIntegral total) + r2 <- c_hs_memcmp p q 0 + r3 <- c_hs_memcmp nullPtr nullPtr 0 + r4 <- c_hs_memcmp nullPtr q 0 + free p + free q + return $ fails + ++ ["ffi self-eq got=" ++ show r1 | r1 /= 0] + ++ ["ffi zero-n got=" ++ show r2 | r2 /= 0] + ++ ["ffi null-null-zero got=" ++ show r3 | r3 /= 0] + ++ ["ffi null-zero got=" ++ show r4 | r4 /= 0] + where + ffiSizes = [0 .. 65] ++ [127, 128, 255, 256, 4096] + +#endif + +main :: IO () +main = do + let fails1 = primChecks + mapM_ putStrLn (take 50 fails1) +#ifndef javascript_HOST_ARCH + fails2 <- ffiChecks + mapM_ putStrLn (take 50 fails2) + let fails = fails1 ++ fails2 +#else + let fails = fails1 +#endif + unless (null fails) $ + putStrLn ("FAILURES: " ++ show (length fails)) + when (null fails) $ + putStrLn "PASS" ===================================== testsuite/tests/primops/should_run/HsMemcmp.stdout ===================================== @@ -0,0 +1 @@ +PASS ===================================== testsuite/tests/primops/should_run/all.T ===================================== @@ -39,6 +39,7 @@ test('ResizeByteArrayPinnedness', compile_and_run, ['']) test('T14664', normal, compile_and_run, ['']) test('CStringLength', normal, compile_and_run, ['-O2']) +test('HsMemcmp', normal, compile_and_run, ['-O2']) test('NonNativeSwitch', normal, compile_and_run, ['-O2']) test('Sized', [ # optasm is broken with js backend: #25922 View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a66921722ea8cf665b8e968cab990b13... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/a66921722ea8cf665b8e968cab990b13... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help