[libc-commits] [libc] [llvm] [libc] Introduce a highly optimized `bcmp` implementation (PR #244952)

Chandler Carruth via libc-commits libc-commits at lists.llvm.org
Thu Nov 26 01:18:46 PST 2026


https://github.com/chandlerc updated https://github.com/llvm/llvm-project/pull/244952

>From 3b9ec330e72fe64b1e8de3709682efd153d2dd19 Mon Sep 17 00:00:00 2001
From: Chandler Carruth <chandlerc at gmail.com>
Date: Thu, 26 Nov 2026 08:03:07 +0000
Subject: [PATCH 1/2] [libc][benchmarks] Add latency and size-class `bcmp` and
 `memcmp` benchmarks

Existing benchmarks are only throughput benchmarks, and use batches
small enough to allow modern branch predictors to memorize the sequence
of sizes.

This extends the benchmarks with new ones in a suite. It adds latency
benchmarks that serialize calls across the different existing size
distributions. It also adds latency and reciprocal throughput benchmarks
across uniformly distributed small size classes to highlight small-size
performance.

It also uses a compact 64k entry batch to ensure branch predictors can't
memorize the size sequence while keeping the comparison data in L1.

Assisted-by: Antigravity with Gemini
---
 .../LibcMemoryGoogleBenchmarkMain.cpp         | 160 ++++++++++++++++++
 1 file changed, 160 insertions(+)

diff --git a/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp b/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp
index 6562366e8683c4..ec58740bb674f5 100644
--- a/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp
+++ b/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp
@@ -8,7 +8,10 @@
 #endif
 #include <chrono>
 #include <cstdint>
+#include <cstdlib>
+#include <cstring>
 #include <random>
+#include <string>
 #include <vector>
 
 using llvm::Align;
@@ -16,11 +19,13 @@ using llvm::ArrayRef;
 #ifdef LIBC_BENCHMARKS_HAS_LLVM_SUPPORT
 using llvm::Twine;
 #endif
+using llvm::libc_benchmarks::AlignedBuffer;
 using llvm::libc_benchmarks::BzeroConfiguration;
 using llvm::libc_benchmarks::ComparisonSetup;
 using llvm::libc_benchmarks::CopySetup;
 using llvm::libc_benchmarks::MemchrConfiguration;
 using llvm::libc_benchmarks::MemcmpOrBcmpConfiguration;
+using llvm::libc_benchmarks::MemcmpOrBcmpFunction;
 using llvm::libc_benchmarks::MemcpyConfiguration;
 using llvm::libc_benchmarks::MemmoveConfiguration;
 using llvm::libc_benchmarks::MemorySizeDistribution;
@@ -139,3 +144,158 @@ BENCHMARK_MEMORY_FUNCTION(BM_Strlen, SearchSetup, StrlenConfiguration,
 extern llvm::ArrayRef<StrcmpConfiguration> getStrcmpConfigurations();
 BENCHMARK_MEMORY_FUNCTION(BM_Strcmp, ComparisonSetup, StrcmpConfiguration,
                           getStrcmpConfigurations());
+
+namespace {
+
+// Large enough that modern branch predictors cannot memorize the repeating
+// sequence of comparison sizes within a batch.
+constexpr size_t kComparisonBatchSize = 64 * 1024;
+
+// Compact 8-byte descriptor (all benchmark sizes and buffer offsets fit in
+// uint16_t) for power-of-two indexing and smaller cache footprint.
+struct ComparisonPair {
+  uint16_t lhs_offset;
+  uint16_t rhs_offset;
+  uint16_t size;
+  uint16_t pad;
+};
+
+template <bool IsLatency>
+[[gnu::noinline]] void
+runComparisonLoop(benchmark::State &state, const char *lhs, const char *rhs,
+                  ArrayRef<ComparisonPair> pairs, MemcmpOrBcmpFunction func) {
+  const size_t n = pairs.size();
+  while (state.KeepRunningBatch(n)) {
+    if constexpr (IsLatency) {
+      size_t count = 0;
+      for (size_t i = 0; i < n; ++count) {
+        const ComparisonPair &p = pairs[i];
+        // Feed the zero/non-zero result into the next index branchlessly so
+        // each comparison must resolve before the next begins, mirroring a
+        // caller's branch on the return value without letting comparisons
+        // overlap.
+        i += 1 + static_cast<size_t>(
+                     func(lhs + p.lhs_offset, rhs + p.rhs_offset, p.size) != 0);
+      }
+      if (count != n)
+        std::abort();
+    } else {
+      for (const ComparisonPair &p : pairs) {
+        // Every pair is equal, so this branch is predicted and successive
+        // comparisons can overlap.
+        if (__builtin_expect(
+                func(lhs + p.lhs_offset, rhs + p.rhs_offset, p.size) != 0, 0))
+          std::abort();
+      }
+    }
+  }
+}
+
+template <bool IsLatency, typename SizeSampler>
+void runComparisonBatch(benchmark::State &state,
+                        const MemcmpOrBcmpConfiguration &config,
+                        size_t max_size, SizeSampler &&size_sampler,
+                        const std::string &label) {
+  // Keep data buffers small enough to stay in L1 while varying alignment.
+  const size_t buffer_size = max_size + 256;
+  AlignedBuffer lhs_buffer(buffer_size);
+  AlignedBuffer rhs_buffer(buffer_size);
+  std::memset(lhs_buffer.begin(), 0x0F, buffer_size);
+  std::memset(rhs_buffer.begin(), 0x0F, buffer_size);
+
+  OffsetDistribution offset_sampler(buffer_size, max_size, kBenchmarkAlignment);
+  auto &gen = getGenerator();
+  std::vector<ComparisonPair> pairs;
+  pairs.reserve(kComparisonBatchSize);
+  uint64_t batch_bytes = 0;
+  for (size_t i = 0; i < kComparisonBatchSize; ++i) {
+    const size_t size = size_sampler(gen);
+    pairs.push_back({static_cast<uint16_t>(offset_sampler(gen)),
+                     static_cast<uint16_t>(offset_sampler(gen)),
+                     static_cast<uint16_t>(size), 0});
+    batch_bytes += size;
+  }
+
+  runComparisonLoop<IsLatency>(state, lhs_buffer.begin(), rhs_buffer.begin(),
+                               pairs, config.function);
+
+  const uint64_t total_bytes =
+      (state.iterations() / kComparisonBatchSize) * batch_bytes;
+  state.SetBytesProcessed(total_bytes);
+  state.SetItemsProcessed(state.iterations());
+  state.SetLabel(label);
+  state.counters["bytes_per_cycle"] = benchmark::Counter(
+      total_bytes / benchmark::CPUInfo::Get().cycles_per_second,
+      benchmark::Counter::kIsRate);
+}
+
+void runDistributionLatencyBenchmark(
+    benchmark::State &state, ArrayRef<MemcmpOrBcmpConfiguration> configs) {
+  const MemorySizeDistribution dist =
+      ComparisonSetup::get_distributions()[state.range(0)];
+  const MemcmpOrBcmpConfiguration config = configs[state.range(1)];
+  std::discrete_distribution<size_t> size_sampler(dist.probabilities.begin(),
+                                                  dist.probabilities.end());
+  runComparisonBatch<true>(state, config, dist.probabilities.size() - 1,
+                           size_sampler,
+                           config.name.str() + "," + dist.name.str());
+}
+
+template <bool IsLatency>
+void runSizeClassBenchmark(benchmark::State &state,
+                           ArrayRef<MemcmpOrBcmpConfiguration> configs) {
+  const size_t min_size = static_cast<size_t>(state.range(0));
+  const size_t max_size = static_cast<size_t>(state.range(1));
+  const MemcmpOrBcmpConfiguration config = configs[state.range(2)];
+  std::uniform_int_distribution<size_t> size_sampler(min_size, max_size);
+  runComparisonBatch<IsLatency>(state, config, max_size, size_sampler,
+                                config.name.str() + ",[" +
+                                    std::to_string(min_size) + "," +
+                                    std::to_string(max_size) + "]");
+}
+
+void applyComparisonDistributionArgs(benchmark::Benchmark *b,
+                                     int64_t conf_size) {
+  const int64_t dist_size =
+      static_cast<int64_t>(ComparisonSetup::get_distributions().size());
+  for (int64_t dist_index = 0; dist_index < dist_size; ++dist_index)
+    for (int64_t conf_index = 0; conf_index < conf_size; ++conf_index)
+      b->Args({dist_index, conf_index});
+}
+
+void applySizeClassArgs(benchmark::Benchmark *b, int64_t conf_size) {
+  static constexpr int64_t kSizeClasses[][2] = {
+      {1, 3},   {4, 8},  {9, 16},   {17, 32},
+      {33, 64}, {1, 16}, {65, 256}, {257, 1024},
+  };
+  b->ArgNames({"min", "max", "conf"});
+  for (const auto &range : kSizeClasses)
+    for (int64_t conf_index = 0; conf_index < conf_size; ++conf_index)
+      b->Args({range[0], range[1], conf_index});
+}
+
+} // namespace
+
+#define BENCHMARK_COMPARISON_SUITE(NAME, CONFIGS)                              \
+  void BM_##NAME##Latency(benchmark::State &S) {                               \
+    runDistributionLatencyBenchmark(S, CONFIGS);                               \
+  }                                                                            \
+  BENCHMARK(BM_##NAME##Latency)->Apply([](benchmark::Benchmark *b) {           \
+    applyComparisonDistributionArgs(b, (CONFIGS).size());                      \
+  });                                                                          \
+  void BM_##NAME##SizeClassThroughput(benchmark::State &S) {                   \
+    runSizeClassBenchmark<false>(S, CONFIGS);                                  \
+  }                                                                            \
+  BENCHMARK(BM_##NAME##SizeClassThroughput)                                    \
+      ->Apply([](benchmark::Benchmark *b) {                                    \
+        applySizeClassArgs(b, (CONFIGS).size());                               \
+      });                                                                      \
+  void BM_##NAME##SizeClassLatency(benchmark::State &S) {                      \
+    runSizeClassBenchmark<true>(S, CONFIGS);                                   \
+  }                                                                            \
+  BENCHMARK(BM_##NAME##SizeClassLatency)->Apply([](benchmark::Benchmark *b) {  \
+    applySizeClassArgs(b, (CONFIGS).size());                                   \
+  })
+
+BENCHMARK_COMPARISON_SUITE(Memcmp, getMemcmpConfigurations());
+BENCHMARK_COMPARISON_SUITE(Bcmp, getBcmpConfigurations());

