[llvm] [InstCombine] Optimize unneeded float to int cast when icmp (PR #155501)

Artem Trokhymchuk via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 31 14:33:53 PDT 2025


================
@@ -7611,6 +7613,208 @@ Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
   return nullptr;
 }
 
+enum class SignType {
+  Positive,
+  NonPositive,
+  Negative,
+  NonNegative,
+};
+
+/// Check signess of a constant integer or vector of integers
+///
+/// \param C constant to check for signedness
+/// \param SignType the sign type to check against
+///
+/// \return whether constant is signess corresponds with the requesed requested
+/// sign
+static bool checkConstantSignType(const Constant *C, SignType Sign) {
+  auto Check = [Sign](const ConstantInt *CI) {
+    switch (Sign) {
+    case SignType::Positive:
+      return !CI->isNegative() && !CI->isZero();
+    case SignType::NonPositive:
+      return CI->isNegative() || CI->isZero();
+    case SignType::Negative:
+      return CI->isNegative();
+    case SignType::NonNegative:
+      return !CI->isNegative();
+    default:
+      llvm_unreachable("Unknown sign type");
+    }
+  };
+
+  if (auto *CI = dyn_cast<ConstantInt>(C))
+    return Check(CI);
+
+  // Check every element for vector
+  if (auto *CDV = dyn_cast<ConstantDataVector>(C)) {
+    for (std::size_t i{}; i != CDV->getNumElements(); ++i) {
+      auto *CI = dyn_cast<ConstantInt>(CDV->getElementAsConstant(i));
+      if (!CI || !Check(CI))
+        return false;
+    }
+    return true;
+  }
+
+  return false;
+}
+
+/// Cast ConstantInt to an appropriate APFloat instance
+///
+/// \param CI ConstantInt instance to cast
+/// \param FPType floating point type to cast to
+/// \param Addend addend to add to constant before casting
+///
+/// \return pair {cast status, APFloat result}
+static std::pair<APFloatBase::opStatus, APFloat>
+castCIToAPF(const ConstantInt *CI, const Type *FPType, int Addend) {
+  APFloat FVal{FPType->isFloatTy() ? APFloat::IEEEsingle()
----------------
trokhymchuk wrote:

thank you, used `FPType->getFltSemantics` function and added double and half float tests
I was unable to add vector of half floats as `@llvm.convert.from.fp16` refused to convert

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


More information about the llvm-commits mailing list