mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-11-24 15:02:44 +00:00
We shouldn't need to do this, and we should be able to rely on LLVM's
`StringRef::operator==` and similar routines to be efficient. But in
practice and after measuring, this seems to not be the case. =/
Both glibc and LLVM-libc have `bcmp` implementations significantly
slower than what we introduce here, and reaching into libc requires PLT
overhead and other challenges. I plan to send a PR to LLVM-libc of this
implementation to replace its `bcmp`. Until that lands and we can
reliably use it, having this makes a _dramatic_ impact on hashtable
performance for string keys, which happens to be the case we care very
much about in the compiler.
This implementation is somewhat based on the premise that hashtable keys
and other kinds of string comparisons are close enough in their expected
behavior and distribution of data sizes that we don't need to overly
specialize. We have data suggesting that _all_ string comparisons are
heavily biased towards short strings and latency-sensitive code paths,
much as hashtable keys are. This implementation specifically optimizes
for those two priorities: latency and short strings.
The overarching design of this string comparison has a few key ideas
that enable it to be efficient:
- Must be an efficient out-of-line function to allow callers to remain
good inline candidates. Also uses `preserve_most` to minimize register
pressure in the caller, and `pure` to avoid re-loading values from
memory.
- Avoid trying to pass `bool`, a defined `0` vs `1` value, or condition
flags across this out-of-line ABI boundary as they are not efficiently
represented and converting to these representations within the
implementation adds overhead. We want the caller to be able to have the
conditional branch that converts to a boolean state where it can be
fused and efficient. The out-of-line function needs to return an
efficient input to a caller's conditional branch. This motivates a
`uint64_t` result type which has the most flexibility for the
implementation.
- Overread for sizes up to 8 bytes when within the page -- we read 8
bytes and then mask off the bits that we were not allowed to read. This
has to be disabled when using sanitizers and we only support
little-endian masking, but is a _significant_ performance improvement
when available.
- Overlapping reads at the start and end: much like in hashing,
_duplicate_ reads are fine, and we can leverage this to handle a range
of sizes with common code, for example reading the first and last 8
bytes handles sizes 9 through 16 with identical code.
- Balance between branch-predictable returns of constants and returning
a computed non-zero value (via xor or other operation) for the caller to
branch on. Sometimes, it is useful to allow branch prediction to
early-exit the comparisons, other times it ends up better to compute the
data and let the caller's branch be predicted or not.
- Use relevant architecture and microarchitecture details when needed.
For example, we carefully select between vector operations and GPR
operations to minimize vector <-> GPR movement overhead.
The PR provides unit tests for the relevant size classes and various
boundary conditions.
We also provide benchmarks, both ones that measure _latency_ of the
comparison by causing each iteration to have a data dependency on the
prior iteration, and ones that measure _throughput_ by allowing each
iteration to run in parallel. Even though we optimize for latency first,
we want to have the best throughput we can.
Cycles per comparison (lower is better) vs. Linux glibc ("System") and
out-of-line LLVM-libc `inline_bcmp` ("LLVM"). "C++ ids" uses the C++
identifier length distribution. `System` and `LLVM` are relative to this
implementation: positive `%` and `>1x` mean this implementation is
faster; negative `%` and `<1x` mean it is slower; `~` is no significant
difference (p < 0.05).
AArch64 (armv8.2-a) on an Apple M1 P-core, cycles per comparison:
| Sizes | Latency | System | LLVM | Throughput | System | LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids | 21.3 | +41% | +40% | 12.5 | +93% | +100% |
| 1-3 | 14.4 | +48% | +64% | 5.0 | 3.99x | 3.83x |
| 4-8 | 14.5 | +55% | +46% | 5.0 | 2.30x | 3.02x |
| 9-16 | 14.6 | +47% | +29% | 4.0 | 2.22x | +95% |
| 17-32 | 17.6 | +20% | +50% | 5.2 | +38% | -21% |
| 33-64 | 20.1 | +40% | +47% | 7.2 | 2.68x | -16% |
| 65-256 | 36.9 | +49% | +17% | 30.0 | +57% | -3% |
| 257-1024 | 103.8 | +38% | +7% | 85.1 | +58% | +0.2% |
x86-64-v3 on an AMD Ryzen 9 9950X (Zen 5), cycles per comparison:
| Sizes | Latency | System | LLVM | Throughput | System | LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids | 24.0 | +1% | +75% | 18.1 | 0.39x | 2.36x |
| 1-3 | 14.4 | +57% | 2.34x | 4.7 | +7% | 7.24x |
| 4-8 | 14.4 | +57% | 2.62x | 4.7 | +7% | 8.36x |
| 9-16 | 15.0 | +53% | +5% | 5.9 | -15% | ~ |
| 17-32 | 22.8 | +0.4% | +10% | 7.0 | -29% | -21% |
| 33-64 | 25.8 | -6% | +6% | 7.1 | -16% | -5% |
| 65-256 | 45.1 | +4% | +25% | 28.3 | -7% | +50% |
| 257-1024 | 64.0 | +17% | +35% | 64.7 | +10% | +16% |
x86-64-v3 on an AMD EPYC 7B13 (Zen 3), cycles per comparison:
| Sizes | Latency | System | LLVM | Throughput | System | LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids | 24.1 | N/A | +54% | 16.9 | +8% | 2.15x |
| 1-3 | 15.6 | N/A | +94% | 5.7 | 4.29x | 5.04x |
| 4-8 | 15.6 | N/A | 2.12x | 5.7 | 2.56x | 5.87x |
| 9-16 | 15.8 | N/A | +11% | 7.1 | 2.03x | ~ |
| 17-32 | 24.6 | N/A | +0.4% | 8.1 | +74% | -12% |
| 33-64 | 30.5 | -6% | -1% | 10.1 | +9% | -10% |
| 65-256 | 46.3 | +12% | +32% | 33.2 | -8% | +39% |
| 257-1024 | 78.8 | +12% | +26% | 82.3 | -3% | ~ |
x86-64-v2 on an AMD Ryzen 9 9950X (Zen 5), cycles per comparison:
| Sizes | Latency | System | LLVM | Throughput | System | LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids | 23.9 | +2% | +78% | 17.7 | 0.40x | 2.45x |
| 1-3 | 14.8 | +53% | 2.28x | 5.0 | ~ | 6.68x |
| 4-8 | 14.9 | +55% | 2.54x | 5.0 | ~ | 7.82x |
| 9-16 | 14.9 | +53% | +5% | 6.0 | -17% | -17% |
| 17-32 | 22.7 | +0.4% | +10% | 6.0 | -17% | ~ |
| 33-64 | 26.9 | -10% | +37% | 7.5 | -20% | 3.35x |
| 65-256 | 47.7 | -1% | +20% | 38.2 | -31% | +30% |
| 257-1024 | 91.5 | -18% | +24% | 91.4 | -22% | +18% |
x86-64-v2 on an AMD EPYC 7B13 (Zen 3), cycles per comparison:
| Sizes | Latency | System | LLVM | Throughput | System | LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids | 24.1 | N/A | +55% | 16.5 | +10% | 2.24x |
| 1-3 | 15.8 | N/A | +92% | 6.3 | 3.88x | 4.60x |
| 4-8 | 15.8 | N/A | 2.10x | 6.3 | 2.32x | 5.34x |
| 9-16 | 15.8 | N/A | +11% | 7.1 | 2.03x | ~ |
| 17-32 | 24.4 | N/A | +4% | 8.1 | +74% | ~ |
| 33-64 | 30.7 | -7% | +26% | 10.0 | +11% | 2.70x |
| 65-256 | 48.5 | +7% | +31% | 45.8 | -33% | +19% |
| 257-1024 | 108.1 | -21% | +11% | 110.9 | -29% | ~ |
Note: Zen 3 `System` latency is `N/A` for `C++ ids` and 1-32 bytes
because glibc's AVX2 `memcmp` returns a constant `0` behind a predicted
branch for equal 2-31 byte strings, so the latency benchmark's select
doesn't wait on the comparison.
Assisted-by: Antigravity with Gemini, Fable, and other models
170 lines
6.5 KiB
C++
170 lines
6.5 KiB
C++
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
|
|
// Exceptions. See /LICENSE for license information.
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
// Benchmarks comparing equal strings, where the caller branches on each
|
|
// comparison's result.
|
|
//
|
|
// `BM_ThroughputEq` branches on each result, so the comparisons of successive
|
|
// pairs can overlap when the branch is predicted.
|
|
//
|
|
// `BM_LatencyEq` measures how long a comparison takes to get its result to
|
|
// such a branch. A predicted branch doesn't make anything wait for the result,
|
|
// so each result instead selects the next pair of strings to compare, and a
|
|
// comparison can't start until the previous one's result is available. This
|
|
// only measures the whole comparison when that result is computed from the
|
|
// strings, rather than supplied by a predicted branch.
|
|
|
|
#include <benchmark/benchmark.h>
|
|
|
|
#include <algorithm>
|
|
|
|
#include "absl/random/random.h"
|
|
#include "common/check.h"
|
|
#include "common/hashtable_key_context.h"
|
|
#include "llvm/ADT/ArrayRef.h"
|
|
#include "llvm/ADT/STLFunctionalExtras.h"
|
|
#include "llvm/ADT/Sequence.h"
|
|
#include "llvm/ADT/SmallVector.h"
|
|
#include "llvm/ADT/StringRef.h"
|
|
#include "llvm/Support/Allocator.h"
|
|
#include "llvm/Support/StringSaver.h"
|
|
#include "testing/base/benchmark_helpers.h"
|
|
#include "toolchain/benchmarking/source_gen.h"
|
|
|
|
namespace Carbon {
|
|
namespace {
|
|
|
|
// The number of identifiers to take sizes from, enough to cover each
|
|
// distribution of sizes below.
|
|
constexpr ssize_t NumIds = 1024;
|
|
|
|
// The number of pairs compared in each batch, which repeat the identifiers'
|
|
// sizes in a random order. This is long enough that branch predictors can't
|
|
// learn the sequence of sizes, as AMD's Zen 3 does when the same 1024 pairs are
|
|
// compared in the same order each time.
|
|
constexpr ssize_t NumPairs = ssize_t{64} * 1024;
|
|
|
|
struct StringPair {
|
|
llvm::StringRef lhs;
|
|
llvm::StringRef rhs;
|
|
};
|
|
|
|
// Returns `if_equal` when the strings of `pair` are equal, and `if_unequal`
|
|
// otherwise, selecting between them without a branch on the comparison's
|
|
// result.
|
|
//
|
|
// This stands in for a caller's branch on that result. Both only test whether
|
|
// the result is zero, so the select costs the same however the comparison
|
|
// returns it: as a `bool`, as a difference, or as `bcmp`'s `int`. But a branch
|
|
// is predicted, so the code after it doesn't wait for the result, whereas the
|
|
// value selected here does.
|
|
//
|
|
// Adding the result to an index would wait for it too, but needs it as a 0 or
|
|
// 1 value. Producing one takes extra instructions, and fewer of them when the
|
|
// comparison returns a `bool`.
|
|
//
|
|
// The select has to stay a conditional move, and compilers turn one into a
|
|
// branch when a loop waits on it, which is faster for anything but this
|
|
// benchmark. So this is a function of its own, with no loop around the select.
|
|
// If `BM_LatencyEq` ever measures the same as `BM_ThroughputEq`, check that
|
|
// this function still has a conditional move.
|
|
[[gnu::noinline]] auto SelectOnEq(const StringPair& pair, ssize_t if_equal,
|
|
ssize_t if_unequal) -> ssize_t {
|
|
bool eq = HashtableEq(pair.lhs, pair.rhs);
|
|
CARBON_DCHECK(eq);
|
|
return eq ? if_equal : if_unequal;
|
|
}
|
|
|
|
// Compares each pair in turn, with each result selecting the next pair. A
|
|
// separate function keeps the loop easy to find in a disassembly, and keeps
|
|
// `pairs` in registers across `DoNotOptimize`.
|
|
[[gnu::noinline]] auto RunLatencyLoop(benchmark::State& state,
|
|
llvm::ArrayRef<StringPair> pairs)
|
|
-> void {
|
|
while (state.KeepRunningBatch(NumPairs)) {
|
|
for (ssize_t i = 0; i < NumPairs;) {
|
|
Testing::DoNotOptimize(i);
|
|
// Every pair is equal, so this steps to the next pair, but only once the
|
|
// comparison's result is available. Unequal pairs would end the batch.
|
|
i = SelectOnEq(pairs[i], i + 1, NumPairs);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Compares each pair in turn, branching on each result.
|
|
[[gnu::noinline]] auto RunThroughputLoop(benchmark::State& state,
|
|
llvm::ArrayRef<StringPair> pairs)
|
|
-> void {
|
|
while (state.KeepRunningBatch(NumPairs)) {
|
|
for (ssize_t i = 0; i < NumPairs; ++i) {
|
|
// Every pair is equal, so the branch for this check is predicted, and
|
|
// the next comparison doesn't wait for this one's result.
|
|
CARBON_CHECK(HashtableEq(pairs[i].lhs, pairs[i].rhs));
|
|
}
|
|
}
|
|
}
|
|
|
|
using RunLoopT = auto(benchmark::State& state, llvm::ArrayRef<StringPair> pairs)
|
|
-> void;
|
|
|
|
// Runs `run_loop` over pairs of equal strings, with sizes from the distribution
|
|
// that `state`'s arguments select.
|
|
auto RunWithPairs(benchmark::State& state,
|
|
llvm::function_ref<RunLoopT> run_loop) -> void {
|
|
llvm::SmallVector<llvm::StringRef> ids =
|
|
Testing::SourceGen::Global().GetShuffledIdentifiers(
|
|
NumIds, state.range(0), state.range(1), state.range(2) != 0);
|
|
// Compare each identifier with a copy at a different address. Identifiers of
|
|
// the same size share the first one's strings, which keeps the strings in
|
|
// cache.
|
|
llvm::BumpPtrAllocator allocator;
|
|
llvm::StringSaver copies(allocator);
|
|
llvm::SmallVector<StringPair> pairs_by_size(state.range(1) + 1);
|
|
llvm::SmallVector<StringPair> pairs;
|
|
pairs.reserve(NumPairs);
|
|
ssize_t bytes = 0;
|
|
for (ssize_t i : llvm::seq(NumPairs)) {
|
|
llvm::StringRef id = ids[i % NumIds];
|
|
StringPair& size_pair = pairs_by_size[id.size()];
|
|
if (size_pair.lhs.empty()) {
|
|
size_pair = {.lhs = id, .rhs = copies.save(id)};
|
|
}
|
|
pairs.push_back(size_pair);
|
|
bytes += id.size();
|
|
}
|
|
std::shuffle(pairs.begin(), pairs.end(), absl::BitGen());
|
|
run_loop(state, pairs);
|
|
state.SetBytesProcessed(state.iterations() / NumPairs * bytes);
|
|
}
|
|
|
|
auto BM_LatencyEq(benchmark::State& state) -> void {
|
|
RunWithPairs(state, RunLatencyLoop);
|
|
}
|
|
|
|
auto BM_ThroughputEq(benchmark::State& state) -> void {
|
|
RunWithPairs(state, RunThroughputLoop);
|
|
}
|
|
|
|
auto SizeArgs(benchmark::Benchmark* b) -> void {
|
|
b->ArgNames({"min", "max", "uniform"})
|
|
// The distribution of identifier lengths observed in C++ code.
|
|
->Args({1, 64, 0})
|
|
// Uniform distributions over each size class, and over all short sizes.
|
|
->Args({1, 3, 1})
|
|
->Args({4, 8, 1})
|
|
->Args({9, 16, 1})
|
|
->Args({17, 32, 1})
|
|
->Args({33, 64, 1})
|
|
->Args({1, 16, 1})
|
|
// Lengths beyond those of almost all identifiers.
|
|
->Args({65, 256, 1})
|
|
->Args({257, 1024, 1});
|
|
}
|
|
|
|
BENCHMARK(BM_LatencyEq)->Apply(SizeArgs);
|
|
BENCHMARK(BM_ThroughputEq)->Apply(SizeArgs);
|
|
|
|
} // namespace
|
|
} // namespace Carbon
|