[Mlir-commits] [mlir] [mlir][tosa][tosa-to-linalg] Add NaN Mode Lowering (PR #125668)

Jack Frankland llvmlistbot at llvm.org
Wed Feb 19 02:28:52 PST 2025


================
@@ -36,6 +36,47 @@
 using namespace mlir;
 using namespace mlir::tosa;
 
+// Helper function to materialize the semantically correct compare and select
+// operations a binary operation with a specific NaN propagation mode.
+//
+// In the case of "PROPAGATE" semantics no compare and selection is required and
+// this function does nothing.
+//
+// In the case of "IGNORE" semantics this function materializes a comparison of
+// the current operands to the op which will return true for any NaN
+// argument and then selects between the non-NaN operation argument and the
+// calculated result based on whether the lhs or rhs is NaN or not. In pseudo
+// code:
+//
+// binary<op>(lhs, rhs):
+//   result = op(lhs, rhs)
+//   if lhs == NaN return rhs
+//   if rhs == NaN return lhs
+//   return result
+static Value materializeBinaryNanCheckIfRequired(Operation *op,
+                                                 PatternRewriter &rewriter,
+                                                 Value lhs, Value rhs,
+                                                 Value result) {
+  const auto nanMode = getNanMode(op, rewriter);
+  if (!nanMode)
+    return {};
----------------
FranklandJack wrote:

In the case of an absent parameter `getNanMode` will return "PROPAGATE" for operators that support this attribute. In the case of operators that do not support a nan mode attribute this function should not be called hence it returns a `std::nullopt` to indicate an error. This is then checked in the code above and a default initialized `mlir::Value` is constructed and returned. Eventually this will be checked further up the call stack (https://github.com/llvm/llvm-project/pull/125668/files/96ae7bcbebeef4756dddfe4042de7054d9bd5e5b#diff-928740f67ba57a268513ef27f751e3844f0e306c94a74c7db5bd95c327c1d292R1000) and used to raise a rewrite error.

So there are really three cases that `getNanMode()` deals with:
1. The op supports a NaN mode and an attribute is present - return the present attribute value.
2. The op supports a NaN mode and the attribute is not present - return the default mode ("PROPAGATE").
3. The op does not supporta NaN mode - return an error (std::nullopt) to indicate the function should not have been called with this op.

https://github.com/llvm/llvm-project/pull/125668


More information about the Mlir-commits mailing list