[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:33 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))) {
+ return replaceInstUsesWith(SI, ResCall);
+ }
+ if ((ResCall = foldSelectIntrinsicBinary<Intrinsic::ctlz>(SI, Builder))) {
----------------
dtcxzyw wrote:
You don't need to call foldSelectIntrinsicBinary three times. Just match the pattern as follows:
```
auto *LHSIntrinsic = dyn_cast<IntrinsicInst>(SI->getTrueValue());
if (!LHSIntrinsic) return nullptr;
auto *RHSIntrinsic = dyn_cast<IntrinsicInst>(SI->getFalseValue());
if (!RHSIntrinsic || LHSIntrinsic->getIntrinsicID() != RHSIntrinsic->getIntrinsicID()) return nullptr;
Intrinsic::ID IID = LHSIntrinsic->getIntrinsicID();
switch(IID) {
case Intrinsic::abs:
case Intrinsic::cttz:
case Intrinsic::ctlz: {
// ...
}
case Intrinsic::ctpop: {
// ...
}
default:
return nullptr;
}
```
https://github.com/llvm/llvm-project/pull/178002
More information about the llvm-commits
mailing list