Skip to content

Commit 26c95ae

Browse files
jacquesguanjacquesguan
authored andcommitted
[mlir][Math] Add constant folder for sqrt.
Differential Revision: https://reviews.llvm.org/D121980
1 parent 14bd14f commit 26c95ae

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-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
@@ -724,6 +724,7 @@ def Math_SqrtOp : Math_FloatUnaryOp<"sqrt"> {
724724
%x = math.sqrt %y : tensor<4x?xf32>
725725
```
726726
}];
727+
let hasFolder = 1;
727728
}
728729

729730
//===----------------------------------------------------------------------===//

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,31 @@ OpFoldResult math::PowFOp::fold(ArrayRef<Attribute> operands) {
101101
return {};
102102
}
103103

104+
OpFoldResult math::SqrtOp::fold(ArrayRef<Attribute> operands) {
105+
auto constOperand = operands.front();
106+
if (!constOperand)
107+
return {};
108+
109+
auto attr = constOperand.dyn_cast<FloatAttr>();
110+
if (!attr)
111+
return {};
112+
113+
auto ft = getType().cast<FloatType>();
114+
115+
APFloat apf = attr.getValue();
116+
117+
if (apf.isNegative())
118+
return {};
119+
120+
if (ft.getWidth() == 64)
121+
return FloatAttr::get(getType(), sqrt(apf.convertToDouble()));
122+
123+
if (ft.getWidth() == 32)
124+
return FloatAttr::get(getType(), sqrtf(apf.convertToFloat()));
125+
126+
return {};
127+
}
128+
104129
/// Materialize an integer or floating point constant.
105130
Operation *math::MathDialect::materializeConstant(OpBuilder &builder,
106131
Attribute value, Type type,

mlir/test/Dialect/Math/canonicalize.mlir

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,12 @@ func @powf_fold() -> f32 {
8282
%r = math.powf %c, %c : f32
8383
return %r : f32
8484
}
85+
86+
// CHECK-LABEL: @sqrt_fold
87+
// CHECK: %[[cst:.+]] = arith.constant 2.000000e+00 : f32
88+
// CHECK: return %[[cst]]
89+
func @sqrt_fold() -> f32 {
90+
%c = arith.constant 4.0 : f32
91+
%r = math.sqrt %c : f32
92+
return %r : f32
93+
}

0 commit comments

Comments
 (0)