[clang] [clang] Improve getFileIDLocal binary search. (PR #146510)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Tue Jul 1 06:33:27 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)
----------------
erichkeane wrote:

Why equal?  Shouldn't "we found this!" mean we exit the loop? And does the '+1' here cause us to miss it if the offset is exactly 'midoffset'?

https://github.com/llvm/llvm-project/pull/146510


More information about the cfe-commits mailing list