diff --git a/mlir/include/mlir/Dialect/Math/IR/MathOps.td b/mlir/include/mlir/Dialect/Math/IR/MathOps.td --- a/mlir/include/mlir/Dialect/Math/IR/MathOps.td +++ b/mlir/include/mlir/Dialect/Math/IR/MathOps.td @@ -768,6 +768,7 @@ %a = math.roundeven %b : f64 ``` }]; + let hasFolder = 1; } //===----------------------------------------------------------------------===// diff --git a/mlir/lib/Dialect/Math/IR/MathOps.cpp b/mlir/lib/Dialect/Math/IR/MathOps.cpp --- a/mlir/lib/Dialect/Math/IR/MathOps.cpp +++ b/mlir/lib/Dialect/Math/IR/MathOps.cpp @@ -397,6 +397,24 @@ }); } +//===----------------------------------------------------------------------===// +// RoundEvenOp folder +//===----------------------------------------------------------------------===// + +OpFoldResult math::RoundEvenOp::fold(ArrayRef operands) { + return constFoldUnaryOpConditional( + operands, [](const APFloat &a) -> Optional { + switch (a.getSizeInBits(a.getSemantics())) { + case 64: + return APFloat(roundeven(a.convertToDouble())); + case 32: + return APFloat(roundevenf(a.convertToFloat())); + default: + return {}; + } + }); +} + /// Materialize an integer or floating point constant. Operation *math::MathDialect::materializeConstant(OpBuilder &builder, Attribute value, Type type, diff --git a/mlir/test/Dialect/Math/canonicalize.mlir b/mlir/test/Dialect/Math/canonicalize.mlir --- a/mlir/test/Dialect/Math/canonicalize.mlir +++ b/mlir/test/Dialect/Math/canonicalize.mlir @@ -358,3 +358,20 @@ return %0 : vector<4xf32> } +// CHECK-LABEL: @roundeven_fold +// CHECK-NEXT: %[[cst:.+]] = arith.constant 2.000000e+00 : f32 +// CHECK-NEXT: return %[[cst]] +func.func @roundeven_fold() -> f32 { + %c = arith.constant 1.5 : f32 + %r = math.roundeven %c : f32 + return %r : f32 +} + +// CHECK-LABEL: @roundeven_fold_vec +// CHECK-NEXT: %[[cst:.+]] = arith.constant dense<[0.000000e+00, -0.000000e+00, 2.000000e+00, -2.000000e+00]> : vector<4xf32> +// CHECK-NEXT: return %[[cst]] +func.func @roundeven_fold_vec() -> (vector<4xf32>) { + %v1 = arith.constant dense<[0.5, -0.5, 1.5, -1.5]> : vector<4xf32> + %0 = math.roundeven %v1 : vector<4xf32> + return %0 : vector<4xf32> +}