>From 95f1d8fb42618ce3b4ae0a3682b6b63da6003ca2 Mon Sep 17 00:00:00 2001
From: Chandler Carruth <chandlerc at gmail.com>
Date: Mon, 16 Nov 2026 09:26:50 +0000
Subject: [PATCH 2/2] [libc] Introduce a highly optimized `bcmp` implementation

The existing implementation of `bcmp` wasn't un-optimized, but it turns
out there was a _lot_ of performance left on the table here, and a lot
of important callers were suffering from this.

This PR reworks `bcmp`'s implementation from top to bottom and across
all the architectures that I had a good idea of how to pursue
performance. 32-bit architectures bias a bit towards small code size
rather than runtime performance, while the most tuned runtime
performance is in the 64-bit architecture implementations.

It optimizes (aggressively) for the distribution of string function
operands we have seen in practice, re-using a bunch of benchmark
machinery from the rest of llvm-libc for this. The notable bias is
optimizing for very _short_ strings -- those end up dominating the
distribution we observe in practice.

It covers Arm, x86, and RISC-V, both 64-bit and 32-bit, and the most
widespread set of architecture variants for each. For 32-bit
architectures and RISC-V, tested with QEMU and performance analysis with
`llvm-mca` as I don't have enough representative hardware.

Key aspects of the optimized implementation strategy:
- Never read outside `[0, count)`, including never reading memory with
  size zero as some callers require. Avoiding small-string overread
  keeps every path safe under Arm MTE (16-byte tag granules),
  sanitizers, CHERI, and LTO without page-boundary checks or mask
  tables. While we explored overread options, they added significant
  complexity and we were able to get exact read options to be
  competitive in expected latency and throughput. This is heavily based
  on our experience being that size branching tends to be highly
  predictable in practice.
- Use branched size classes with overlapping reads (`4..8`, `2..3`, `1`,
  pushing rare `0` off the `2..8` paths, then `9..16`, `17..32`,
  `33..64`) tuned for predictable size branches. On x86-64 `4..8`,
  checking the tail with a predicted-not-taken branch and returning the
  hoisted head XOR keeps the tail AGU off the equal-path critical path.
- Calling conventions don't propagate condition flags, so either
  conditionally return a constant (which can be predicted within
  `bcmp`), or return bits that the caller can compare with zero rather
  than doing the comparison within `bcmp`. The latter is especially
  important as it allows a single prediction in the caller and avoids
  materializing condition flags into the ABI.
- Avoid vector register -> GPR stalls. Some of the time this is by doing
  a comparison directly on vector registers when we can and want a
  predictable branch on that comparison. But the largest aspect is using
  GPRs aggressively so that we can compare and branch without the
  penalty.
- Keep the `0..64` fast path compact and `vzeroupper`-clean on `<=32`
  bytes by tail-calling out-of-line `>64` handlers on x86-64 and
  AArch64, and stick to XMM/YMM (using AVX-512VL+BW mask compares for
  `17..64` without a separate ZMM `>64` path) for simplicity and smaller
  code size.

This adds shared `bcmp` utilities and expanded unit tests, and uses the
latency and throughput comparison benchmarks from the parent PR so we
can measure both and ensure we don't compromise one for the sake of the
other. A brief summary of the results (CPU ns, lower is better):

| Target / Benchmark               |        Base |         New |   Improvement |
| -------------------------------- | ----------: | ----------: | ------------: |
| Zen 5 BM_Bcmp Google A..W        |   1.33-1.62 |   1.36-1.59 | 0.99x geomean |
| Zen 5 BM_BcmpLatency Google A..W |   5.11-9.05 |   4.74-7.28 | 1.16x geomean |
| Zen 5 RTput [1,3] / [4,8]        | 4.96 / 5.66 | 2.47 / 0.92 | 2.01x / 6.17x |
| Zen 5 RTput [1,16] / [65,256]    | 5.41 / 4.71 | 4.25 / 3.47 | 1.27x / 1.36x |
| Zen 5 Lat [1,3] / [4,8]          | 6.59 / 7.48 | 4.16 / 2.39 | 1.58x / 3.13x |
| Zen 5 Lat [65,256] / [257,1024]  | 8.87 / 11.5 | 5.46 / 10.7 | 1.62x / 1.07x |
| Zen 3 BM_Bcmp Google A..W        |   3.30-3.96 |   2.59-3.58 | 1.20x geomean |
| Zen 3 BM_BcmpLatency Google A..W |   8.56-13.1 |   7.92-11.9 | 1.15x geomean |
| Zen 3 BM_Bcmp 384..4096          |        37.8 |        29.6 |         1.28x |
| Zen 3 RTput [1,3] / [4,8]        | 7.19 / 8.31 | 4.14 / 1.57 | 1.74x / 5.29x |
| Zen 3 Lat [4,8] / [65,256]       | 10.1 / 16.0 | 4.26 / 9.91 | 2.37x / 1.61x |
| M1 BM_Bcmp 384..4096             |        50.5 |        41.5 |         1.22x |
| M1 BM_BcmpLatency Google A..W    |   8.35-14.1 |   7.18-10.8 | 1.20x geomean |
| M1 RTput [1,3] / [4,8]           | 5.58 / 4.00 | 3.22 / 1.17 | 1.73x / 3.42x |
| M1 RTput [9,16] / [1,16]         | 2.28 / 6.61 | 1.34 / 5.48 | 1.70x / 1.21x |
| M1 Lat [17,32] / [33,64]         | 9.49 / 10.6 | 6.30 / 6.12 | 1.51x / 1.73x |
| M1 Lat [65,256] / [257,1024]     | 14.7 / 21.7 | 11.1 / 17.4 | 1.32x / 1.25x |

(Dropping the 512-bit ZMM `>64` loop trades off `384..4096` on Zen 5 --
12.5 vs 14.6 ns RTput, 18.4 vs 21.8 ns Lat -- for a single AVX2 loop,
smaller code, and no ZMM frequency impact on Intel.)

Assisted-by: Antigravity with Gemini
---
 libc/src/string/memory_utils/CMakeLists.txt   |   5 +
 .../string/memory_utils/aarch64/inline_bcmp.h | 183 +++++++-------
 .../memory_utils/generic/aligned_access.h     | 109 +++++---
 .../string/memory_utils/generic/bcmp_utils.h  | 184 ++++++++++++++
 libc/src/string/memory_utils/inline_bcmp.h    |  25 +-
 .../string/memory_utils/riscv/inline_bcmp.h   |  78 +++++-
 .../string/memory_utils/x86_64/inline_bcmp.h  | 239 +++++++++++++-----
 libc/src/strings/bcmp.cpp                     |  11 +
 libc/test/src/strings/bcmp_test.cpp           | 135 +++++++++-
 .../libc/src/string/memory_utils/BUILD.bazel  |   1 +
 .../libc/src/strings/BUILD.bazel              |   2 +
 .../libc/test/src/strings/BUILD.bazel         |   8 +-
 12 files changed, 779 insertions(+), 201 deletions(-)
 create mode 100644 libc/src/string/memory_utils/generic/bcmp_utils.h

