[llvm] [InstCombine] Opt phi(freeze(undef), C) -> phi(C, C) (PR #161181)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Mon Sep 29 05:26:19 PDT 2025


================
@@ -5179,8 +5179,51 @@ Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) {
   // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
   //       duplicating logic for binops at least.
   auto getUndefReplacement = [&](Type *Ty) {
-    Value *BestValue = nullptr;
+    auto pickCommonConstantFromPHI = [](PHINode &PN) -> Value * {
+      // phi(freeze(undef), C, C). Choose C for freeze so the PHI can be
+      // removed.
+      Constant *BestValue = nullptr;
+      Constant *C = nullptr;
+      for (Value *V : PN.incoming_values()) {
+        if (match(V, m_Freeze(m_Undef())))
+          continue;
+
+        if (!isa<Constant>(V))
+          return nullptr;
+
+        C = cast<Constant>(V);
+
+        if (BestValue && BestValue != C)
+          return nullptr;
+
+        BestValue = C;
+      }
+      return BestValue;
+    };
+
     Value *NullValue = Constant::getNullValue(Ty);
+
+    bool OnlyPHIUsers =
+        all_of(I.users(), [](const User *U) { return isa<PHINode>(U); });
+    if (OnlyPHIUsers) {
+      Value *BestValue = nullptr;
+      for (auto *U : I.users()) {
+        Value *V = pickCommonConstantFromPHI(*cast<PHINode>(U));
+        if (!V)
+          continue;
+
+        if (!BestValue) {
+          BestValue = V;
+        } else if (BestValue && BestValue == NullValue) {
+          BestValue = NullValue;
+        }
+      }
+
+      if (BestValue)
+        return BestValue;
+    }
----------------
nikic wrote:

Why does this need separate handling? Can't we integrate phis as just another case inside the loop below?

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


More information about the llvm-commits mailing list