[mlir][Math] Add constant folder for TanOp.
authorjacquesguan <Jianjian.Guan@streamcomputing.com>
Mon, 1 Aug 2022 07:52:55 +0000 (15:52 +0800)
committerjacquesguan <Jianjian.Guan@streamcomputing.com>
Tue, 2 Aug 2022 03:20:53 +0000 (11:20 +0800)
This patch adds constant folder for TanOp which only supports single and double precision floating-point.

Differential Revision: https://reviews.llvm.org/D130873

mlir/include/mlir/Dialect/Math/IR/MathOps.td
mlir/lib/Dialect/Math/IR/MathOps.cpp
mlir/test/Dialect/Math/canonicalize.mlir

index 75b8782..70bdf09 100644 (file)
@@ -656,6 +656,7 @@ def Math_TanOp : Math_FloatUnaryOp<"tan"> {
     %a = math.tan %b : f64
     ```
   }];
+  let hasFolder = 1;
 }
 
 //===----------------------------------------------------------------------===//
index 2ba640b..ad3c1b0 100644 (file)
@@ -264,6 +264,24 @@ OpFoldResult math::ExpM1Op::fold(ArrayRef<Attribute> operands) {
       });
 }
 
+//===----------------------------------------------------------------------===//
+// TanOp folder
+//===----------------------------------------------------------------------===//
+
+OpFoldResult math::TanOp::fold(ArrayRef<Attribute> operands) {
+  return constFoldUnaryOpConditional<FloatAttr>(
+      operands, [](const APFloat &a) -> Optional<APFloat> {
+        switch (a.getSizeInBits(a.getSemantics())) {
+        case 64:
+          return APFloat(tan(a.convertToDouble()));
+        case 32:
+          return APFloat(tanf(a.convertToFloat()));
+        default:
+          return {};
+        }
+      });
+}
+
 /// Materialize an integer or floating point constant.
 Operation *math::MathDialect::materializeConstant(OpBuilder &builder,
                                                   Attribute value, Type type,
index dfd1e57..8ed20b7 100644 (file)
@@ -282,3 +282,23 @@ func.func @expm1_fold_vec() -> (vector<4xf32>) {
   %0 = math.expm1 %v1 : vector<4xf32>
   return %0 : vector<4xf32>
 }
+
+
+// CHECK-LABEL: @tan_fold
+// CHECK-NEXT: %[[cst:.+]] = arith.constant 1.55740774 : f32
+// CHECK-NEXT:   return %[[cst]]
+func.func @tan_fold() -> f32 {
+  %c = arith.constant 1.0 : f32
+  %r = math.tan %c : f32
+  return %r : f32
+}
+
+// CHECK-LABEL: @tan_fold_vec
+// CHECK-NEXT: %[[cst:.+]] = arith.constant dense<[0.000000e+00, 1.55740774, 0.000000e+00, 1.55740774]> : vector<4xf32>
+// CHECK-NEXT:   return %[[cst]]
+func.func @tan_fold_vec() -> (vector<4xf32>) {
+  %v1 = arith.constant dense<[0.0, 1.0, 0.0, 1.0]> : vector<4xf32>
+  %0 = math.tan %v1 : vector<4xf32>
+  return %0 : vector<4xf32>
+}
+