# [RFC] Add min/max operations.

I propose to add `MinOp`

, `MaxOp`

operations to Standard or Math dialects. There were plans to move arithmetics from Standard dialect into some new dialects, if that is still the case, then I volunteer to do the split.

## Background

Legalization of higher-level dialects that operate on tensors/memrefs, e.g. HLO, TF, results in a loop nest or some operation like `linalg.generic`

with scalar operations in its region. For most operations there is a corresponding op in Standard or Math dialects. Sum of two tensors `mhlo.add`

can be expressed with `std.addf`

, hyperbolic tangent is mapped to `math.tanh`

.

Unfortunately, `mhlo.maximum`

is rewritten as 2 ops when we deal with integers

```
%0 = cmpi sgt, %lhs, %rhs : i32
%1 = select %0, %lhs, %rhs : i32
```

and 5 ops when we have an op on floats that correctly propagates NANs

```
%NAN = constant 0x7FC00000 : f32
%0 = cmpf ogt, %lhs, %rhs : f32
%1 = select %0, %lhs, %rhs : f32
%2 = cmpf uno, %lhs, %rhs : f32
%3 = select %2, %NAN, %37 : f32
```

There is nothing wrong with this approach if the compiler does not require to perform vectorization or conversion to atomic operations and it just lowers the IR gradually to LLVM. The only downside that I see here is that MLIR users have to reinvent the wheel and write conversion for maximum/minimum which leads to duplicate code.

It becomes unnecessarily more complex when one needs to pattern match `cmp`

and `select`

to convert to `std.atomic_rmw`

or to a corresponding vector operation. Moreover, LLVM has `llvm.maximum`

, `llvm.umax`

and `llvm.smax`

intrinsics and I think it would make sense to add `std.max`

or `math.max`

to MLIR.