diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp
index 8fa648c730b996676c71b1fe6a97d5e7af0176c0..1b8383bc426128546ba83bf986e3c8415f9bfde1 100644
--- a/lib/Basic/SourceManager.cpp
+++ b/lib/Basic/SourceManager.cpp
@@ -863,6 +863,11 @@ FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
       return Res;
     }
 
+    // Sanity checking, otherwise a bug may lead to hanging in release build.
+    if (LessIndex == MiddleIndex) {
+      assert(0 && "binary search missed the entry");
+      return FileID();
+    }
     LessIndex = MiddleIndex;
   }
 }