[llvm] [ConstantFold] Fix result type when folding powi.f16 (PR #98681)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 12 12:07:32 PDT 2024


https://github.com/dtcxzyw created https://github.com/llvm/llvm-project/pull/98681

Fixes #98665.


>From a0097cbfd275d08831ee02b354fce7011d57eb19 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Sat, 13 Jul 2024 03:05:37 +0800
Subject: [PATCH] [ConstantFold] Fix result type when folding powi.f16

---
 llvm/lib/Analysis/ConstantFolding.cpp                | 12 +++++++-----
 .../Transforms/InstSimplify/ConstProp/pr98665.ll     | 11 +++++++++++
 2 files changed, 18 insertions(+), 5 deletions(-)
 create mode 100644 llvm/test/Transforms/InstSimplify/ConstProp/pr98665.ll

diff --git a/llvm/lib/Analysis/ConstantFolding.cpp b/llvm/lib/Analysis/ConstantFolding.cpp
index 962880f68f076..b86f91edeb5b9 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -2760,11 +2760,13 @@ static Constant *ConstantFoldIntrinsicCall2(Intrinsic::ID IntrinsicID, Type *Ty,
 
       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
         return nullptr;
-      if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
-        return ConstantFP::get(
-            Ty->getContext(),
-            APFloat((float)std::pow((float)Op1V.convertToDouble(),
-                                    (int)Op2C->getZExtValue())));
+      if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy()) {
+        APFloat Res((float)std::pow((float)Op1V.convertToDouble(),
+                                    (int)Op2C->getZExtValue()));
+        bool unused;
+        Res.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
+        return ConstantFP::get(Ty->getContext(), Res);
+      }
       if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
         return ConstantFP::get(
             Ty->getContext(),
diff --git a/llvm/test/Transforms/InstSimplify/ConstProp/pr98665.ll b/llvm/test/Transforms/InstSimplify/ConstProp/pr98665.ll
new file mode 100644
index 0000000000000..8b7d361840936
--- /dev/null
+++ b/llvm/test/Transforms/InstSimplify/ConstProp/pr98665.ll
@@ -0,0 +1,11 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 5
+; RUN: opt < %s -passes=instsimplify -S | FileCheck %s
+; Make sure that the type is correct after constant folding
+
+define half @pr98665() {
+; CHECK-LABEL: define half @pr98665() {
+; CHECK-NEXT:    ret half 0xH3C00
+;
+  %x = call half @llvm.powi.f16.i32(half 0xH3C00, i32 1)
+  ret half %x
+}



More information about the llvm-commits mailing list