[llvm] Add StringMap::lookup() overload to take a default value and return a reference to the value to avoid a copy (PR #115469)

Jakub Kuderski via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 11 06:52:56 PST 2024


================
@@ -257,6 +257,15 @@ class LLVM_ALLOCATORHOLDER_EMPTYBASE StringMap
     return ValueTy();
   }
 
+  /// lookup - Return the entry for the specified key, or a default
+  /// provided value if no such entry exists.
+  const ValueTy &lookup(StringRef Key, const ValueTy& Value) const {
----------------
kuhar wrote:

> I assume there would be a lot of use cases for this and it could simplify the code.

Is this more of a guess or have you identified multiple places where it'd help across the project?

> Returning a pointer would work, though it seems to be somewhat less elegant. Do you mean that also the default value would be a pointer?

I was thinking of something like `auto* val = x.lookup_or(Key, ptr)` or `x.lookup(Key, ptrPtr);` (where `ptrPtr` is written to if the value is present, otherwise it keeps pointing to whatever it used to). This is not very elegant but it's very explicit around lifetimes, but I think it should be a better option for very specialized use cases that warrant it.

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


More information about the llvm-commits mailing list