[clang] [clang] Improve getFileIDLocal binary search. (PR #146510)
Haojian Wu via cfe-commits
cfe-commits at lists.llvm.org
Tue Jul 1 12:58:53 PDT 2025
================
@@ -855,35 +857,24 @@ FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
break;
}
- NumProbes = 0;
- while (true) {
- unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
- SourceLocation::UIntTy MidOffset =
- getLocalSLocEntry(MiddleIndex).getOffset();
-
- ++NumProbes;
-
- // If the offset of the midpoint is too large, chop the high side of the
- // range to the midpoint.
- if (MidOffset > SLocOffset) {
- GreaterIndex = MiddleIndex;
- continue;
- }
+ while (LessIndex < GreaterIndex) {
+ ++NumBinaryProbes;
- // If the middle index contains the value, succeed and return.
- if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
- SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
- FileID Res = FileID::get(MiddleIndex);
+ unsigned MiddleIndex = LessIndex + (GreaterIndex - LessIndex) / 2;
- // Remember it. We have good locality across FileID lookups.
- LastFileIDLookup = Res;
- NumBinaryProbes += NumProbes;
- return Res;
- }
+ SourceLocation::UIntTy MidOffset =
+ LocalSLocEntryTable[MiddleIndex].getOffset();
- // Otherwise, move the low-side up to the middle index.
- LessIndex = MiddleIndex;
+ if (MidOffset <= SLocOffset)
----------------
hokein wrote:
Yeah, initializing GreaterIndex to size can be a bit confusing, but that initial value is never actually used.
GreaterIndex always points to an entry whose offset is strictly greater than `SLocOffse`t. The search space is defined as `[LessIndex, GreaterIndex)`, so we know by design that GreaterIndex is never a valid result.
https://github.com/llvm/llvm-project/pull/146510
More information about the cfe-commits
mailing list