[llvm] [JumpThreading] Refractor redirectValuesFromPredecessorsToPhi: avoid unnecessary map resizing in gatherIncomingValuesToPhi (PR #173596)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 8 08:02:35 PST 2026


================
@@ -925,37 +925,48 @@ using IncomingValueMap = SmallDenseMap<BasicBlock *, Value *, 16>;
 /// \returns the selected value.
 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
                                           IncomingValueMap &IncomingValues) {
+  IncomingValueMap::const_iterator It = IncomingValues.find(BB);
   if (!isa<UndefValue>(OldVal)) {
-    assert((!IncomingValues.count(BB) ||
-            IncomingValues.find(BB)->second == OldVal) &&
+    assert((It != IncomingValues.end() &&
+            (!(It->second) || It->second == OldVal)) &&
            "Expected OldVal to match incoming value from BB!");
 
-    IncomingValues.insert(std::make_pair(BB, OldVal));
+    IncomingValues.insert_or_assign(BB, OldVal);
     return OldVal;
   }
 
-  IncomingValueMap::const_iterator It = IncomingValues.find(BB);
-  if (It != IncomingValues.end()) return It->second;
+  if (It != IncomingValues.end() && It->second)
+    return It->second;
 
   return OldVal;
 }
 
 /// Create a map from block to value for the operands of a
 /// given phi.
 ///
-/// Create a map from block to value for each non-undef value flowing
-/// into \p PN.
+/// This function initializes the map with UndefValue for all predecessors
+/// in BBPreds, and then updates the map with concrete non-undef values
+/// found in the PHI node.
 ///
 /// \param PN The phi we are collecting the map for.
+/// \param BBPreds The list of all predecessor blocks to initialize with Undef.
 /// \param IncomingValues [out] The map from block to value for this phi.
-static void gatherIncomingValuesToPhi(PHINode *PN,
-                                      IncomingValueMap &IncomingValues) {
+static void gatherIncomingValuesToPhi(llvm::PHINode *PN,
+                                      IncomingValueMap &IncomingValues,
+                                      const PredBlockVector &BBPreds) {
+  for (llvm::BasicBlock *Pred : BBPreds) {
+    IncomingValues[Pred] = nullptr;
+  }
+
   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
-    BasicBlock *BB = PN->getIncomingBlock(i);
-    Value *V = PN->getIncomingValue(i);
+    llvm::Value *V = PN->getIncomingValue(i);
+    if (llvm::isa<llvm::UndefValue>(V))
+      continue;
 
-    if (!isa<UndefValue>(V))
-      IncomingValues.insert(std::make_pair(BB, V));
+    llvm::BasicBlock *BB = PN->getIncomingBlock(i);
+    if (IncomingValues.count(BB)) {
+      IncomingValues[BB] = V;
----------------
nikic wrote:

This performs a duplicate map lookup. I think what you want to do is use `auto It = IncomingValues.find(BB); if (It != end()) It->second = V;` or so.

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


More information about the llvm-commits mailing list