[llvm] [IR] Optimize PHINode::removeIncomingValueIf() using two-pointer (PR #171961)

Mingjie Xu via llvm-commits llvm-commits at lists.llvm.org
Sat Dec 13 17:40:23 PST 2025


https://github.com/Enna1 updated https://github.com/llvm/llvm-project/pull/171961

>From 853327a8e803dcafed195f0328cd81033d1683ae Mon Sep 17 00:00:00 2001
From: "xumingjie.enna1" <xumingjie.enna1 at bytedance.com>
Date: Wed, 10 Dec 2025 14:50:06 +0800
Subject: [PATCH] [IR] Optimize PHINode::removeIncomingValueIf() using
 two-pointer

---
 llvm/lib/IR/Instructions.cpp | 33 ++++++++++++++++-----------------
 1 file changed, 16 insertions(+), 17 deletions(-)

diff --git a/llvm/lib/IR/Instructions.cpp b/llvm/lib/IR/Instructions.cpp
index db0d5af83655f..aa46cbfc59f6b 100644
--- a/llvm/lib/IR/Instructions.cpp
+++ b/llvm/lib/IR/Instructions.cpp
@@ -161,28 +161,27 @@ Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
 
 void PHINode::removeIncomingValueIf(function_ref<bool(unsigned)> Predicate,
                                     bool DeletePHIIfEmpty) {
-  SmallDenseSet<unsigned> RemoveIndices;
-  for (unsigned Idx = 0; Idx < getNumIncomingValues(); ++Idx)
+  unsigned NumOps = getNumIncomingValues();
+  unsigned NewNumOps = 0;
+  for (unsigned Idx = 0; Idx < NumOps; ++Idx) {
     if (Predicate(Idx))
-      RemoveIndices.insert(Idx);
+      continue;
 
-  if (RemoveIndices.empty())
+    if (Idx != NewNumOps) {
+      setIncomingValue(NewNumOps, getIncomingValue(Idx));
+      setIncomingBlock(NewNumOps, getIncomingBlock(Idx));
+    }
+    ++NewNumOps;
+  }
+
+  if (NewNumOps == NumOps)
     return;
 
   // Remove operands.
-  auto NewOpEnd = remove_if(operands(), [&](Use &U) {
-    return RemoveIndices.contains(U.getOperandNo());
-  });
-  for (Use &U : make_range(NewOpEnd, op_end()))
-    U.set(nullptr);
-
-  // Remove incoming blocks.
-  (void)std::remove_if(const_cast<block_iterator>(block_begin()),
-                 const_cast<block_iterator>(block_end()), [&](BasicBlock *&BB) {
-                   return RemoveIndices.contains(&BB - block_begin());
-                 });
-
-  setNumHungOffUseOperands(getNumOperands() - RemoveIndices.size());
+  for (unsigned Idx = NewNumOps; Idx < NumOps; ++Idx)
+    getOperandUse(Idx).set(nullptr);
+
+  setNumHungOffUseOperands(NewNumOps);
 
   // If the PHI node is dead, because it has zero entries, nuke it now.
   if (getNumOperands() == 0 && DeletePHIIfEmpty) {



More information about the llvm-commits mailing list