[llvm] [InstCombine] Fold select of intrinsic into intrinsic of select (PR #178002)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Tue Jan 27 09:11:32 PST 2026


================
@@ -492,6 +492,64 @@ Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
   return nullptr;
 }
 
+template <Intrinsic::ID ID>
+static Instruction *foldSelectIntrinsicUnary(SelectInst &SI,
+                                             InstCombiner::BuilderTy &Builder) {
+  Value *TrueV = SI.getTrueValue();
+  Value *FalseV = SI.getFalseValue();
+  Value *TV = nullptr, *FV = nullptr;
+
+  if (match(TrueV, m_Intrinsic<ID>(m_Value(TV))) &&
+      match(FalseV, m_Intrinsic<ID>(m_Value(FV)))) {
+    Value *NewSel = Builder.CreateSelect(SI.getCondition(), TV, FV, "", &SI);
+    Instruction *NewCall =
+        Builder.CreateIntrinsic(ID, {NewSel->getType()}, {NewSel});
+    return NewCall;
+  }
+  return nullptr;
+}
+
+template <Intrinsic::ID ID>
+static Instruction *
+foldSelectIntrinsicBinary(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
+  Value *TrueV = SI.getTrueValue();
+  Value *FalseV = SI.getFalseValue();
+  Value *TV = nullptr, *FV = nullptr;
+  ConstantInt *TZ = nullptr, *FZ = nullptr;
+
+  if (match(TrueV, m_Intrinsic<ID>(m_Value(TV), m_ConstantInt(TZ))) &&
+      match(FalseV, m_Intrinsic<ID>(m_Value(FV), m_ConstantInt(FZ))) &&
+      TZ == FZ) {
+    Value *NewSel = Builder.CreateSelect(SI.getCondition(), TV, FV, "", &SI);
+    Instruction *NewCall =
+        Builder.CreateIntrinsic(ID, {NewSel->getType()}, {NewSel, TZ});
+    return NewCall;
+  }
+  return nullptr;
+}
+
+/// This transforms patterns of the form:
+///   select cond, intrinsic(x, ...), intrinsic(y, ...)
+/// into:
+///   intrinsic(select cond, x, y, ...)
+Instruction *InstCombinerImpl::foldSelectIntrinsic(SelectInst &SI) {
+  Instruction *ResCall = nullptr;
+
+  if ((ResCall = foldSelectIntrinsicUnary<Intrinsic::ctpop>(SI, Builder))) {
----------------
dtcxzyw wrote:

```suggestion
  if (Instruction *ResCall = foldSelectIntrinsicUnary<Intrinsic::ctpop>(SI, Builder)) {
```


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


More information about the llvm-commits mailing list