Skip to content

Commit f1033a3

Browse files
jacquesguanjacquesguan
authored andcommitted
[mlir][Math] Add constant folder for TanOp.
This patch adds constant folder for TanOp which only supports single and double precision floating-point. Differential Revision: https://reviews.llvm.org/D130873
1 parent 39cfde2 commit f1033a3

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

mlir/include/mlir/Dialect/Math/IR/MathOps.td

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,7 @@ def Math_TanOp : Math_FloatUnaryOp<"tan"> {
656656
%a = math.tan %b : f64
657657
```
658658
}];
659+
let hasFolder = 1;
659660
}
660661

661662
//===----------------------------------------------------------------------===//

mlir/lib/Dialect/Math/IR/MathOps.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,24 @@ OpFoldResult math::ExpM1Op::fold(ArrayRef<Attribute> operands) {
264264
});
265265
}
266266

267+
//===----------------------------------------------------------------------===//
268+
// TanOp folder
269+
//===----------------------------------------------------------------------===//
270+
271+
OpFoldResult math::TanOp::fold(ArrayRef<Attribute> operands) {
272+
return constFoldUnaryOpConditional<FloatAttr>(
273+
operands, [](const APFloat &a) -> Optional<APFloat> {
274+
switch (a.getSizeInBits(a.getSemantics())) {
275+
case 64:
276+
return APFloat(tan(a.convertToDouble()));
277+
case 32:
278+
return APFloat(tanf(a.convertToFloat()));
279+
default:
280+
return {};
281+
}
282+
});
283+
}
284+
267285
/// Materialize an integer or floating point constant.
268286
Operation *math::MathDialect::materializeConstant(OpBuilder &builder,
269287
Attribute value, Type type,

mlir/test/Dialect/Math/canonicalize.mlir

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,23 @@ func.func @expm1_fold_vec() -> (vector<4xf32>) {
282282
%0 = math.expm1 %v1 : vector<4xf32>
283283
return %0 : vector<4xf32>
284284
}
285+
286+
287+
// CHECK-LABEL: @tan_fold
288+
// CHECK-NEXT: %[[cst:.+]] = arith.constant 1.55740774 : f32
289+
// CHECK-NEXT: return %[[cst]]
290+
func.func @tan_fold() -> f32 {
291+
%c = arith.constant 1.0 : f32
292+
%r = math.tan %c : f32
293+
return %r : f32
294+
}
295+
296+
// CHECK-LABEL: @tan_fold_vec
297+
// CHECK-NEXT: %[[cst:.+]] = arith.constant dense<[0.000000e+00, 1.55740774, 0.000000e+00, 1.55740774]> : vector<4xf32>
298+
// CHECK-NEXT: return %[[cst]]
299+
func.func @tan_fold_vec() -> (vector<4xf32>) {
300+
%v1 = arith.constant dense<[0.0, 1.0, 0.0, 1.0]> : vector<4xf32>
301+
%0 = math.tan %v1 : vector<4xf32>
302+
return %0 : vector<4xf32>
303+
}
304+

0 commit comments

Comments
 (0)