[llvm] [InstCombine] Ensure Safe Handling of Flags in foldFNegIntoConstant (PR #94148)

via llvm-commits llvm-commits at lists.llvm.org
Sun Jun 30 22:17:07 PDT 2024


================
@@ -2653,8 +2653,15 @@ static Instruction *foldFNegIntoConstant(Instruction &I, const DataLayout &DL) {
   // Fold negation into constant operand.
   // -(X * C) --> X * (-C)
   if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
-    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
+    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
+      if (match(C, m_AnyZeroFP()) && I.getFastMathFlags().noInfs()) {
+        return BinaryOperator::CreateFMulFMF(
+            X, NegC,
+            I.getFastMathFlags() &
+                cast<FPMathOperator>(I.getOperand(0))->getFastMathFlags());
----------------
SahilPatidar wrote:


alive2: https://alive2.llvm.org/ce/z/DHmA7a
I apologize for the delay; I was quite busy. Based on my observation, I came up with this combination: if we have `nnan` in any instruction, we can propagate flags to our transformation.

```cpp
FastMathFlags NF1 = F1 & F2;
FastMathFlags NF2 = F1 | F2;

if (NF2.noNaNs()) {
    return F2;
}

if (NF1.any() || (F1.none() && F2.none())) {
    return NF1;
}

if (F1.all() || F2.all()) {
    return F2;
}

return NF1;
```

Let me know what you think.

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


More information about the llvm-commits mailing list