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 @@ -541,6 +541,7 @@ %y = math.log1p %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 @@ -128,6 +128,28 @@ }); } +//===----------------------------------------------------------------------===// +// Log1pOp folder +//===----------------------------------------------------------------------===// + +OpFoldResult math::Log1pOp::fold(ArrayRef operands) { + return constFoldUnaryOpConditional( + operands, [](const APFloat &a) -> Optional { + switch (a.getSizeInBits(a.getSemantics())) { + case 64: + if ((a + APFloat(1.0)).isNegative()) + return {}; + return APFloat(log1p(a.convertToDouble())); + case 32: + if ((a + APFloat(1.0f)).isNegative()) + return {}; + return APFloat(log1pf(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 @@ -192,3 +192,21 @@ %0 = math.log10 %v1 : vector<4xf32> return %0 : vector<4xf32> } + +// CHECK-LABEL: @log1p_fold +// CHECK: %[[cst:.+]] = arith.constant 2.8903718 : f32 + // CHECK: return %[[cst]] +func.func @log1p_fold() -> f32 { + %c = arith.constant 17.0 : f32 + %r = math.log1p %c : f32 + return %r : f32 +} + +// CHECK-LABEL: @log1p_fold_vec +// CHECK: %[[cst:.+]] = arith.constant dense<[1.38629436, 1.79175949, 2.07944155, 2.48490667]> : vector<4xf32> +// CHECK: return %[[cst]] +func.func @log1p_fold_vec() -> (vector<4xf32>) { + %v1 = arith.constant dense<[3.0, 5.0, 7.0, 11.0]> : vector<4xf32> + %0 = math.log1p %v1 : vector<4xf32> + return %0 : vector<4xf32> +}