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 @@ -517,6 +517,7 @@ %y = math.log10 %x : 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 @@ -107,6 +107,27 @@ }); } +//===----------------------------------------------------------------------===// +// Log10Op folder +//===----------------------------------------------------------------------===// + +OpFoldResult math::Log10Op::fold(ArrayRef operands) { + return constFoldUnaryOpConditional( + operands, [](const APFloat &a) -> Optional { + if (a.isNegative()) + return {}; + + switch (a.getSizeInBits(a.getSemantics())) { + case 64: + return APFloat(log10(a.convertToDouble())); + case 32: + return APFloat(log10f(a.convertToFloat())); + default: + return {}; + } + }); +} + //===----------------------------------------------------------------------===// // PowFOp folder //===----------------------------------------------------------------------===// 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 @@ -174,3 +174,21 @@ %r = math.ctpop %c : i32 return %r : i32 } + +// CHECK-LABEL: @log10_fold +// CHECK: %[[cst:.+]] = arith.constant 2.000000e+00 : f32 + // CHECK: return %[[cst]] +func.func @log10_fold() -> f32 { + %c = arith.constant 100.0 : f32 + %r = math.log10 %c : f32 + return %r : f32 +} + +// CHECK-LABEL: @log10_fold_vec +// CHECK: %[[cst:.+]] = arith.constant dense<[0.000000e+00, 1.000000e+00, 2.000000e+00, 2.301030e+00]> : vector<4xf32> +// CHECK: return %[[cst]] +func.func @log10_fold_vec() -> (vector<4xf32>) { + %v1 = arith.constant dense<[1.0, 10.0, 100.0, 200.0]> : vector<4xf32> + %0 = math.log10 %v1 : vector<4xf32> + return %0 : vector<4xf32> +}