diff --git a/libc/src/string/memory_utils/CMakeLists.txt b/libc/src/string/memory_utils/CMakeLists.txt
index 510546d79988ae..9025b2d5cf4ae4 100644
--- a/libc/src/string/memory_utils/CMakeLists.txt
+++ b/libc/src/string/memory_utils/CMakeLists.txt
@@ -11,6 +11,7 @@ add_header_library(
     arm/inline_memcpy.h
     arm/inline_memset.h
     generic/aligned_access.h
+    generic/bcmp_utils.h
     generic/byte_per_byte.h
     inline_bcmp.h
     inline_bzero.h
@@ -36,14 +37,18 @@ add_header_library(
   DEPENDS
     libc.hdr.stdint_proxy
     libc.src.__support.common
+    libc.src.__support.CPP.array
     libc.src.__support.CPP.bit
     libc.src.__support.CPP.cstddef
     libc.src.__support.CPP.type_traits
+    libc.src.__support.macros.attributes
     libc.src.__support.macros.config
     libc.src.__support.macros.is_defined
     libc.src.__support.macros.optimization
     libc.src.__support.macros.properties.architectures
     libc.src.__support.macros.properties.compiler
+    libc.src.__support.macros.properties.cpu_features
+    libc.src.__support.macros.properties.types
 )
 
 add_header_library(
diff --git a/libc/src/string/memory_utils/aarch64/inline_bcmp.h b/libc/src/string/memory_utils/aarch64/inline_bcmp.h
index 9c6821037ff1a7..344db26789dc10 100644
--- a/libc/src/string/memory_utils/aarch64/inline_bcmp.h
+++ b/libc/src/string/memory_utils/aarch64/inline_bcmp.h
@@ -5,111 +5,120 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===----------------------------------------------------------------------===//
-#ifndef LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
-#define LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
 
-#include "src/__support/macros/attributes.h"   // LIBC_INLINE
+#include "hdr/stdint_proxy.h"
+#include "src/__support/macros/attributes.h"   // LIBC_INLINE, LIBC_NOINLINE
 #include "src/__support/macros/config.h"       // LIBC_NAMESPACE_DECL
 #include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
-#include "src/string/memory_utils/op_aarch64.h"
-#include "src/string/memory_utils/op_generic.h"
-#include "src/string/memory_utils/utils.h" // Ptr, CPtr
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType, load_unaligned
 
 #include <stddef.h> // size_t
 
+#ifdef __ARM_NEON
+#include "src/__support/macros/properties/types.h" // LIBC_TYPES_HAS_INT128
+#include <arm_neon.h>
+#endif
+
 namespace LIBC_NAMESPACE_DECL {
 
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_aarch64_no_fp(CPtr p1, CPtr p2, size_t count) {
-  if (LIBC_LIKELY(count < 16)) {
-    switch (count) {
-    case 0:
-      return BcmpReturnType::zero();
-    case 1:
-      return generic::Bcmp<uint8_t>::block(p1, p2);
-    case 2:
-      return generic::Bcmp<uint16_t>::block(p1, p2);
-    case 3:
-      return generic::Bcmp<uint16_t>::head_tail(p1, p2, count);
-    case 4:
-      return generic::Bcmp<uint32_t>::block(p1, p2);
-    case 5:
-    case 6:
-    case 7:
-      return generic::Bcmp<uint32_t>::head_tail(p1, p2, count);
-    case 8:
-      return generic::Bcmp<uint64_t>::block(p1, p2);
-    case 9:
-    case 10:
-    case 11:
-    case 12:
-    case 13:
-    case 14:
-    case 15:
-      return generic::Bcmp<uint64_t>::head_tail(p1, p2, count);
-    }
-  }
+#ifdef __ARM_NEON
+namespace internal {
 
-  return generic::Bcmp<uint64_t>::loop_and_tail_align_above(256, p1, p2, count);
+// Comparing `__uint128_t` keeps 17..32 in GPRs (`ldp` + `cmp` + `ccmp`)
+// without Neon-to-GPR transfer latency; LLVM would otherwise vectorize 64-bit
+// comparisons into Neon. Checking the tail with a predicted-not-taken branch
+// keeps tail address computation off the equal-path critical path.
+LIBC_INLINE BcmpReturnType bcmp_aarch64_17_to_32(CPtr p1, CPtr p2,
+                                                 size_t count) {
+#ifdef LIBC_TYPES_HAS_INT128
+  if (LIBC_UNLIKELY(bcmp_xor<__uint128_t>(p1 + count - 16, p2 + count - 16) !=
+                    0))
+    return BcmpReturnType::nonzero();
+  return static_cast<uint32_t>(bcmp_xor<__uint128_t>(p1, p2) != 0);
+#else
+  return bcmp_17_to_32_64bit(p1, p2, count);
+#endif
 }
 
-#ifdef __ARM_NEON
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_aarch64_with_fp(CPtr p1, CPtr p2, size_t count) {
-  if (LIBC_LIKELY(count <= 32)) {
-    if (LIBC_UNLIKELY(count >= 16)) {
-      return aarch64::Bcmp<16>::head_tail(p1, p2, count);
-    }
-    switch (count) {
-    case 0:
-      return BcmpReturnType::zero();
-    case 1:
-      return generic::Bcmp<uint8_t>::block(p1, p2);
-    case 2:
-      return generic::Bcmp<uint16_t>::block(p1, p2);
-    case 3:
-      return generic::Bcmp<uint16_t>::head_tail(p1, p2, count);
-    case 4:
-      return generic::Bcmp<uint32_t>::block(p1, p2);
-    case 5:
-    case 6:
-    case 7:
-      return generic::Bcmp<uint32_t>::head_tail(p1, p2, count);
-    case 8:
-      return generic::Bcmp<uint64_t>::block(p1, p2);
-    case 9:
-    case 10:
-    case 11:
-    case 12:
-    case 13:
-    case 14:
-    case 15:
-      return generic::Bcmp<uint64_t>::head_tail(p1, p2, count);
-    }
-  }
+LIBC_INLINE uint8x16_t aarch64_xor16(CPtr p1, CPtr p2) {
+  return veorq_u8(load_unaligned<uint8x16_t>(p1),
+                  load_unaligned<uint8x16_t>(p2));
+}
 
-  if (count <= 64)
-    return aarch64::Bcmp<32>::head_tail(p1, p2, count);
+LIBC_INLINE uint8x16_t aarch64_xor32(CPtr p1, CPtr p2) {
+  return vorrq_u8(aarch64_xor16(p1, p2), aarch64_xor16(p1 + 16, p2 + 16));
+}
+
+// Pairwise `umaxp` folds four 32-bit lanes into 64 bits (`umaxp + fmov`) with
+// lower latency than a full horizontal `umaxv` reduction.
+LIBC_INLINE bool aarch64_neon_nonzero(uint8x16_t diff) {
+  const uint32x4_t d32 = vreinterpretq_u32_u8(diff);
+  return vgetq_lane_u64(vreinterpretq_u64_u32(vpmaxq_u32(d32, d32)), 0) != 0;
+}
+
+LIBC_INLINE bool aarch64_neon_64_ne(CPtr p1, CPtr p2) {
+  return aarch64_neon_nonzero(
+      vorrq_u8(aarch64_xor32(p1, p2), aarch64_xor32(p1 + 32, p2 + 32)));
+}
+
+// Sizes > 32 pair Neon early-exit checks over `[4, count)` with a GPR `[0, 4)`
+// final return (hiding Neon-to-GPR latency on equal inputs). The > 64 handler
+// is kept out-of-line and tail-called so the 0..64 fast path stays compact.
+LIBC_INLINE BcmpReturnType bcmp_aarch64_33_to_64(CPtr p1, CPtr p2,
+                                                 size_t count) {
+  const uint8x16_t head =
+      vorrq_u8(aarch64_xor16(p1 + 4, p2 + 4), aarch64_xor16(p1 + 16, p2 + 16));
+  if (LIBC_UNLIKELY(aarch64_neon_nonzero(
+          vorrq_u8(head, aarch64_xor32(p1 + count - 32, p2 + count - 32)))))
+    return BcmpReturnType::nonzero();
+  return bcmp_xor<uint32_t>(p1, p2);
+}
 
-  // Aligned loop if > 256, otherwise normal loop
-  if (LIBC_UNLIKELY(count > 256)) {
-    if (auto value = aarch64::Bcmp<32>::block(p1, p2))
-      return value;
-    align_to_next_boundary<16, Arg::P1>(p1, p2, count);
+LIBC_NOINLINE LIBC_INLINE uint32_t bcmp_aarch64_over_64(CPtr p1, CPtr p2,
+                                                        size_t count) {
+  const uint8x16_t head =
+      vorrq_u8(aarch64_xor16(p1 + 4, p2 + 4), aarch64_xor16(p1 + 16, p2 + 16));
+  if (LIBC_UNLIKELY(aarch64_neon_nonzero(
+          vorrq_u8(head, aarch64_xor32(p1 + 32, p2 + 32)))))
+    return 1;
+  if (count > 128) {
+    if (LIBC_UNLIKELY(bcmp_xor<uint32_t>(p1, p2) != 0))
+      return 1;
+    const size_t last = count - 64;
+    for (size_t i = 64 - static_cast<size_t>(distance_to_align_down<16>(p1));
+         i < last; i += 64) {
+      if (LIBC_UNLIKELY(aarch64_neon_64_ne(p1 + i, p2 + i)))
+        return 1;
+    }
   }
-  return aarch64::Bcmp<32>::loop_and_tail(p1, p2, count);
+  if (LIBC_UNLIKELY(aarch64_neon_64_ne(p1 + count - 64, p2 + count - 64)))
+    return 1;
+  return bcmp_xor<uint32_t>(p1, p2);
 }
-#endif
 
-LIBC_FLATTEN LIBC_INLINE BcmpReturnType
-inline_bcmp_aarch64_dispatch(CPtr p1, CPtr p2, size_t count) {
-#if defined(__ARM_NEON)
-  return inline_bcmp_aarch64_with_fp(p1, p2, count);
+} // namespace internal
+#endif // __ARM_NEON
+
+[[maybe_unused]] LIBC_INLINE
+    BcmpReturnType inline_bcmp_aarch64(CPtr p1, CPtr p2, size_t count) {
+#ifdef __ARM_NEON
+  if (count <= 8)
+    return internal::bcmp_0_to_8(p1, p2, count);
+  if (count <= 16)
+    return internal::bcmp_9_to_16(p1, p2, count);
+  if (count <= 32)
+    return internal::bcmp_aarch64_17_to_32(p1, p2, count);
+  if (count <= 64)
+    return internal::bcmp_aarch64_33_to_64(p1, p2, count);
+  return internal::bcmp_aarch64_over_64(p1, p2, count);
 #else
-  return inline_bcmp_aarch64_no_fp(p1, p2, count);
-#endif
+  return inline_bcmp_unaligned_64bit(p1, p2, count);
+#endif // __ARM_NEON
 }
 
 } // namespace LIBC_NAMESPACE_DECL
 
-#endif // LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
diff --git a/libc/src/string/memory_utils/generic/aligned_access.h b/libc/src/string/memory_utils/generic/aligned_access.h
index 49a318d9c8a954..ec06b1c5fa8eff 100644
--- a/libc/src/string/memory_utils/generic/aligned_access.h
+++ b/libc/src/string/memory_utils/generic/aligned_access.h
@@ -13,7 +13,10 @@
 #ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_ALIGNED_ACCESS_H
 #define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_ALIGNED_ACCESS_H
 
-#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "src/__support/endian_internal.h"
+#include "src/__support/macros/attributes.h" // LIBC_ALWAYS_INLINE, LIBC_INLINE
+#include "src/__support/macros/config.h"     // LIBC_NAMESPACE_DECL
+#include "src/__support/macros/optimization.h" // LIBC_LOOP_NOUNROLL
 #include "src/string/memory_utils/generic/byte_per_byte.h"
 #include "src/string/memory_utils/op_generic.h" // generic::splat
 #include "src/string/memory_utils/utils.h"      // Ptr, CPtr
@@ -121,42 +124,82 @@ inline_memset_aligned_access_64bit(Ptr dst, uint8_t value, size_t count) {
 // bcmp
 ///////////////////////////////////////////////////////////////////////////////
 
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_aligned_access_32bit(CPtr p1, CPtr p2, size_t count) {
-  constexpr size_t kAlign = sizeof(uint32_t);
-  if (count <= 2 * kAlign)
-    return inline_bcmp_byte_per_byte(p1, p2, count);
-  size_t bytes_to_p1_align = distance_to_align_up<kAlign>(p1);
-  if (auto value = inline_bcmp_byte_per_byte(p1, p2, bytes_to_p1_align))
-    return value;
-  size_t offset = bytes_to_p1_align;
-  size_t p2_alignment = distance_to_align_down<kAlign>(p2 + offset);
-  for (; offset < count - kAlign; offset += kAlign) {
-    uint32_t a = load32_aligned<uint32_t>(p1, offset);
-    uint32_t b = load32_aligned(p2, offset, p2_alignment);
-    if (a != b)
-      return BcmpReturnType::nonzero();
+template <typename Word>
+LIBC_ALWAYS_INLINE BcmpReturnType inline_bcmp_aligned_access(CPtr p1, CPtr p2,
+                                                             size_t count) {
+  constexpr size_t ALIGN = sizeof(Word);
+  if (count == 0)
+    return BcmpReturnType::zero();
+  if (count <= 3)
+    return cpp::to_integer<uint32_t>((p1[0] ^ p2[0]) |
+                                     (p1[count - 1] ^ p2[count - 1]) |
+                                     (p1[count >> 1] ^ p2[count >> 1]));
+  if (count >= 2 * ALIGN) {
+    size_t lead = static_cast<size_t>(distance_to_align_up<ALIGN>(p1));
+    const size_t p2_align =
+        (static_cast<size_t>(distance_to_align_down<ALIGN>(p2)) + lead) &
+        (ALIGN - 1);
+    // When `p1` and `p2` are not mutually aligned, consume one extra leading
+    // word byte-by-byte so `p1` stays aligned and `p2_base = p2 - p2_align`
+    // lies strictly inside the caller's buffer (never reading outside
+    // `[0, count)`).
+    if (p2_align != 0)
+      lead += ALIGN;
+    if (lead != 0) {
+      if (auto value = inline_bcmp_byte_per_byte(p1, p2, lead))
+        return value;
+      p1 += lead;
+      p2 += lead;
+      count -= lead;
+    }
+    auto load_word = [](CPtr p) -> Word {
+      return load_unaligned<Word>(assume_aligned<ALIGN>(p));
+    };
+    if (p2_align == 0) {
+      if constexpr (ALIGN == 8) {
+        LIBC_LOOP_NOUNROLL
+        for (; count >= 32; p1 += 32, p2 += 32, count -= 32) {
+          if ((load_word(p1) ^ load_word(p2)) |
+              (load_word(p1 + 8) ^ load_word(p2 + 8)) |
+              (load_word(p1 + 16) ^ load_word(p2 + 16)) |
+              (load_word(p1 + 24) ^ load_word(p2 + 24)))
+            return BcmpReturnType::nonzero();
+        }
+      }
+      LIBC_LOOP_NOUNROLL
+      for (; count >= ALIGN; p1 += ALIGN, p2 += ALIGN, count -= ALIGN) {
+        if (load_word(p1) != load_word(p2))
+          return BcmpReturnType::nonzero();
+      }
+    } else if (count >= 2 * ALIGN) {
+      CPtr p2_base = p2 - p2_align;
+      const unsigned sh_lo = static_cast<unsigned>(p2_align * 8);
+      const unsigned sh_hi = static_cast<unsigned>((ALIGN * 8) - sh_lo);
+      Word prev = load_word(p2_base);
+      LIBC_LOOP_NOUNROLL
+      for (; count >= 2 * ALIGN;
+           p1 += ALIGN, p2_base += ALIGN, count -= ALIGN) {
+        const Word next = load_word(p2_base + ALIGN);
+        const Word w2 = Endian::IS_LITTLE ? (prev >> sh_lo) | (next << sh_hi)
+                                          : (prev << sh_lo) | (next >> sh_hi);
+        if (load_word(p1) != w2)
+          return BcmpReturnType::nonzero();
+        prev = next;
+      }
+      p2 = p2_base + p2_align;
+    }
   }
-  return inline_bcmp_byte_per_byte(p1, p2, count, offset);
+  return inline_bcmp_byte_per_byte(p1, p2, count);
 }
 
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
+[[maybe_unused]] LIBC_ALWAYS_INLINE BcmpReturnType
+inline_bcmp_aligned_access_32bit(CPtr p1, CPtr p2, size_t count) {
+  return inline_bcmp_aligned_access<uint32_t>(p1, p2, count);
+}
+
+[[maybe_unused]] LIBC_ALWAYS_INLINE BcmpReturnType
 inline_bcmp_aligned_access_64bit(CPtr p1, CPtr p2, size_t count) {
-  constexpr size_t kAlign = sizeof(uint64_t);
-  if (count <= 2 * kAlign)
-    return inline_bcmp_byte_per_byte(p1, p2, count);
-  size_t bytes_to_p1_align = distance_to_align_up<kAlign>(p1);
-  if (auto value = inline_bcmp_byte_per_byte(p1, p2, bytes_to_p1_align))
-    return value;
-  size_t offset = bytes_to_p1_align;
-  size_t p2_alignment = distance_to_align_down<kAlign>(p2 + offset);
-  for (; offset < count - kAlign; offset += kAlign) {
-    uint64_t a = load64_aligned<uint64_t>(p1, offset);
-    uint64_t b = load64_aligned(p2, offset, p2_alignment);
-    if (a != b)
-      return BcmpReturnType::nonzero();
-  }
-  return inline_bcmp_byte_per_byte(p1, p2, count, offset);
+  return inline_bcmp_aligned_access<uint64_t>(p1, p2, count);
 }
 
 ///////////////////////////////////////////////////////////////////////////////
diff --git a/libc/src/string/memory_utils/generic/bcmp_utils.h b/libc/src/string/memory_utils/generic/bcmp_utils.h
new file mode 100644
index 00000000000000..47290035509852
--- /dev/null
+++ b/libc/src/string/memory_utils/generic/bcmp_utils.h
@@ -0,0 +1,184 @@
+//===-- Shared bcmp building blocks -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_BCMP_UTILS_H
+#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_BCMP_UTILS_H
+
+#include "hdr/stdint_proxy.h"
+#include "src/__support/CPP/cstddef.h"
+#include "src/__support/macros/attributes.h" // LIBC_ALWAYS_INLINE, LIBC_INLINE
+#include "src/__support/macros/config.h"     // LIBC_NAMESPACE_DECL
+#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY, LIBC_LOOP_NOUNROLL
+#include "src/__support/macros/properties/architectures.h"
+#include "src/__support/macros/properties/compiler.h" // LIBC_COMPILER_IS_MSVC
+#include "src/__support/macros/properties/types.h"    // LIBC_TYPES_HAS_INT64
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType, load_unaligned
+
+#include <stddef.h> // size_t
+
+namespace LIBC_NAMESPACE_DECL {
+namespace internal {
+
+template <typename T> LIBC_INLINE T bcmp_xor(CPtr p1, CPtr p2) {
+  return load_unaligned<T>(p1) ^ load_unaligned<T>(p2);
+}
+
+// Compares count bytes for count in 1..3 without reading outside [0, count).
+LIBC_ALWAYS_INLINE BcmpReturnType bcmp_exact_1_to_3(CPtr p1, CPtr p2,
+                                                    size_t count) {
+  return cpp::to_integer<uint32_t>((p1[0] ^ p2[0]) |
+                                   (p1[count - 1] ^ p2[count - 1]) |
+                                   (p1[count >> 1] ^ p2[count >> 1]));
+}
+
+// Compares count bytes for count in 2..3 without reading outside [0, count).
+LIBC_INLINE BcmpReturnType bcmp_2_to_3(CPtr p1, CPtr p2, size_t count) {
+  const size_t tail = count - sizeof(uint16_t);
+  return static_cast<uint32_t>(bcmp_xor<uint16_t>(p1, p2) |
+                               bcmp_xor<uint16_t>(p1 + tail, p2 + tail));
+}
+
+// Compares count bytes for count in 4..8 without reading outside [0, count).
+// On x86-64, checking the tail with a predicted-not-taken branch and returning
+// the head XOR keeps the `(count - 4)` AGU off the equal-path critical path and
+// lets the compare fuse with a load and branch. Hoisting both head loads while
+// keeping the XOR after the branch avoids both sinking the loads and tail-
+// merging an empty `ret` with AVX `vzeroupper; ret`. On AArch64, LLVM
+// if-converts a tail branch into `cmp` + `csinc`, so OR-ing both XORs stays on
+// general ALU pipes instead.
+LIBC_INLINE BcmpReturnType bcmp_4_to_8(CPtr p1, CPtr p2, size_t count) {
+  const size_t tail = count - sizeof(uint32_t);
+#if defined(LIBC_TARGET_ARCH_IS_X86_64) && !defined(LIBC_COMPILER_IS_MSVC)
+  uint32_t h1 = load_unaligned<uint32_t>(p1);
+  uint32_t h2 = load_unaligned<uint32_t>(p2);
+  asm("" : "+r"(h1), "+r"(h2));
+  if (LIBC_UNLIKELY(load_unaligned<uint32_t>(p1 + tail) !=
+                    load_unaligned<uint32_t>(p2 + tail)))
+    return BcmpReturnType::nonzero();
+  return h1 ^ h2;
+#else
+  return bcmp_xor<uint32_t>(p1, p2) | bcmp_xor<uint32_t>(p1 + tail, p2 + tail);
+#endif
+}
+
+// Compares count bytes for count in 0..8 without reading outside [0, count).
+// Checking `count >= 4` then `count >= 2` keeps the rare `count == 0` exit off
+// the 2..8 paths and uses minimal loads for predictable short sizes.
+LIBC_INLINE BcmpReturnType bcmp_0_to_8(CPtr p1, CPtr p2, size_t count) {
+  if (count >= 4)
+    return bcmp_4_to_8(p1, p2, count);
+  if (count >= 2)
+    return bcmp_2_to_3(p1, p2, count);
+  if (LIBC_UNLIKELY(count == 0))
+    return BcmpReturnType::zero();
+  return cpp::to_integer<uint32_t>(p1[0] ^ p2[0]);
+}
+
+// Compares count in 9..16 using non-adjacent 32-bit loads so LLVM keeps all
+// loads in GPRs (avoiding NEON SLP `vmov` and unaligned `ldrd`/`ldm` on Arm).
+LIBC_INLINE BcmpReturnType bcmp_9_to_16_32bit(CPtr p1, CPtr p2, size_t count) {
+  if (LIBC_UNLIKELY((bcmp_xor<uint32_t>(p1 + 4, p2 + 4) |
+                     bcmp_xor<uint32_t>(p1 + count - 8, p2 + count - 8)) != 0))
+    return BcmpReturnType::nonzero();
+  return bcmp_xor<uint32_t>(p1, p2) |
+         bcmp_xor<uint32_t>(p1 + count - 4, p2 + count - 4);
+}
+
+#ifdef LIBC_TYPES_HAS_INT64
+
+// Compares count in 9..16: predicted early exit on `[4, count)` and direct
+// 32-bit XOR return on `[0, 4)` (no `setne`/`cset` or `count`-indexed AGU).
+LIBC_INLINE BcmpReturnType bcmp_9_to_16(CPtr p1, CPtr p2, size_t count) {
+  if (LIBC_UNLIKELY((bcmp_xor<uint32_t>(p1 + 4, p2 + 4) |
+                     bcmp_xor<uint64_t>(p1 + count - 8, p2 + count - 8)) != 0))
+    return BcmpReturnType::nonzero();
+  return bcmp_xor<uint32_t>(p1, p2);
+}
+
+// Branchless 17..32 comparison using 64-bit loads. Interleaving head and tail
+// pairs prevents LLVM from SLP-vectorizing adjacent loads on RVV targets.
+LIBC_INLINE BcmpReturnType bcmp_17_to_32_64bit(CPtr p1, CPtr p2, size_t count) {
+  const uint64_t d0 = bcmp_xor<uint64_t>(p1, p2) |
+                      bcmp_xor<uint64_t>(p1 + count - 16, p2 + count - 16);
+  const uint64_t d1 = bcmp_xor<uint64_t>(p1 + 8, p2 + 8) |
+                      bcmp_xor<uint64_t>(p1 + count - 8, p2 + count - 8);
+  return static_cast<uint32_t>((d0 | d1) != 0);
+}
+
+LIBC_INLINE bool bcmp_32_64bit_ne(CPtr p1, CPtr p2) {
+  return (bcmp_xor<uint64_t>(p1, p2) | bcmp_xor<uint64_t>(p1 + 8, p2 + 8) |
+          bcmp_xor<uint64_t>(p1 + 16, p2 + 16) |
+          bcmp_xor<uint64_t>(p1 + 24, p2 + 24)) != 0;
+}
+
+#endif // LIBC_TYPES_HAS_INT64
+
+} // namespace internal
+
+// Generic unaligned 32-bit scalar `bcmp` (32-bit Arm with unaligned support,
+// x86-32 without SSE2, RV32 with `__riscv_misaligned_fast`). Stride-8 pairing
+// keeps all loads in GPRs (no NEON SLP `vmov` or unaligned `ldrd`/`ldm`).
+[[maybe_unused]] LIBC_ALWAYS_INLINE BcmpReturnType
+inline_bcmp_unaligned_32bit(CPtr p1, CPtr p2, size_t count) {
+  if (count <= 8)
+    return internal::bcmp_0_to_8(p1, p2, count);
+  if (count <= 16)
+    return internal::bcmp_9_to_16_32bit(p1, p2, count);
+  LIBC_LOOP_NOUNROLL
+  for (size_t i = 0; i < count - 16; i += 16) {
+    if (LIBC_UNLIKELY((internal::bcmp_xor<uint32_t>(p1 + i, p2 + i) |
+                       internal::bcmp_xor<uint32_t>(p1 + i + 8, p2 + i + 8)) !=
+                      0))
+      return BcmpReturnType::nonzero();
+    if (LIBC_UNLIKELY(
+            (internal::bcmp_xor<uint32_t>(p1 + i + 4, p2 + i + 4) |
+             internal::bcmp_xor<uint32_t>(p1 + i + 12, p2 + i + 12)) != 0))
+      return BcmpReturnType::nonzero();
+  }
+  const CPtr tail1 = p1 + count - 16;
+  const CPtr tail2 = p2 + count - 16;
+  if (LIBC_UNLIKELY((internal::bcmp_xor<uint32_t>(tail1 + 4, tail2 + 4) |
+                     internal::bcmp_xor<uint32_t>(tail1 + 12, tail2 + 12)) !=
+                    0))
+    return BcmpReturnType::nonzero();
+  return internal::bcmp_xor<uint32_t>(tail1, tail2) |
+         internal::bcmp_xor<uint32_t>(tail1 + 8, tail2 + 8);
+}
+
+#ifdef LIBC_TYPES_HAS_INT64
+
+// Generic unaligned 64-bit scalar `bcmp` (x86-64 without SSE2, AArch64
+// `-mgeneral-regs-only`, RV64 with `__riscv_misaligned_fast`).
+[[maybe_unused]] LIBC_ALWAYS_INLINE BcmpReturnType
+inline_bcmp_unaligned_64bit(CPtr p1, CPtr p2, size_t count) {
+  if (count <= 8)
+    return internal::bcmp_0_to_8(p1, p2, count);
+  if (count <= 16)
+    return internal::bcmp_9_to_16(p1, p2, count);
+  if (count <= 32)
+    return internal::bcmp_17_to_32_64bit(p1, p2, count);
+  if (LIBC_UNLIKELY(internal::bcmp_32_64bit_ne(p1, p2)))
+    return BcmpReturnType::nonzero();
+  if (count > 64) {
+    const size_t last = count - 32;
+    LIBC_LOOP_NOUNROLL
+    for (size_t i = 32 - static_cast<size_t>(distance_to_align_down<8>(p1));
+         i < last; i += 32) {
+      if (LIBC_UNLIKELY(internal::bcmp_32_64bit_ne(p1 + i, p2 + i)))
+        return BcmpReturnType::nonzero();
+    }
+  }
+  return static_cast<uint32_t>(
+      internal::bcmp_32_64bit_ne(p1 + count - 32, p2 + count - 32));
+}
+
+#endif // LIBC_TYPES_HAS_INT64
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_BCMP_UTILS_H
diff --git a/libc/src/string/memory_utils/inline_bcmp.h b/libc/src/string/memory_utils/inline_bcmp.h
index b241e999a6aae1..3f4e7db2704173 100644
--- a/libc/src/string/memory_utils/inline_bcmp.h
+++ b/libc/src/string/memory_utils/inline_bcmp.h
@@ -9,10 +9,10 @@
 #ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_BCMP_H
 #define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_BCMP_H
 
-#include "src/__support/common.h"
-#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "src/__support/macros/attributes.h" // LIBC_ALWAYS_INLINE, LIBC_FLATTEN
 #include "src/__support/macros/config.h"     // LIBC_NAMESPACE_DECL
 #include "src/__support/macros/properties/architectures.h" // LIBC_TARGET_ARCH_IS_
+#include "src/string/memory_utils/utils.h"                 // CPtr
 
 #include <stddef.h> // size_t
 
@@ -23,8 +23,21 @@
 #include "src/string/memory_utils/x86_64/inline_bcmp.h"
 #define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_x86
 #elif defined(LIBC_TARGET_ARCH_IS_AARCH64)
+#if defined(__ARM_FEATURE_UNALIGNED) || defined(_M_ARM64)
 #include "src/string/memory_utils/aarch64/inline_bcmp.h"
-#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aarch64_dispatch
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aarch64
+#else
+#include "src/string/memory_utils/generic/aligned_access.h"
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aligned_access_64bit
+#endif
+#elif defined(LIBC_TARGET_ARCH_IS_ARM)
+#if defined(__ARM_FEATURE_UNALIGNED)
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_unaligned_32bit
+#else
+#include "src/string/memory_utils/generic/aligned_access.h"
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aligned_access_32bit
+#endif
 #elif defined(LIBC_TARGET_ARCH_IS_ANY_RISCV)
 #include "src/string/memory_utils/riscv/inline_bcmp.h"
 #define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_riscv
@@ -35,8 +48,10 @@
 
 namespace LIBC_NAMESPACE_DECL {
 
-LIBC_FLATTEN LIBC_INLINE int inline_bcmp(const void *p1, const void *p2,
-                                         size_t count) {
+// Always inline so `bcmp` (aligned to 64 bytes) does not emit a tail-call stub
+// to an unaligned out-of-line `inline_bcmp`.
+LIBC_FLATTEN LIBC_ALWAYS_INLINE int inline_bcmp(const void *p1, const void *p2,
+                                                size_t count) {
   return static_cast<int>(LIBC_SRC_STRING_MEMORY_UTILS_BCMP(
       reinterpret_cast<CPtr>(p1), reinterpret_cast<CPtr>(p2), count));
 }
diff --git a/libc/src/string/memory_utils/riscv/inline_bcmp.h b/libc/src/string/memory_utils/riscv/inline_bcmp.h
index 666ad6382412e5..300ca980596874 100644
--- a/libc/src/string/memory_utils/riscv/inline_bcmp.h
+++ b/libc/src/string/memory_utils/riscv/inline_bcmp.h
@@ -5,30 +5,84 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===----------------------------------------------------------------------===//
-#ifndef LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
-#define LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
+#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
+#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
 
-#include "src/__support/macros/attributes.h"               // LIBC_INLINE
-#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
-#include "src/__support/macros/properties/architectures.h" // LIBC_TARGET_ARCH_IS_RISCV64
-#include "src/string/memory_utils/generic/aligned_access.h"
-#include "src/string/memory_utils/utils.h" // Ptr, CPtr
+#include "hdr/stdint_proxy.h"
+#include "src/__support/macros/attributes.h"   // LIBC_INLINE
+#include "src/__support/macros/config.h"       // LIBC_NAMESPACE_DECL
+#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
+#include "src/__support/macros/properties/architectures.h"
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType
 
 #include <stddef.h> // size_t
 
+#if !defined(LIBC_TARGET_ARCH_IS_RISCV64) &&                                   \
+    !defined(LIBC_TARGET_ARCH_IS_RISCV32)
+#error "Unimplemented"
+#endif
+
+#if defined(__riscv_vector) && defined(__riscv_v_intrinsic) &&                 \
+    (__riscv_v_intrinsic >= 11000)
+#include <riscv_vector.h>
+#define LIBC_RISCV_HAS_RVV
+#elif !defined(__riscv_misaligned_fast)
+#include "src/string/memory_utils/generic/aligned_access.h"
+#endif
+
 namespace LIBC_NAMESPACE_DECL {
 
 [[maybe_unused]] LIBC_INLINE BcmpReturnType inline_bcmp_riscv(CPtr p1, CPtr p2,
                                                               size_t count) {
-#if defined(LIBC_TARGET_ARCH_IS_RISCV64)
+#ifdef LIBC_RISCV_HAS_RVV
+#ifdef __riscv_misaligned_fast
+  if (count <= 8)
+    return internal::bcmp_0_to_8(p1, p2, count);
+#ifdef LIBC_TARGET_ARCH_IS_RISCV64
+  if (count <= 16)
+    return internal::bcmp_9_to_16(p1, p2, count);
+  if (count <= 32)
+    return internal::bcmp_17_to_32_64bit(p1, p2, count);
+#else
+  if (count <= 16)
+    return internal::bcmp_9_to_16_32bit(p1, p2, count);
+#endif
+#else
+  if (count == 0)
+    return BcmpReturnType::zero();
+  if (count <= 3)
+    return internal::bcmp_exact_1_to_3(p1, p2, count);
+#endif
+  // VLA RVV 1.0 loop (LMUL=4); `do..while` avoids a loop-back branch on
+  // single-chunk inputs after short sizes exit above.
+  do {
+    const size_t vl = __riscv_vsetvl_e8m4(count);
+    const vuint8m4_t v1 =
+        __riscv_vle8_v_u8m4(reinterpret_cast<const uint8_t *>(p1), vl);
+    const vuint8m4_t v2 =
+        __riscv_vle8_v_u8m4(reinterpret_cast<const uint8_t *>(p2), vl);
+    const vbool2_t ne = __riscv_vmsne_vv_u8m4_b2(v1, v2, vl);
+    if (LIBC_UNLIKELY(__riscv_vfirst_m_b2(ne, vl) >= 0))
+      return BcmpReturnType::nonzero();
+    p1 += vl;
+    p2 += vl;
+    count -= vl;
+  } while (count > 0);
+  return BcmpReturnType::zero();
+#elif defined(__riscv_misaligned_fast) && defined(LIBC_TARGET_ARCH_IS_RISCV64)
+  return inline_bcmp_unaligned_64bit(p1, p2, count);
+#elif defined(__riscv_misaligned_fast)
+  return inline_bcmp_unaligned_32bit(p1, p2, count);
+#elif defined(LIBC_TARGET_ARCH_IS_RISCV64)
   return inline_bcmp_aligned_access_64bit(p1, p2, count);
-#elif defined(LIBC_TARGET_ARCH_IS_RISCV32)
-  return inline_bcmp_aligned_access_32bit(p1, p2, count);
 #else
-#error "Unimplemented"
+  return inline_bcmp_aligned_access_32bit(p1, p2, count);
 #endif
 }
 
 } // namespace LIBC_NAMESPACE_DECL
 
-#endif // LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
+#undef LIBC_RISCV_HAS_RVV
+
+#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
diff --git a/libc/src/string/memory_utils/x86_64/inline_bcmp.h b/libc/src/string/memory_utils/x86_64/inline_bcmp.h
index 0eaf968f2f78db..d21b9ecedd9cbe 100644
--- a/libc/src/string/memory_utils/x86_64/inline_bcmp.h
+++ b/libc/src/string/memory_utils/x86_64/inline_bcmp.h
@@ -1,4 +1,4 @@
-//===-- Bcmp implementation for x86_64 --------------------------*- C++ -*-===//
+//===-- Bcmp implementation for x86 -----------------------------*- C++ -*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -8,84 +8,201 @@
 #ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_X86_64_INLINE_BCMP_H
 #define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_X86_64_INLINE_BCMP_H
 
-#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "hdr/stdint_proxy.h"
+#include "src/__support/macros/attributes.h" // LIBC_INLINE, LIBC_NOINLINE
 #include "src/__support/macros/config.h"     // LIBC_NAMESPACE_DECL
-#include "src/string/memory_utils/op_generic.h"
-#include "src/string/memory_utils/op_x86.h"
-#include "src/string/memory_utils/utils.h" // Ptr, CPtr
+#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY, LIBC_LOOP_NOUNROLL
+#include "src/__support/macros/properties/architectures.h"
+#include "src/__support/macros/properties/cpu_features.h" // LIBC_TARGET_CPU_HAS_SSE2
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType, load_unaligned
 
 #include <stddef.h> // size_t
 
+#if defined(LIBC_TARGET_CPU_HAS_SSE2)
+#include <immintrin.h>
+#endif
+
 namespace LIBC_NAMESPACE_DECL {
 
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_generic_gt16(CPtr p1, CPtr p2, size_t count) {
-  return generic::Bcmp<uint64_t>::loop_and_tail_align_above(256, p1, p2, count);
+#if defined(LIBC_TARGET_CPU_HAS_SSE2)
+namespace internal {
+
+LIBC_INLINE __m128i sse2_eq_16(CPtr a, CPtr b) {
+  return _mm_cmpeq_epi8(load_unaligned<__m128i>(a), load_unaligned<__m128i>(b));
 }
 
-#if defined(__SSE4_1__)
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_x86_sse41_gt16(CPtr p1, CPtr p2, size_t count) {
-  if (count <= 32)
-    return generic::Bcmp<__m128i>::head_tail(p1, p2, count);
-  return generic::Bcmp<__m128i>::loop_and_tail_align_above(256, p1, p2, count);
+LIBC_INLINE __m128i sse2_eq_32(CPtr a, CPtr b) {
+  return _mm_and_si128(sse2_eq_16(a, b), sse2_eq_16(a + 16, b + 16));
 }
-#endif // __SSE4_1__
 
-#if defined(__AVX__)
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_x86_avx_gt16(CPtr p1, CPtr p2, size_t count) {
-  if (count <= 32)
-    return generic::Bcmp<__m128i>::head_tail(p1, p2, count);
-  if (count <= 64)
-    return generic::Bcmp<__m256i>::head_tail(p1, p2, count);
-  return generic::Bcmp<__m256i>::loop_and_tail_align_above(256, p1, p2, count);
+LIBC_INLINE uint32_t sse2_mismatch_mask(__m128i eq) {
+  return static_cast<uint32_t>(_mm_movemask_epi8(eq)) ^ 0xffffU;
 }
-#endif // __AVX__
 
-#if defined(__AVX512BW__)
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_x86_avx512bw_gt16(CPtr p1, CPtr p2, size_t count) {
-  if (count <= 32)
-    return generic::Bcmp<__m128i>::head_tail(p1, p2, count);
-  if (count <= 64)
-    return generic::Bcmp<__m256i>::head_tail(p1, p2, count);
-  if (count <= 128)
-    return generic::Bcmp<__m512i>::head_tail(p1, p2, count);
-  return generic::Bcmp<__m512i>::loop_and_tail_align_above(256, p1, p2, count);
+// 17..32 and 33..64 return a 16- or 32-bit mismatch bitmask directly in `int`
+// (avoiding `ptest` + `setcc`). With AVX-512VL+BW, `_mm*_cmpneq_epi8_mask` runs
+// both comparisons in parallel and combines with `kor` instead of LLVM lowering
+// `and(cmpeq, cmpeq)` to a serialized masked `vpcmpeqb %k0{%k1}`.
+LIBC_INLINE BcmpReturnType bcmp_x86_17_to_32(CPtr p1, CPtr p2, size_t count) {
+#if defined(__AVX512VL__) && defined(__AVX512BW__)
+  const __mmask16 head_ne = _mm_cmpneq_epi8_mask(load_unaligned<__m128i>(p1),
+                                                 load_unaligned<__m128i>(p2));
+  const __mmask16 tail_ne =
+      _mm_cmpneq_epi8_mask(load_unaligned<__m128i>(p1 + count - 16),
+                           load_unaligned<__m128i>(p2 + count - 16));
+  return static_cast<uint32_t>(head_ne | tail_ne);
+#else
+  return sse2_mismatch_mask(_mm_and_si128(
+      sse2_eq_16(p1, p2), sse2_eq_16(p1 + count - 16, p2 + count - 16)));
+#endif
+}
+
+#if defined(LIBC_TARGET_ARCH_IS_X86_32)
+
+// Compact 32-byte SSE2 loop + tail for 32-bit x86 (low GPR count & code size).
+LIBC_INLINE BcmpReturnType bcmp_x86_32_gt32(CPtr p1, CPtr p2, size_t count) {
+  LIBC_LOOP_NOUNROLL
+  for (size_t i = 0; i < count - 32; i += 32) {
+    if (LIBC_UNLIKELY(_mm_movemask_epi8(sse2_eq_32(p1 + i, p2 + i)) != 0xffff))
+      return BcmpReturnType::nonzero();
+  }
+  return sse2_mismatch_mask(sse2_eq_32(p1 + count - 32, p2 + count - 32));
+}
+
+#else // x86-64
+
+LIBC_INLINE BcmpReturnType bcmp_x86_33_to_64(CPtr p1, CPtr p2, size_t count) {
+#if defined(__AVX512VL__) && defined(__AVX512BW__)
+  const __mmask32 head_ne = _mm256_cmpneq_epi8_mask(
+      load_unaligned<__m256i>(p1), load_unaligned<__m256i>(p2));
+  const __mmask32 tail_ne =
+      _mm256_cmpneq_epi8_mask(load_unaligned<__m256i>(p1 + count - 32),
+                              load_unaligned<__m256i>(p2 + count - 32));
+  return static_cast<uint32_t>(head_ne | tail_ne);
+#elif defined(__AVX2__)
+  const __m256i eq = _mm256_and_si256(
+      _mm256_cmpeq_epi8(load_unaligned<__m256i>(p1),
+                        load_unaligned<__m256i>(p2)),
+      _mm256_cmpeq_epi8(load_unaligned<__m256i>(p1 + count - 32),
+                        load_unaligned<__m256i>(p2 + count - 32)));
+  return ~static_cast<uint32_t>(_mm256_movemask_epi8(eq));
+#else
+  return sse2_mismatch_mask(_mm_and_si128(
+      sse2_eq_32(p1, p2), sse2_eq_32(p1 + count - 32, p2 + count - 32)));
+#endif
+}
+
+// Out-of-line tail-called > 64-byte handler keeping the 0..64 fast path small
+// and its instruction layout and `vzeroupper` placement clean. Medium sizes
+// (`65..256` AVX2 / `65..128` SSE2) return the mismatch mask of the first block
+// directly while checking remaining bytes with predicted early-exit branches,
+// hiding tail load latency on equal inputs. Larger sizes check the head before
+// entering the aligned loop so early mismatches exit immediately.
+#if defined(__AVX2__)
+LIBC_NOINLINE LIBC_INLINE uint32_t bcmp_x86_over_64(CPtr p1, CPtr p2,
+                                                    size_t count) {
+  auto xor_32 = [](CPtr a, CPtr b) -> __m256i {
+    return _mm256_xor_si256(load_unaligned<__m256i>(a),
+                            load_unaligned<__m256i>(b));
+  };
+  auto xor_128 = [&](CPtr a, CPtr b) -> __m256i {
+    return _mm256_or_si256(
+        _mm256_or_si256(xor_32(a, b), xor_32(a + 32, b + 32)),
+        _mm256_or_si256(xor_32(a + 64, b + 64), xor_32(a + 96, b + 96)));
+  };
+  const __m256i head_eq = _mm256_cmpeq_epi8(load_unaligned<__m256i>(p1),
+                                            load_unaligned<__m256i>(p2));
+  const __m256i second_xor = xor_32(p1 + 32, p2 + 32);
+  if (count <= 128) {
+    const __m256i rest_xor = _mm256_or_si256(
+        _mm256_or_si256(second_xor, xor_32(p1 + count - 64, p2 + count - 64)),
+        xor_32(p1 + count - 32, p2 + count - 32));
+    if (LIBC_UNLIKELY(!_mm256_testz_si256(rest_xor, rest_xor)))
+      return 1;
+    return ~static_cast<uint32_t>(_mm256_movemask_epi8(head_eq));
+  }
+  const __m256i head_rest =
+      _mm256_or_si256(second_xor, _mm256_or_si256(xor_32(p1 + 64, p2 + 64),
+                                                  xor_32(p1 + 96, p2 + 96)));
+  const size_t last = count - 128;
+  if (count <= 256) {
+    const __m256i rest_xor =
+        _mm256_or_si256(head_rest, xor_128(p1 + last, p2 + last));
+    if (LIBC_UNLIKELY(!_mm256_testz_si256(rest_xor, rest_xor)))
+      return 1;
+    return ~static_cast<uint32_t>(_mm256_movemask_epi8(head_eq));
+  }
+  if (LIBC_UNLIKELY(~static_cast<uint32_t>(_mm256_movemask_epi8(head_eq)) !=
+                        0 ||
+                    !_mm256_testz_si256(head_rest, head_rest)))
+    return 1;
+  for (size_t i = 128 - static_cast<size_t>(distance_to_align_down<32>(p1));
+       i < last; i += 128) {
+    const __m256i block_xor = xor_128(p1 + i, p2 + i);
+    if (LIBC_UNLIKELY(!_mm256_testz_si256(block_xor, block_xor)))
+      return 1;
+  }
+  const __m256i tail_xor = xor_128(p1 + last, p2 + last);
+  return ~static_cast<uint32_t>(_mm256_movemask_epi8(
+      _mm256_cmpeq_epi8(tail_xor, _mm256_setzero_si256())));
+}
+#else
+LIBC_NOINLINE LIBC_INLINE uint32_t bcmp_x86_over_64(CPtr p1, CPtr p2,
+                                                    size_t count) {
+  auto eq_64 = [](CPtr a, CPtr b) -> __m128i {
+    return _mm_and_si128(sse2_eq_32(a, b), sse2_eq_32(a + 32, b + 32));
+  };
+  const __m128i head_eq = sse2_eq_32(p1, p2);
+  const __m128i second_eq = sse2_eq_32(p1 + 32, p2 + 32);
+  const size_t last = count - 64;
+  if (count <= 128) {
+    if (LIBC_UNLIKELY(_mm_movemask_epi8(_mm_and_si128(
+                          second_eq, eq_64(p1 + last, p2 + last))) != 0xffff))
+      return 1;
+    return sse2_mismatch_mask(head_eq);
+  }
+  if (LIBC_UNLIKELY(_mm_movemask_epi8(_mm_and_si128(head_eq, second_eq)) !=
+                    0xffff))
+    return 1;
+  for (size_t i = 64 - static_cast<size_t>(distance_to_align_down<16>(p1));
+       i < last; i += 64) {
+    if (LIBC_UNLIKELY(_mm_movemask_epi8(eq_64(p1 + i, p2 + i)) != 0xffff))
+      return 1;
+  }
+  return sse2_mismatch_mask(eq_64(p1 + last, p2 + last));
 }
-#endif // __AVX512BW__
+#endif // __AVX2__ / SSE2
+
+#endif // LIBC_TARGET_ARCH_IS_X86_32
+
+} // namespace internal
+#endif // LIBC_TARGET_CPU_HAS_SSE2
 
 [[maybe_unused]] LIBC_INLINE BcmpReturnType inline_bcmp_x86(CPtr p1, CPtr p2,
                                                             size_t count) {
-  if (count == 0)
-    return BcmpReturnType::zero();
-  if (count == 1)
-    return generic::Bcmp<uint8_t>::block(p1, p2);
-  if (count == 2)
-    return generic::Bcmp<uint16_t>::block(p1, p2);
-  if (count == 3)
-    return generic::BcmpSequence<uint16_t, uint8_t>::block(p1, p2);
-  if (count == 4)
-    return generic::Bcmp<uint32_t>::block(p1, p2);
-  if (count == 5)
-    return generic::BcmpSequence<uint32_t, uint8_t>::block(p1, p2);
-  if (count == 6)
-    return generic::BcmpSequence<uint32_t, uint16_t>::block(p1, p2);
-  if (count == 7)
-    return generic::BcmpSequence<uint32_t, uint16_t, uint8_t>::block(p1, p2);
-  if (count == 8)
-    return generic::Bcmp<uint64_t>::block(p1, p2);
+#if defined(LIBC_TARGET_CPU_HAS_SSE2)
+  if (count <= 8)
+    return internal::bcmp_0_to_8(p1, p2, count);
+#if defined(LIBC_TARGET_ARCH_IS_X86_32)
+  if (count <= 16)
+    return internal::bcmp_9_to_16_32bit(p1, p2, count);
+  if (count <= 32)
+    return internal::bcmp_x86_17_to_32(p1, p2, count);
+  return internal::bcmp_x86_32_gt32(p1, p2, count);
+#else
   if (count <= 16)
-    return generic::Bcmp<uint64_t>::head_tail(p1, p2, count);
-#if defined(__AVX512BW__)
-  return inline_bcmp_x86_avx512bw_gt16(p1, p2, count);
-#elif defined(__AVX__)
-  return inline_bcmp_x86_avx_gt16(p1, p2, count);
-#elif defined(__SSE4_1__)
-  return inline_bcmp_x86_sse41_gt16(p1, p2, count);
+    return internal::bcmp_9_to_16(p1, p2, count);
+  if (count <= 32)
+    return internal::bcmp_x86_17_to_32(p1, p2, count);
+  if (count <= 64)
+    return internal::bcmp_x86_33_to_64(p1, p2, count);
+  return internal::bcmp_x86_over_64(p1, p2, count);
+#endif
+#elif defined(LIBC_TARGET_ARCH_IS_X86_32)
+  return inline_bcmp_unaligned_32bit(p1, p2, count);
 #else
-  return inline_bcmp_generic_gt16(p1, p2, count);
+  return inline_bcmp_unaligned_64bit(p1, p2, count);
 #endif
 }
 
diff --git a/libc/src/strings/bcmp.cpp b/libc/src/strings/bcmp.cpp
index 083f13d3f95d3a..2684ab45b7b7bc 100644
--- a/libc/src/strings/bcmp.cpp
+++ b/libc/src/strings/bcmp.cpp
@@ -8,11 +8,22 @@
 
 #include "src/strings/bcmp.h"
 #include "src/__support/common.h"
+#include "src/__support/macros/attributes.h"
 #include "src/__support/macros/config.h"
+#include "src/__support/macros/properties/architectures.h"
 #include "src/string/memory_utils/inline_bcmp.h"
 
 namespace LIBC_NAMESPACE_DECL {
 
+// Align to a 64-byte cache line on 64-bit targets so the 4..8 byte fast path
+// fits within a single cache line and avoids alignment-sensitive latency
+// swings.
+#if __has_cpp_attribute(gnu::aligned) &&                                       \
+    (defined(LIBC_TARGET_ARCH_IS_X86_64) ||                                    \
+     defined(LIBC_TARGET_ARCH_IS_AARCH64) ||                                   \
+     defined(LIBC_TARGET_ARCH_IS_RISCV64))
+[[gnu::aligned(64)]]
+#endif
 LLVM_LIBC_FUNCTION(int, bcmp,
                    (const void *lhs, const void *rhs, size_t count)) {
   return inline_bcmp(lhs, rhs, count);
diff --git a/libc/test/src/strings/bcmp_test.cpp b/libc/test/src/strings/bcmp_test.cpp
index 794f9a1b8bd9de..d0d7db80f06235 100644
--- a/libc/test/src/strings/bcmp_test.cpp
+++ b/libc/test/src/strings/bcmp_test.cpp
@@ -7,11 +7,16 @@
 //===----------------------------------------------------------------------===//
 
 #include "src/__support/macros/config.h"
+#include "src/__support/macros/properties/os.h" // LIBC_TARGET_OS_IS_LINUX
 #include "src/strings/bcmp.h"
 #include "test/UnitTest/Test.h"
 #include "test/UnitTest/TestLogger.h"
 #include "test/src/string/memory_utils/memory_check_utils.h"
 
+#if !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+#include "test/src/string/memory_utils/protected_pages.h"
+#endif // !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+
 namespace LIBC_NAMESPACE_DECL {
 
 TEST(LlvmLibcBcmpTest, CmpZeroByte) {
@@ -44,11 +49,11 @@ static inline int Adaptor(cpp::span<char> p1, cpp::span<char> p2, size_t size) {
 }
 
 TEST(LlvmLibcBcmpTest, SizeSweep) {
-  static constexpr size_t kMaxSize = 400;
+  static constexpr size_t kMaxSize = 600;
   Buffer Buffer1(kMaxSize);
   Buffer Buffer2(kMaxSize);
   Randomize(Buffer1.span());
-  for (size_t size = 0; size < kMaxSize; ++size) {
+  for (size_t size = 0; size <= kMaxSize; ++size) {
     auto span1 = Buffer1.span().subspan(0, size);
     auto span2 = Buffer2.span().subspan(0, size);
     const bool OK = CheckBcmp<Adaptor>(span1, span2, size);
@@ -58,4 +63,130 @@ TEST(LlvmLibcBcmpTest, SizeSweep) {
   }
 }
 
+static inline void check_flipped_byte(const char *a, char *b, size_t size,
+                                      size_t idx) {
+  b[idx] ^= 1;
+  ASSERT_NE(LIBC_NAMESPACE::bcmp(a, b, size), 0);
+  ASSERT_NE(LIBC_NAMESPACE::bcmp(b, a, size), 0);
+  b[idx] ^= 1;
+}
+
+// Offsets lhs across every alignment modulo 64 so aligned loops and unaligned
+// tails are exercised for all size classes.
+TEST(LlvmLibcBcmpTest, AlignmentSweep) {
+  static constexpr size_t MAX_OFFSET = 64;
+  static constexpr size_t MAX_SIZE = 600;
+  Buffer buffer1(MAX_OFFSET + MAX_SIZE);
+  Buffer buffer2(MAX_SIZE);
+  Randomize(buffer1.span());
+
+  auto check_size = [&](size_t size) {
+    for (size_t offset = 0; offset < MAX_OFFSET; ++offset) {
+      auto span1 = buffer1.span().subspan(offset, size);
+      auto span2 = buffer2.span().subspan(0, size);
+      if (size <= 72) {
+        ASSERT_TRUE(CheckBcmp<Adaptor>(span1, span2, size));
+        ASSERT_EQ(LIBC_NAMESPACE::bcmp(span2.data(), span1.data(), size), 0);
+      } else {
+        ReferenceCopy(span2, span1);
+        ASSERT_EQ(LIBC_NAMESPACE::bcmp(span1.data(), span2.data(), size), 0);
+        ASSERT_EQ(LIBC_NAMESPACE::bcmp(span2.data(), span1.data(), size), 0);
+        const size_t positions[] = {0, 1, 31, 32, 63, 64, size / 2, size - 1};
+        for (size_t i : positions)
+          check_flipped_byte(span1.data(), span2.data(), size, i);
+      }
+    }
+  };
+
+  for (size_t size = 0; size <= 72; ++size)
+    check_size(size);
+  const size_t bases[] = {126, 254, 510};
+  for (size_t base : bases)
+    for (size_t size = base; size <= base + 8; ++size)
+      check_size(size);
+  check_size(MAX_SIZE);
+}
+
+// Verify that bytes outside [0, size) never affect the result.
+TEST(LlvmLibcBcmpTest, IgnoresSurroundingBytes) {
+  static constexpr size_t PAD = 64;
+  static constexpr size_t MAX_SIZE = 64;
+  char lhs[PAD + MAX_SIZE + PAD];
+  char rhs[PAD + MAX_SIZE + PAD];
+
+  for (size_t size = 0; size <= MAX_SIZE; ++size) {
+    for (size_t i = 0; i < PAD; ++i) {
+      lhs[i] = lhs[PAD + size + i] = 'x';
+      rhs[i] = rhs[PAD + size + i] = 'y';
+    }
+    for (size_t i = 0; i < size; ++i)
+      lhs[PAD + i] = rhs[PAD + i] = static_cast<char>('a' + (i % 26));
+
+    ASSERT_EQ(LIBC_NAMESPACE::bcmp(lhs + PAD, rhs + PAD, size), 0);
+    if (size == 0)
+      continue;
+
+    for (size_t i = 0; i < PAD; ++i)
+      rhs[i] = rhs[PAD + size + i] = 'x';
+    check_flipped_byte(lhs + PAD, rhs + PAD, size, size - 1);
+    check_flipped_byte(lhs + PAD, rhs + PAD, size, 0);
+  }
+}
+
+#if !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+
+// Places buffers against inaccessible guard pages so out-of-page reads fault.
+TEST(LlvmLibcBcmpTest, CheckAccess) {
+  static constexpr size_t MAX_SIZE = 600;
+  LIBC_ASSERT(MAX_SIZE < GetPageSize());
+  ProtectedPages pages;
+  const Page page_a = pages.GetPageA().WithAccess(PROT_READ | PROT_WRITE);
+  const Page page_b = pages.GetPageB().WithAccess(PROT_READ | PROT_WRITE);
+  const size_t page_size = page_a.page_size;
+  Randomize(
+      cpp::span<char>(reinterpret_cast<char *>(page_a.page_ptr), page_size));
+
+  const void *inaccessible[] = {
+      nullptr,
+      page_a.page_ptr - 1,
+      page_a.page_ptr + page_size,
+  };
+  for (const void *bad : inaccessible) {
+    ASSERT_EQ(LIBC_NAMESPACE::bcmp(bad, bad, 0), 0);
+    ASSERT_EQ(LIBC_NAMESPACE::bcmp(page_a.page_ptr, bad, 0), 0);
+    ASSERT_EQ(LIBC_NAMESPACE::bcmp(bad, page_a.page_ptr, 0), 0);
+  }
+
+  for (size_t size = 1; size <= 64; ++size) {
+    for (size_t offset = 0; offset < 16; ++offset) {
+      cpp::span<char> rhs(reinterpret_cast<char *>(page_b.top(size) - offset),
+                          size);
+      uint8_t *a_ptrs[] = {page_a.bottom(size) + offset,
+                           page_a.top(size) - offset};
+      for (uint8_t *a_raw : a_ptrs) {
+        cpp::span<char> lhs(reinterpret_cast<char *>(a_raw), size);
+        ASSERT_TRUE(CheckBcmp<Adaptor>(lhs, rhs, size));
+        ASSERT_EQ(LIBC_NAMESPACE::bcmp(rhs.data(), lhs.data(), size), 0);
+      }
+    }
+  }
+
+  for (size_t size = 65; size <= MAX_SIZE; ++size) {
+    uint8_t *a_ptrs[] = {page_a.bottom(size), page_a.top(size)};
+    uint8_t *b_ptrs[] = {page_b.bottom(size), page_b.top(size)};
+    for (uint8_t *a_raw : a_ptrs) {
+      for (uint8_t *b_raw : b_ptrs) {
+        cpp::span<char> a(reinterpret_cast<char *>(a_raw), size);
+        cpp::span<char> b(reinterpret_cast<char *>(b_raw), size);
+        ReferenceCopy(b, a);
+        ASSERT_EQ(LIBC_NAMESPACE::bcmp(a.data(), b.data(), size), 0);
+        check_flipped_byte(a.data(), b.data(), size, 0);
+        check_flipped_byte(a.data(), b.data(), size, size - 1);
+      }
+    }
+  }
+}
+
+#endif // !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+
 } // namespace LIBC_NAMESPACE_DECL
diff --git a/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel
index e5e8c5bed7c4ce..07e21380d02a7d 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel
@@ -36,6 +36,7 @@ libc_support_library(
         "arm/inline_memcpy.h",
         "arm/inline_memset.h",
         "generic/aligned_access.h",
+        "generic/bcmp_utils.h",
         "generic/byte_per_byte.h",
         "generic/inline_strlen.h",
         "inline_bcmp.h",
diff --git a/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel
index faf6edb6adb2d7..8e59c99d883133 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel
@@ -55,7 +55,9 @@ libc_function(
     hdrs = ["bcmp.h"],
     deps = [
         "//libc/src/__support:common",
+        "//libc/src/__support/macros:attributes",
         "//libc/src/__support/macros:config",
+        "//libc/src/__support/macros/properties:architectures",
         "//libc/src/string/memory_utils",
     ],
 )
diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel
index 37ab5e139ae55f..b7c6c419f15b33 100644
--- a/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel
@@ -25,10 +25,16 @@ libc_test(
     name = "bcmp_test",
     srcs = ["bcmp_test.cpp"],
     deps = [
+        "//libc/src/__support/macros/properties:os",
         "//libc/src/strings:bcmp",
         "//libc/test/UnitTest:test_logger",
         "//libc/test/src/string:memory_check_utils",
-    ],
+    ] + select({
+        "//libc:full_build": [],
+        "//conditions:default": [
+            "//libc/test/src/string:protected_pages",
+        ],
+    }),
 )
 
 libc_test(



More information about the libc-commits mailing list