[llvm] [InstCombine] fold `ldexp(x, zext(i1 y))` to `fmul x, (select y, 2.0, 1.0)` (PR #94887)

via llvm-commits llvm-commits at lists.llvm.org
Sat Jun 8 20:27:39 PDT 2024


https://github.com/c8ef created https://github.com/llvm/llvm-project/pull/94887

close: #92538

>From 00af1fbb6311694303ff6e161d122cdf1dc8f646 Mon Sep 17 00:00:00 2001
From: c8ef <c8ef at outlook.com>
Date: Sun, 9 Jun 2024 11:24:47 +0800
Subject: [PATCH] ldexp(x, zext(i1 y))

---
 .../InstCombine/InstCombineCalls.cpp          | 13 ++++++++++
 .../test/Transforms/InstCombine/ldexp-zext.ll | 24 +++++++++++++++++++
 2 files changed, 37 insertions(+)
 create mode 100644 llvm/test/Transforms/InstCombine/ldexp-zext.ll

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 0632f3cfc6dd2..15c11799b949e 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -2618,6 +2618,19 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
       }
     }
 
+    // ldexp(x, zext(i1 y)) -> fmul x, (select y, 2.0, 1.0)
+    Value *ExtSrc;
+    if (match(Exp, m_ZExt(m_Value(ExtSrc))) &&
+        ExtSrc->getType()->getScalarSizeInBits() == 1) {
+      Value *Cmp = Builder.CreateICmp(
+          ICmpInst::ICMP_NE, ExtSrc, Constant::getNullValue(ExtSrc->getType()));
+      SelectInst *Select = SelectInst::Create(
+          Cmp, ConstantFP::get(Type::getFloatTy(II->getContext()), 2.0),
+          ConstantFP::get(Type::getFloatTy(II->getContext()), 1.0));
+      Builder.Insert(Select);
+      return BinaryOperator::CreateFMul(Src, Select);
+    }
+
     break;
   }
   case Intrinsic::ptrauth_auth:
diff --git a/llvm/test/Transforms/InstCombine/ldexp-zext.ll b/llvm/test/Transforms/InstCombine/ldexp-zext.ll
new file mode 100644
index 0000000000000..998a8d321342c
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/ldexp-zext.ll
@@ -0,0 +1,24 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+define float @ldexp_zext(float %x, i1 %bool) {
+; CHECK-LABEL: @ldexp_zext(
+; CHECK-NEXT:    [[TMP1:%.*]] = select i1 [[BOOL:%.*]], float 2.000000e+00, float 1.000000e+00
+; CHECK-NEXT:    [[LDEXP:%.*]] = fmul float [[TMP1]], [[X:%.*]]
+; CHECK-NEXT:    ret float [[LDEXP]]
+;
+  %zext = zext i1 %bool to i32
+  %ldexp = call float @llvm.ldexp.f32.i32(float %x, i32 %zext)
+  ret float %ldexp
+}
+
+define float @ldexp_zext_negative(float %x, i8 %y) {
+; CHECK-LABEL: @ldexp_zext_negative(
+; CHECK-NEXT:    [[ZEXT:%.*]] = zext i8 [[Y:%.*]] to i32
+; CHECK-NEXT:    [[LDEXP:%.*]] = call float @llvm.ldexp.f32.i32(float [[X:%.*]], i32 [[ZEXT]])
+; CHECK-NEXT:    ret float [[LDEXP]]
+;
+  %zext = zext i8 %y to i32
+  %ldexp = call float @llvm.ldexp.f32.i32(float %x, i32 %zext)
+  ret float %ldexp
+}



More information about the llvm-commits mailing list