[Mlir-commits] [mlir] [mlir][arith] Improve `truncf` folding (PR #80206)

Markus Böck llvmlistbot at llvm.org
Wed Jan 31 14:08:28 PST 2024


================
@@ -1393,23 +1395,20 @@ LogicalResult arith::TruncIOp::verify() {
 // TruncFOp
 //===----------------------------------------------------------------------===//
 
-/// Perform safe const propagation for truncf, i.e. only propagate if FP value
+/// Perform safe const propagation for truncf, i.e., only propagate if FP value
 /// can be represented without precision loss or rounding.
 OpFoldResult arith::TruncFOp::fold(FoldAdaptor adaptor) {
-  auto constOperand = adaptor.getIn();
-  if (!constOperand || !llvm::isa<FloatAttr>(constOperand))
-    return {};
-
-  // Convert to target type via 'double'.
-  double sourceValue =
-      llvm::dyn_cast<FloatAttr>(constOperand).getValue().convertToDouble();
-  auto targetAttr = FloatAttr::get(getType(), sourceValue);
-
-  // Propagate if constant's value does not change after truncation.
-  if (sourceValue == targetAttr.getValue().convertToDouble())
-    return targetAttr;
-
-  return {};
+  auto resElemType = cast<FloatType>(getElementTypeOrSelf(getType()));
+  const llvm::fltSemantics &targetSemantics = resElemType.getFloatSemantics();
+  return constFoldCastOp<FloatAttr, FloatAttr>(
+      adaptor.getOperands(), getType(),
+      [&targetSemantics](APFloat a, bool &castStatus) {
+        bool losesInfo = false;
+        auto status = a.convert(
+            targetSemantics, llvm::RoundingMode::NearestTiesToEven, &losesInfo);
+        castStatus = !losesInfo && status == APFloat::opOK;
+        return a;
----------------
zero9178 wrote:

Do you happen to know by any chance as to why the fold is only performed if there is no loss of information (something inherent to the operation)? The docs for `truncf` state that it uses the default rounding mode although it does not say what this rounding mode is. 
LLVM e.g. always performs this fold https://github.com/llvm/llvm-project/blob/49e3e7514309823e39627175d5337c5d5aff92c1/llvm/lib/IR/ConstantFold.cpp#L257-L263

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


More information about the Mlir-commits mailing list