[clang] Optimize Cache Insertion with try_emplace for Reduced Lookups (PR #131402)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Mar 14 15:17:17 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
Author: Ayush Pareek (ayushpareek2003)
<details>
<summary>Changes</summary>
for the functions- insertEntryForFilename() , insertRealPathForFilename()
Replaced `Cache.insert()` with `Cache.try_emplace()` to reduce redundant lookups
Improved efficiency by avoiding unnecessary copying of values when the key already exists
---
Full diff: https://github.com/llvm/llvm-project/pull/131402.diff
1 Files Affected:
- (modified) clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h (+15-14)
``````````diff
diff --git a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index d12814e7c9253..a24ba86dae0ef 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -247,15 +247,16 @@ class DependencyScanningFilesystemLocalCache {
insertEntryForFilename(StringRef Filename,
const CachedFileSystemEntry &Entry) {
assert(llvm::sys::path::is_absolute_gnu(Filename));
- auto [It, Inserted] = Cache.insert({Filename, {&Entry, nullptr}});
- auto &[CachedEntry, CachedRealPath] = It->getValue();
- if (!Inserted) {
- // The file is already present in the local cache. If we got here, it only
- // contains the real path. Let's make sure the entry is populated too.
- assert((!CachedEntry && CachedRealPath) && "entry already present");
- CachedEntry = &Entry;
- }
- return *CachedEntry;
+
+ auto &[CachedEntry, CachedRealPath] = Cache.try_emplace(
+ Filename, &Entry, nullptr).first->getValue();
+
+ if (!CachedEntry) {
+ assert((!CachedEntry && CachedRealPath) && "entry already present");
+ CachedEntry = &Entry;
+ }
+
+ return *CachedEntry;
}
/// Returns real path associated with the filename or nullptr if none is
@@ -272,14 +273,14 @@ class DependencyScanningFilesystemLocalCache {
insertRealPathForFilename(StringRef Filename,
const CachedRealPath &RealPath) {
assert(llvm::sys::path::is_absolute_gnu(Filename));
- auto [It, Inserted] = Cache.insert({Filename, {nullptr, &RealPath}});
- auto &[CachedEntry, CachedRealPath] = It->getValue();
- if (!Inserted) {
- // The file is already present in the local cache. If we got here, it only
- // contains the entry. Let's make sure the real path is populated too.
+ auto &[CachedEntry, CachedRealPath] = Cache.try_emplace(
+ Filename, nullptr, &RealPath).first->getValue();
+
+ if (!CachedRealPath) {
assert((!CachedRealPath && CachedEntry) && "real path already present");
CachedRealPath = &RealPath;
}
+
return *CachedRealPath;
}
};
``````````
</details>
https://github.com/llvm/llvm-project/pull/131402
More information about the cfe-commits
mailing list