[LinalgExt] Add is_stable to sort and replace the bubble sort lowering (#25262)
## Context
`iree_linalg_ext.sort` lowers to a bubble sort:
`SortOp::generateScalarImplementation` emits one sweep of n-1
compare-swaps for each of the n iterations of the loop over the sort
dimension, with no early exit. Sorting n elements takes O(n^2) steps,
which shows up as soon as the sorted dimension has a few thousand
elements. We hit this with the argsort of 4420 candidates in the non-max
suppression of a detection model, where the sort dispatch alone took
about 18 ms on x86-64, many times the rest of the model.
A faster in-place algorithm is not stable, and stability turned out to
matter: the bubble sort keeps equal elements in input order when the
comparator is non-strict (`oge`, `sle`, ...), because it then never
swaps them. The Torch frontend emits exactly such comparators, and e.g.
`onnx.NonMaxSuppression` expects the lowest index first among boxes with
the same score (`test_nonmaxsuppression_identical_boxes` failed with a
plain heapsort). With a strict comparator (`ogt`, `slt`, ...) the bubble
sort is not stable: keys `1, 1, 2, 2, 0` sorted descending together with
their indices return the indices `3 2 1 0 4`.
So this PR makes stability explicit and picks the algorithm from it.
## This PR
### `is_stable`
The op gets an `is_stable` attribute, false by default and only printed
when set:
```mlir
%0:2 = iree_linalg_ext.sort dimension(0) is_stable(true)
ins(%keys, %payload : tensor<?xf32>, tensor<?xi32>)
outs(%init0, %init1 : tensor<?xf32>, tensor<?xi32>) {
^bb0(%lhs: f32, %rhs: f32, %lhs_payload: i32, %rhs_payload: i32):
%before = arith.cmpf ogt, %lhs, %rhs : f32
iree_linalg_ext.yield %before : i1
} -> tensor<?xf32>, tensor<?xi32>
```
The op description now defines the terms. The comparator *does not
order* two elements if it returns the same value for both argument
orders (both `false` with a strict comparison, both `true` with a
non-strict one). Without `is_stable` such elements end up in unspecified
order. With `is_stable` they keep their input order: an element only
moves in front of another one if the comparator returns `true` for that
order and `false` for the opposite one. This definition is the same for
strict and non-strict comparators.
### Lowering variants
All variants are in place: they need no storage besides the operands, so
nothing changes for bufferization or stack usage, and they work for
dynamic sizes and on every backend. The loop nest built from the
iteration domain is unchanged; a slice is sorted in the first iteration
of the loop over the sort dimension, where the inputs were already
copied to the outputs. Operands that are sorted in place are no longer
copied onto themselves.
**1. Not stable: heapsort.** O(n log n) comparisons.
```
for (root = n/2 - 1; root >= 0; --root) // build the heap
siftDown(root, slice[root], n)
for (end = n - 1; end > 0; --end) { // move its first element
last = slice[end]; slice[end] = slice[0] // behind the shrinking heap
siftDown(0, last, end)
}
```
`siftDown` is a `scf.while` that moves an element down until neither
child has to be placed after it.
**2. Stable: binary insertion sort.** O(n log n) comparisons, but O(n^2)
element moves. It is the fallback that always works: a stable sort with
O(n log n) moves needs scratch storage of the operand size (merge sort),
which a dispatch can only take from the stack and which is unbounded for
dynamic sizes.
```
for (i = 1; i < n; ++i) {
element = slice[i]
lo = <first position in the sorted prefix [0, i) whose element has to stay
behind `element`, by binary search>
for (j = i; j > lo; --j) slice[j] = slice[j - 1]
slice[lo] = element
}
```
The search uses "strictly before" (comparator true for this order and
false for the opposite one), so that elements the comparator does not
order are never reordered.
**3. Stable with a position operand: heapsort with a tie-break
(canonicalization).** If an operand of a stable sort holds the positions
along the sort dimension (a `linalg.generic` yielding `linalg.index`,
which is what `aten.sort` passes as indices), it tells the input order
of any two elements. `FoldSortStabilityIntoComparator` extends the
comparator to order the elements it does not order itself by position,
and clears `is_stable`:
```mlir
^bb0(%lhs: f32, %rhs: f32, %lhs_pos: i64, %rhs_pos: i64):
%before = arith.cmpf oge, %lhs, %rhs : f32
%after = arith.cmpf oge, %rhs, %lhs : f32
%ordered = arith.xori %before, %after : i1
%lower_pos = arith.cmpi slt, %lhs_pos, %rhs_pos : i64
%result = arith.select %ordered, %before, %lower_pos : i1
iree_linalg_ext.yield %result : i1
```
The comparator is then a strict total order: no two elements are left
without a defined order, so every sorting algorithm returns the result
of the stable sort and the op can use variant 1. The cost is a second
evaluation of the comparator per comparison.
The rewrite only applies if the sorted positions are used. If they are
not, `RemoveUnusedSortOpResults` drops the operand as before, instead of
keeping its buffer in the dispatch just for the comparator; the sort
then stays stable (variant 2, or variant 4).
**4. Stable but unobservable: heapsort (canonicalization).**
`DropUnobservableSortStability` clears `is_stable` for a single integer
operand whose comparator is an integer comparison of its two arguments.
Elements that such a comparator does not order are the same value, so
their order cannot be observed. Floats are left alone (`0.0` and `-0.0`
compare equal but differ).
### Frontends
* **Torch:** the conversion of `tm_tensor.sort` always sets `is_stable`,
since those sorts have relied on the stable behaviour. With the index
operand of `aten.sort` they get variant 3; a sort that only uses the
values gets variant 2 (floats) or 4 (integers).
* **StableHLO:** `is_stable` of `stablehlo.sort` is passed on. It was
dropped before, and since StableHLO comparators are usually strict,
stable StableHLO sorts were in fact not stable.
### Things to know
* **Unstable sorts order ties differently than before.** That is only
allowed for sorts without `is_stable`, i.e. StableHLO sorts with
`is_stable = false` and ops built directly.
* **NaN.** An ordered float comparison does not order NaN with any
value, which makes the comparator inconsistent (it orders `1.0` and
`2.0`, but neither with NaN). The op description now requires a
consistent comparator. In a simulation of the old lowering on a few
inputs, NaNs stayed at their input positions and the other values were
sorted around them. With the new lowerings the other values can come out
unsorted as well, e.g. `3, NaN, 1, 2, NaN, 5, 4, 0` sorted with `ogt`
gives `NaN, 1, 0, NaN, 5, 4, 2, 3`. A frontend that has to support NaN
keys needs a comparator that orders them (e.g. NaN last, as `torch.sort`
does); the Torch comparators do not do that today.
* `topk_v2` keeps its bubble sort over the k outputs; it is not touched
here.
## Performance
Apple M4, llvm-cpu, `local-task`, median of 5 repetitions. Each program
generates pseudo-random keys and sorts them with a single
`iree_linalg_ext.sort`; the times include generating the keys (about
0.01 ms for 4420 elements). The `main` column is the same program
without `is_stable`, which `main` does not have.
| program | variant | main | this PR | speedup |
|---|---|---|---|---|
| 1024 f32, descending | 1 heapsort | 1.08 ms | 0.032 ms | 34x |
| 4420 f32, descending | 1 heapsort | 20.7 ms | 0.125 ms | 166x |
| 4420 f32, already sorted | 1 heapsort | 20.3 ms | 0.113 ms | 180x |
| 4420 f32, reversed | 1 heapsort | 20.3 ms | 0.107 ms | 190x |
| 4420 i32, ascending | 1 heapsort | 10.3 ms | 0.113 ms | 91x |
| 4420 f32 keys + i32 index iota (argsort) | 1 heapsort | 20.1 ms |
0.127 ms | 158x |
| 16384 f32, descending | 1 heapsort | 280 ms | 0.515 ms | 544x |
| 512x128 f32, along the inner dimension | 1 heapsort | 1.82 ms | 0.310
ms | 5.9x |
| 128x512 f32, along the outer dimension | 1 heapsort | 9.53 ms | 0.394
ms | 24x |
| stable, 4420 f32 keys + i32 index iota (argsort) | 3 heapsort +
tie-break | 20.1 ms | 0.236 ms | 85x |
| stable, 4420 i32, ascending | 4 heapsort | 10.3 ms | 0.115 ms | 90x |
| stable, 1024 f32, descending | 2 insertion sort | 1.08 ms | 0.131 ms |
8.2x |
| stable, 4420 f32, descending | 2 insertion sort | 20.7 ms | 1.48 ms |
14x |
| stable, 4420 f32, already sorted | 2 insertion sort | 20.3 ms | 0.067
ms | 303x |
| stable, 4420 f32, reversed | 2 insertion sort | 20.3 ms | 2.69 ms |
7.6x |
| stable, 4420 f32 keys + i32 payload | 2 insertion sort | 20.1 ms |
1.79 ms | 11x |
| stable, 16384 f32, descending | 2 insertion sort | 280 ms | 17.9 ms |
16x |
The tie-break of variant 3 costs a bit less than 2x over the plain
heapsort. The element-move loop of the insertion sort is not vectorized
by LLVM at the moment (about one element per cycle); if stable sorts
without a position operand turn out to matter, that loop is where to
look.
## Tests
* `LinalgExt/IR/test/roundtrip.mlir`: the attribute.
* `LinalgExt/IR/test/canonicalize.mlir`: variant 3 applies with used
positions along the sort dimension, and not for positions along another
dimension, unused positions, or a sort that is not stable; variant 4
applies to a plain integer comparison, and not to floats or a comparator
that does more than compare its arguments.
* `LinalgExt/Transforms/test/convert_to_loops.mlir`: the heapsort and
the insertion sort structure; `sort_multi` has one operand that is not
sorted in place, to cover the copy.
* Torch and StableHLO conversion tests: `is_stable` is set / passed on.
* `tests/e2e/linalg_ext_ops/sort.mlir`: eight more tests: odd length
with duplicate and negative keys, a single element, the inner dimension,
keys with indices, a tie-break comparator on many equal keys, and stable
sorts of many equal keys with a strict comparator, a non-strict one, and
a position operand.
* Run locally: the e2e file passes on llvm-cpu, VMVX and Metal, and
compiles for Vulkan SPIR-V. `test_nonmaxsuppression_identical_boxes`
from iree-test-suites passes at O0 and O2. I could not run CUDA/ROCm or
the full Torch and ONNX suites locally.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Florian Walbroel <walbroel@roofline.ai>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/compiler/plugins/input/StableHLO/Conversion/StableHLOToLinalgExt.cpp b/compiler/plugins/input/StableHLO/Conversion/StableHLOToLinalgExt.cpp
index ffd6fa9..6615893 100644
--- a/compiler/plugins/input/StableHLO/Conversion/StableHLOToLinalgExt.cpp
+++ b/compiler/plugins/input/StableHLO/Conversion/StableHLOToLinalgExt.cpp
@@ -194,7 +194,7 @@
}
auto sortOp = IREE::LinalgExt::SortOp::create(
rewriter, loc, resultTypes, adaptor.getOperands(), outputs,
- op.getDimensionAttr());
+ op.getDimension(), op.getIsStable());
rewriter.inlineRegionBefore(op.getComparator(), sortOp.getRegion(),
sortOp.getRegion().begin());
Region ®ion = sortOp.getRegion();
diff --git a/compiler/plugins/input/StableHLO/Conversion/test/stablehlo_to_linalg_ext.mlir b/compiler/plugins/input/StableHLO/Conversion/test/stablehlo_to_linalg_ext.mlir
index 447615c..2546022 100644
--- a/compiler/plugins/input/StableHLO/Conversion/test/stablehlo_to_linalg_ext.mlir
+++ b/compiler/plugins/input/StableHLO/Conversion/test/stablehlo_to_linalg_ext.mlir
@@ -16,6 +16,7 @@
// CHECK: %[[OUT:.+]] = tensor.empty() : tensor<128xi32>
// CHECK: %[[SORT:.+]] = iree_linalg_ext.sort
// CHECK-SAME: dimension(0)
+// CHECK-NOT: is_stable
// CHECK-SAME: ins(%[[ARG0]] : tensor<128xi32>)
// CHECK-SAME: outs(%[[OUT]] : tensor<128xi32>)
// CHECK: ^bb0(%[[ARG1:.+]]: i32, %[[ARG2:.+]]: i32)
@@ -25,6 +26,20 @@
// -----
+// CHECK-LABEL: func.func @sort_1d_stable(
+func.func @sort_1d_stable(%arg0: tensor<128xi32>) -> (tensor<128xi32>) {
+ %0 = "stablehlo.sort"(%arg0) ( {
+ ^bb0(%arg2: tensor<i32>, %arg3: tensor<i32>):
+ %1 = "stablehlo.compare"(%arg2, %arg3) {comparison_direction = #stablehlo<comparison_direction GT>} : (tensor<i32>, tensor<i32>) -> tensor<i1>
+ "stablehlo.return"(%1) : (tensor<i1>) -> ()
+ }) {dimension = 0 : i64, is_stable = true} : (tensor<128xi32>) -> (tensor<128xi32>)
+ return %0 : tensor<128xi32>
+}
+// CHECK: iree_linalg_ext.sort
+// CHECK-SAME: dimension(0) is_stable(true)
+
+// -----
+
// CHECK-LABEL: func.func @sort_1d_ui(
// CHECK-SAME: %[[ARG0:[a-zA-Z0-9]+]]
// CHECK-SAME: )
diff --git a/compiler/plugins/input/Torch/InputConversion/ConvertTMTensorToLinalgExt.cpp b/compiler/plugins/input/Torch/InputConversion/ConvertTMTensorToLinalgExt.cpp
index a85d92c..fcda946 100644
--- a/compiler/plugins/input/Torch/InputConversion/ConvertTMTensorToLinalgExt.cpp
+++ b/compiler/plugins/input/Torch/InputConversion/ConvertTMTensorToLinalgExt.cpp
@@ -117,9 +117,11 @@
rewriter, loc, tensor::getMixedSizes(rewriter, loc, input),
resultType.getElementType()));
}
+ // Sorts coming from Torch rely on elements that compare equal keeping
+ // their input order, e.g. the lowest index comes first among equal values.
auto sortOp = IREE::LinalgExt::SortOp::create(
rewriter, loc, op.getResultTypes(), op.getOutputs(), outputs,
- op.getDimensionAttr());
+ op.getDimension(), /*is_stable=*/true);
rewriter.inlineRegionBefore(op.getRegion(), sortOp.getRegion(),
sortOp.getRegion().begin());
rewriter.replaceOp(op, sortOp->getResults());
diff --git a/compiler/plugins/input/Torch/InputConversion/test/sort.mlir b/compiler/plugins/input/Torch/InputConversion/test/sort.mlir
index c63e157..0b5eaf7 100644
--- a/compiler/plugins/input/Torch/InputConversion/test/sort.mlir
+++ b/compiler/plugins/input/Torch/InputConversion/test/sort.mlir
@@ -14,7 +14,7 @@
// CHECK: %[[EMPTY_INPUT:.+]] = tensor.empty() : tensor<3x4xf32>
// CHECK: %[[EMPTY_INDICES:.+]] = tensor.empty() : tensor<3x4xi64>
// CHECK: %[[SORT:.+]]:2 = iree_linalg_ext.sort
-// CHECK-SAME: dimension(1)
+// CHECK-SAME: dimension(1) is_stable(true)
// CHECK-SAME: ins(%[[INPUT]], %[[INDICES]] : tensor<3x4xf32>, tensor<3x4xi64>)
// CHECK-SAME: outs(%[[EMPTY_INPUT]], %[[EMPTY_INDICES]] : tensor<3x4xf32>, tensor<3x4xi64>) {
// CHECK: ^bb0(%[[INP1:.+]]: f32, %[[INP2:.+]]: f32, %{{.*}}: i64, %{{.*}}: i64):
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp
index 46cc9aa..ca84c5b 100644
--- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp
+++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp
@@ -1265,7 +1265,8 @@
// args.
auto newSortOp = IREE::LinalgExt::SortOp::create(
rewriter, loc, usedResultTypes,
- /*inputs=*/usedInputs, usedOutputs, sortOp.getDimension());
+ /*inputs=*/usedInputs, usedOutputs, sortOp.getDimension(),
+ sortOp.getIsStable());
newSortOp.getRegion().takeBody(sortOp.getRegion());
newSortOp.getRegion().front().eraseArguments(eraseArg);
rewriter.replaceAllUsesWith(usedResults, newSortOp.getResults());
@@ -1273,11 +1274,158 @@
return success();
}
};
+
+/// Returns true if `value` holds, at every position, the index of that
+/// position along `dimension`: a `linalg.generic` without inputs that yields
+/// `linalg.index dimension`, optionally cast to an integer type.
+static bool isIndexAlongDimension(Value value, int64_t dimension) {
+ auto genericOp = value.getDefiningOp<linalg::GenericOp>();
+ if (!genericOp || genericOp.getNumDpsInputs() != 0 ||
+ genericOp.getNumDpsInits() != 1 ||
+ !genericOp.getMatchingIndexingMap(genericOp.getDpsInitOperand(0))
+ .isIdentity()) {
+ return false;
+ }
+ Block *body = genericOp.getBlock();
+ Value yielded = body->getTerminator()->getOperand(0);
+ if (auto castOp = yielded.getDefiningOp<arith::IndexCastOp>()) {
+ yielded = castOp.getIn();
+ }
+ auto indexOp = yielded.getDefiningOp<linalg::IndexOp>();
+ return indexOp && indexOp->getBlock() == body &&
+ static_cast<int64_t>(indexOp.getDim()) == dimension;
+}
+
+/// Turns a stable sort into an unstable one if one of its operands holds the
+/// positions along the sort dimension. That operand tells the input order of
+/// two elements, so the comparator can order the elements that it does not
+/// order itself by position. It then is a strict total order: no two elements
+/// are left for which the order is unspecified, and every sorting algorithm
+/// returns the result of the stable sort. The unstable sort lowers to a
+/// faster algorithm.
+///
+/// For example:
+///
+/// %0:2 = iree_linalg_ext.sort dimension(0) is_stable(true)
+/// ins(%keys, %positions : tensor<?xf32>, tensor<?xi64>)
+/// outs(%empty0, %empty1 : tensor<?xf32>, tensor<?xi64>) {
+/// ^bb0(%lhs: f32, %rhs: f32, %lhs_pos: i64, %rhs_pos: i64):
+/// %before = arith.cmpf oge, %lhs, %rhs : f32
+/// iree_linalg_ext.yield %before : i1
+/// } -> tensor<?xf32>, tensor<?xi64>
+///
+/// ->
+///
+/// %0:2 = iree_linalg_ext.sort dimension(0)
+/// ins(%keys, %positions : tensor<?xf32>, tensor<?xi64>)
+/// outs(%empty0, %empty1 : tensor<?xf32>, tensor<?xi64>) {
+/// ^bb0(%lhs: f32, %rhs: f32, %lhs_pos: i64, %rhs_pos: i64):
+/// %before = arith.cmpf oge, %lhs, %rhs : f32
+/// %after = arith.cmpf oge, %rhs, %lhs : f32
+/// %ordered = arith.xori %before, %after : i1
+/// %lower_pos = arith.cmpi slt, %lhs_pos, %rhs_pos : i64
+/// %result = arith.select %ordered, %before, %lower_pos : i1
+/// iree_linalg_ext.yield %result : i1
+/// } -> tensor<?xf32>, tensor<?xi64>
+///
+/// The rewrite is limited to position operands whose result is used. An
+/// unused one is removed by `RemoveUnusedSortOpResults` instead, which avoids
+/// keeping its buffer only for the sake of the comparator.
+struct FoldSortStabilityIntoComparator
+ : OpRewritePattern<IREE::LinalgExt::SortOp> {
+ using Base::Base;
+ LogicalResult matchAndRewrite(IREE::LinalgExt::SortOp sortOp,
+ PatternRewriter &rewriter) const override {
+ if (!sortOp.getIsStable()) {
+ return rewriter.notifyMatchFailure(sortOp, "sort is not stable");
+ }
+ if (sortOp.hasPureBufferSemantics()) {
+ return rewriter.notifyMatchFailure(sortOp, "expected tensor semantics");
+ }
+ int64_t dimension = sortOp.getDimension();
+ std::optional<unsigned> positionOperand;
+ for (auto [index, input] : llvm::enumerate(sortOp.getInputs())) {
+ if (isIndexAlongDimension(input, dimension) &&
+ !sortOp.getResult(index).use_empty()) {
+ positionOperand = index;
+ break;
+ }
+ }
+ if (!positionOperand) {
+ return rewriter.notifyMatchFailure(
+ sortOp, "no used operand holds the positions along the dimension");
+ }
+
+ Block &block = sortOp.getRegion().front();
+ Operation *terminator = block.getTerminator();
+ Location loc = sortOp.getLoc();
+ OpBuilder::InsertionGuard guard(rewriter);
+ rewriter.setInsertionPoint(terminator);
+
+ // Evaluate the comparator a second time with the elements swapped.
+ IRMapping swapped;
+ for (unsigned i = 0, e = block.getNumArguments(); i < e; i += 2) {
+ swapped.map(block.getArgument(i), block.getArgument(i + 1));
+ swapped.map(block.getArgument(i + 1), block.getArgument(i));
+ }
+ SmallVector<Operation *> bodyOps(
+ llvm::make_pointer_range(block.without_terminator()));
+ for (Operation *op : bodyOps) {
+ rewriter.clone(*op, swapped);
+ }
+ Value before = terminator->getOperand(0);
+ Value after = swapped.lookupOrDefault(before);
+
+ // The comparator orders two elements if it holds in exactly one direction.
+ Value isOrdered = arith::XOrIOp::create(rewriter, loc, before, after);
+ Value lowerPosition =
+ arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::slt,
+ block.getArgument(2 * *positionOperand),
+ block.getArgument(2 * *positionOperand + 1));
+ Value result = arith::SelectOp::create(rewriter, loc, isOrdered, before,
+ lowerPosition);
+ rewriter.modifyOpInPlace(terminator,
+ [&]() { terminator->setOperand(0, result); });
+ rewriter.modifyOpInPlace(sortOp, [&]() { sortOp.setIsStable(false); });
+ return success();
+ }
+};
+
+/// Turns a stable sort into an unstable one if the order of the elements that
+/// the comparator does not order cannot be observed: a single integer operand
+/// whose comparator is an integer comparison of its two arguments. Two
+/// elements that such a comparator does not order are the same value.
+struct DropUnobservableSortStability
+ : OpRewritePattern<IREE::LinalgExt::SortOp> {
+ using Base::Base;
+ LogicalResult matchAndRewrite(IREE::LinalgExt::SortOp sortOp,
+ PatternRewriter &rewriter) const override {
+ if (!sortOp.getIsStable()) {
+ return rewriter.notifyMatchFailure(sortOp, "sort is not stable");
+ }
+ if (sortOp.getNumDpsInputs() != 1) {
+ return rewriter.notifyMatchFailure(sortOp, "expected a single operand");
+ }
+ Block &block = sortOp.getRegion().front();
+ Value lhs = block.getArgument(0);
+ Value rhs = block.getArgument(1);
+ auto cmpOp =
+ block.getTerminator()->getOperand(0).getDefiningOp<arith::CmpIOp>();
+ if (!cmpOp || !((cmpOp.getLhs() == lhs && cmpOp.getRhs() == rhs) ||
+ (cmpOp.getLhs() == rhs && cmpOp.getRhs() == lhs))) {
+ return rewriter.notifyMatchFailure(
+ sortOp, "comparator is not an integer comparison of its arguments");
+ }
+ rewriter.modifyOpInPlace(sortOp, [&]() { sortOp.setIsStable(false); });
+ return success();
+ }
+};
} // namespace
void SortOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *ctx) {
- results.add<RemoveUnusedSortOpResults>(ctx);
+ results.add<RemoveUnusedSortOpResults, FoldSortStabilityIntoComparator,
+ DropUnobservableSortStability>(ctx);
}
//===----------------------------------------------------------------------===//
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td
index f194ba7..9d38d62 100644
--- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td
+++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td
@@ -599,17 +599,49 @@
`dimension` with the given `comparator`.
See https://www.tensorflow.org/xla/operation_semantics#sort.
+
+ The comparator gets two elements, as one pair of scalars per operand, and
+ returns whether the first has to be placed before the second. It does not
+ order two elements if it returns the same value for both argument orders,
+ e.g. for equal keys both `false` with a strict comparison like `slt` and
+ both `true` with a non-strict one like `sle`.
+
+ By default the sort is not stable: elements that the comparator does not
+ order are placed in unspecified order. With `is_stable` set they keep their
+ input order: an element is only moved in front of another one if the
+ comparator returns `true` for that order and `false` for the opposite one.
+ A stable sort lowers to a slower algorithm, so only request it if the
+ order of such elements matters.
+
+ The comparator has to be consistent: if it does not order `a` and `b`, and
+ does not order `b` and `c`, it must not order `a` and `c` either. An
+ ordered floating point comparison is not consistent when the operand
+ contains NaNs, which it does not order with any other value. The result
+ for an inconsistent comparator is some permutation of the elements, in
+ unspecified order.
+
+ Example:
+ ```mlir
+ %sorted = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%arr : tensor<?xi64>) outs(%init : tensor<?xi64>) {
+ ^bb0(%lhs: i64, %rhs: i64):
+ %before = arith.cmpi slt, %lhs, %rhs : i64
+ iree_linalg_ext.yield %before : i1
+ } -> tensor<?xi64>
+ ```
}];
let arguments = (ins Variadic<AnyRankedTensorOrMemRef>:$inputs,
Variadic<AnyRankedTensorOrMemRef>:$outputs,
- I64Attr:$dimension
+ I64Attr:$dimension,
+ DefaultValuedAttr<BoolAttr, "false">:$is_stable
);
let results = (outs Variadic<AnyRankedTensor>:$results);
let regions = (region AnyRegion:$region);
let assemblyFormat = [{
attr-dict
`dimension` `(` $dimension `)`
+ (`is_stable` `(` $is_stable^ `)`)?
(`ins` `(` $inputs^ `:` type($inputs) `)`)?
`outs` `(` $outputs `:` type($outputs) `)`
$region (`->` type($results)^)?
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp
index 927cde9..31697f9 100644
--- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp
+++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp
@@ -985,9 +985,262 @@
});
}
+namespace {
+/// What the loop lowering of a sort operates on: the buffers that are sorted
+/// in place and the slice of them that is sorted. An element of the sort
+/// consists of one scalar per buffer.
+struct SortLoweringState {
+ Location loc;
+ /// The buffers holding the elements. All of them are permuted together.
+ SmallVector<Value> buffers;
+ /// The position of the sorted slice in the dimensions other than `sortDim`.
+ /// The entry of `sortDim` is ignored.
+ SmallVector<Value> ivs;
+ int64_t sortDim;
+ /// Gets the scalars of two elements as interleaved pairs and yields whether
+ /// the first element has to be placed before the second.
+ Block *comparator;
+};
+} // namespace
+
+/// Loads the element at position `pos` of the sorted slice.
+static SmallVector<Value>
+loadSortElement(OpBuilder &b, const SortLoweringState &state, Value pos) {
+ SmallVector<Value> indices(state.ivs);
+ indices[state.sortDim] = pos;
+ return llvm::map_to_vector(state.buffers, [&](Value buffer) -> Value {
+ return memref::LoadOp::create(b, state.loc, buffer, indices);
+ });
+}
+
+/// Stores `element` at position `pos` of the sorted slice.
+static void storeSortElement(OpBuilder &b, const SortLoweringState &state,
+ ArrayRef<Value> element, Value pos) {
+ SmallVector<Value> indices(state.ivs);
+ indices[state.sortDim] = pos;
+ for (auto [buffer, scalar] : llvm::zip_equal(state.buffers, element)) {
+ memref::StoreOp::create(b, state.loc, scalar, buffer, indices);
+ }
+}
+
+/// Inlines the comparator for the elements `lhs` and `rhs` and returns its
+/// result: an i1 that is true if `lhs` has to be placed before `rhs`.
+static Value emitSortComparator(OpBuilder &b, const SortLoweringState &state,
+ ArrayRef<Value> lhs, ArrayRef<Value> rhs) {
+ IRMapping map;
+ for (auto [index, scalars] : llvm::enumerate(llvm::zip_equal(lhs, rhs))) {
+ map.map(state.comparator->getArgument(2 * index), std::get<0>(scalars));
+ map.map(state.comparator->getArgument(2 * index + 1), std::get<1>(scalars));
+ }
+ for (Operation &op : state.comparator->without_terminator()) {
+ b.clone(op, map);
+ }
+ return map.lookup(state.comparator->getTerminator()->getOperand(0));
+}
+
+/// Returns an i1 that is true if the comparator orders `lhs` before `rhs`: it
+/// holds for (lhs, rhs) and not for (rhs, lhs). Unlike the comparator itself
+/// this is false for elements it does not order, also when it is a non-strict
+/// comparison that returns true for them.
+static Value emitIsStrictlyBefore(OpBuilder &b, const SortLoweringState &state,
+ ArrayRef<Value> lhs, ArrayRef<Value> rhs) {
+ Value before = emitSortComparator(b, state, lhs, rhs);
+ Value after = emitSortComparator(b, state, rhs, lhs);
+ Value trueVal = arith::ConstantIntOp::create(b, state.loc, b.getI1Type(), 1);
+ Value notAfter = arith::XOrIOp::create(b, state.loc, after, trueVal);
+ return arith::AndIOp::create(b, state.loc, before, notAfter);
+}
+
+/// Places `element` into the heap that occupies the positions [0, `end`),
+/// starting at the vacant position `root` and moving it down until neither
+/// child has to be placed after it. The heap keeps the element that sorts
+/// last at position 0; the children of position i are at 2i+1 and 2i+2.
+///
+/// hole = root
+/// while (2 * hole + 1 < end) {
+/// child = <the child of hole that sorts last>
+/// if (!comparator(element, child)) break
+/// slice[hole] = child; hole = <position of child>
+/// }
+/// slice[hole] = element
+static void emitHeapSiftDown(OpBuilder &b, const SortLoweringState &state,
+ Value root, ArrayRef<Value> element, Value end) {
+ Location loc = state.loc;
+ Type indexType = b.getIndexType();
+ Type i1Type = b.getI1Type();
+ Value one = arith::ConstantIndexOp::create(b, loc, 1);
+ Value two = arith::ConstantIndexOp::create(b, loc, 2);
+ Value trueVal = arith::ConstantIntOp::create(b, loc, i1Type, 1);
+ Value falseVal = arith::ConstantIntOp::create(b, loc, i1Type, 0);
+ Value lastPos = arith::SubIOp::create(b, loc, end, one);
+
+ // Loop state: the vacant position and whether to continue.
+ auto whileOp = scf::WhileOp::create(
+ b, loc, TypeRange{indexType, i1Type}, ValueRange{root, trueVal},
+ [loc](OpBuilder &b, Location, ValueRange args) {
+ scf::ConditionOp::create(b, loc, args[1], args);
+ },
+ [&state, loc, element, end, one, two, falseVal,
+ lastPos](OpBuilder &b, Location, ValueRange args) {
+ Value hole = args[0];
+ Value left = arith::AddIOp::create(
+ b, loc, arith::MulIOp::create(b, loc, hole, two), one);
+ Value hasChild =
+ arith::CmpIOp::create(b, loc, arith::CmpIPredicate::slt, left, end);
+ auto ifOp = scf::IfOp::create(
+ b, loc, hasChild,
+ [&state, loc, element, hole, left, one, lastPos](OpBuilder &b,
+ Location) {
+ // The right child may not exist. Clamping it to the last heap
+ // position then compares the left child with itself.
+ Value right = arith::MinSIOp::create(
+ b, loc, arith::AddIOp::create(b, loc, left, one), lastPos);
+ SmallVector<Value> leftElement = loadSortElement(b, state, left);
+ SmallVector<Value> rightElement =
+ loadSortElement(b, state, right);
+ Value takeRight =
+ emitSortComparator(b, state, leftElement, rightElement);
+ Value child =
+ arith::SelectOp::create(b, loc, takeRight, right, left);
+ SmallVector<Value> childElement;
+ for (auto [l, r] : llvm::zip_equal(leftElement, rightElement)) {
+ childElement.push_back(
+ arith::SelectOp::create(b, loc, takeRight, r, l));
+ }
+ Value moveDown =
+ emitSortComparator(b, state, element, childElement);
+ scf::IfOp::create(
+ b, loc, moveDown,
+ [&state, loc, &childElement, hole](OpBuilder &b, Location) {
+ storeSortElement(b, state, childElement, hole);
+ scf::YieldOp::create(b, loc);
+ });
+ Value newHole =
+ arith::SelectOp::create(b, loc, moveDown, child, hole);
+ scf::YieldOp::create(b, loc, ValueRange{newHole, moveDown});
+ },
+ [loc, hole, falseVal](OpBuilder &b, Location) {
+ scf::YieldOp::create(b, loc, ValueRange{hole, falseVal});
+ });
+ scf::YieldOp::create(b, loc, ifOp.getResults());
+ });
+ storeSortElement(b, state, element, whileOp.getResult(0));
+}
+
+/// Emits an in-place heapsort of the `size` elements of the slice: O(n log n)
+/// comparisons and no storage besides the buffers. It is not stable: elements
+/// that the comparator does not order end up in unspecified order.
+///
+/// for (root = size / 2 - 1; root >= 0; --root) // build the heap
+/// siftDown(root, slice[root], size)
+/// for (end = size - 1; end > 0; --end) { // move its first element
+/// last = slice[end]; slice[end] = slice[0] // behind the heap
+/// siftDown(0, last, end)
+/// }
+static void emitHeapSort(OpBuilder &b, const SortLoweringState &state,
+ Value size) {
+ Location loc = state.loc;
+ Value zero = arith::ConstantIndexOp::create(b, loc, 0);
+ Value one = arith::ConstantIndexOp::create(b, loc, 1);
+ Value two = arith::ConstantIndexOp::create(b, loc, 2);
+
+ Value half = arith::DivSIOp::create(b, loc, size, two);
+ Value lastRoot = arith::SubIOp::create(b, loc, half, one);
+ scf::ForOp::create(b, loc, zero, half, one, ValueRange{},
+ [&state, loc, lastRoot, size](OpBuilder &b, Location,
+ Value iv, ValueRange) {
+ Value root = arith::SubIOp::create(b, loc, lastRoot, iv);
+ SmallVector<Value> element =
+ loadSortElement(b, state, root);
+ emitHeapSiftDown(b, state, root, element, size);
+ scf::YieldOp::create(b, loc);
+ });
+
+ Value lastPos = arith::SubIOp::create(b, loc, size, one);
+ scf::ForOp::create(b, loc, zero, lastPos, one, ValueRange{},
+ [&state, loc, lastPos, zero](OpBuilder &b, Location,
+ Value iv, ValueRange) {
+ Value end = arith::SubIOp::create(b, loc, lastPos, iv);
+ SmallVector<Value> first =
+ loadSortElement(b, state, zero);
+ SmallVector<Value> last = loadSortElement(b, state, end);
+ storeSortElement(b, state, first, end);
+ emitHeapSiftDown(b, state, zero, last, end);
+ scf::YieldOp::create(b, loc);
+ });
+}
+
+/// Emits an in-place binary insertion sort of the `size` elements of the
+/// slice. It is stable and needs no storage besides the buffers, at the cost
+/// of O(n^2) element moves (and O(n log n) comparisons).
+///
+/// for (i = 1; i < size; ++i) {
+/// element = slice[i]
+/// // First position in the sorted prefix [0, i) whose element has to
+/// // stay behind `element`.
+/// lo = 0; hi = i
+/// while (lo < hi) {
+/// mid = (lo + hi) / 2
+/// if (isStrictlyBefore(element, slice[mid])) hi = mid else lo = mid + 1
+/// }
+/// for (j = i; j > lo; --j) slice[j] = slice[j - 1]
+/// slice[lo] = element
+/// }
+static void emitStableInsertionSort(OpBuilder &b,
+ const SortLoweringState &state,
+ Value size) {
+ Location loc = state.loc;
+ Value zero = arith::ConstantIndexOp::create(b, loc, 0);
+ Value one = arith::ConstantIndexOp::create(b, loc, 1);
+ Value two = arith::ConstantIndexOp::create(b, loc, 2);
+ scf::ForOp::create(
+ b, loc, one, size, one, ValueRange{},
+ [&state, loc, zero, one, two](OpBuilder &b, Location, Value i,
+ ValueRange) {
+ SmallVector<Value> element = loadSortElement(b, state, i);
+ Type indexType = b.getIndexType();
+ auto searchOp = scf::WhileOp::create(
+ b, loc, TypeRange{indexType, indexType}, ValueRange{zero, i},
+ [loc](OpBuilder &b, Location, ValueRange args) {
+ Value inRange = arith::CmpIOp::create(
+ b, loc, arith::CmpIPredicate::slt, args[0], args[1]);
+ scf::ConditionOp::create(b, loc, inRange, args);
+ },
+ [&state, loc, &element, one, two](OpBuilder &b, Location,
+ ValueRange args) {
+ Value lo = args[0];
+ Value hi = args[1];
+ Value mid = arith::DivSIOp::create(
+ b, loc, arith::AddIOp::create(b, loc, lo, hi), two);
+ SmallVector<Value> midElement = loadSortElement(b, state, mid);
+ Value before =
+ emitIsStrictlyBefore(b, state, element, midElement);
+ Value newLo = arith::SelectOp::create(
+ b, loc, before, lo, arith::AddIOp::create(b, loc, mid, one));
+ Value newHi = arith::SelectOp::create(b, loc, before, mid, hi);
+ scf::YieldOp::create(b, loc, ValueRange{newLo, newHi});
+ });
+ Value insertPos = searchOp.getResult(0);
+ Value numToMove = arith::SubIOp::create(b, loc, i, insertPos);
+ scf::ForOp::create(b, loc, zero, numToMove, one, ValueRange{},
+ [&state, loc, i, one](OpBuilder &b, Location,
+ Value iv, ValueRange) {
+ Value to = arith::SubIOp::create(b, loc, i, iv);
+ Value from =
+ arith::SubIOp::create(b, loc, to, one);
+ SmallVector<Value> moved =
+ loadSortElement(b, state, from);
+ storeSortElement(b, state, moved, to);
+ scf::YieldOp::create(b, loc);
+ });
+ storeSortElement(b, state, element, insertPos);
+ scf::YieldOp::create(b, loc);
+ });
+}
+
LogicalResult SortOp::generateScalarImplementation(OpBuilder &b, Location loc,
ValueRange ivs) {
- auto sortDim = getDimension();
+ int64_t sortDim = getDimension();
Value zero = arith::ConstantIndexOp::create(b, loc, 0);
Value one = arith::ConstantIndexOp::create(b, loc, 1);
Value sortDimSize;
@@ -997,29 +1250,48 @@
sortDimSize = arith::ConstantIndexOp::create(
b, loc, getOperandType(0).getDimSize(sortDim));
}
- SmallVector<Value> indices(ivs);
- Value firstSortPass = arith::CmpIOp::create(b, loc, arith::CmpIPredicate::eq,
- indices[sortDim], zero);
- scf::IfOp::create(b, loc, firstSortPass, [&](OpBuilder &b, Location loc) {
- scf::ForOp::create(
- b, loc, zero, sortDimSize, one, ValueRange{},
- [&](OpBuilder &b, Location loc, Value iv, ValueRange iters) {
- SmallVector<Value> indices(ivs);
- indices[sortDim] = iv;
- for (auto [input, output] :
- llvm::zip_equal(getDpsInputs(), getDpsInits())) {
- Value v = memref::LoadOp::create(b, loc, input, indices);
- memref::StoreOp::create(b, loc, v, output, indices);
- }
- scf::YieldOp::create(b, loc);
- });
- scf::YieldOp::create(b, loc);
- });
- Value ub = arith::SubIOp::create(b, loc, sortDimSize, one);
- SmallVector<Value> compareOperands(getDpsInits().begin(),
- getDpsInits().end());
- emitBubbleSortSweep(b, loc, zero, one, ub, sortDim, ivs, compareOperands,
- /*carryOperands=*/{}, getRegion());
+ SortLoweringState state{loc, llvm::to_vector(getDpsInits()),
+ llvm::to_vector(ivs), sortDim, &getRegion().front()};
+ // Operands that are sorted in place need no copy.
+ SmallVector<std::pair<Value, Value>> copies;
+ for (auto [input, output] : llvm::zip_equal(getDpsInputs(), getDpsInits())) {
+ if (input != output) {
+ copies.emplace_back(input, output);
+ }
+ }
+ bool isStable = getIsStable();
+
+ // The loop nest built from the iteration domain also iterates over the sort
+ // dimension. A slice is sorted as a whole, so everything happens in the
+ // first of these iterations: copy the inputs to the outputs, then sort the
+ // outputs in place.
+ Value firstIteration = arith::CmpIOp::create(b, loc, arith::CmpIPredicate::eq,
+ ivs[sortDim], zero);
+ scf::IfOp::create(
+ b, loc, firstIteration,
+ [&state, &copies, loc, zero, one, sortDimSize, isStable](OpBuilder &b,
+ Location) {
+ if (!copies.empty()) {
+ scf::ForOp::create(
+ b, loc, zero, sortDimSize, one, ValueRange{},
+ [&state, &copies, loc](OpBuilder &b, Location, Value iv,
+ ValueRange) {
+ SmallVector<Value> indices(state.ivs);
+ indices[state.sortDim] = iv;
+ for (auto [input, output] : copies) {
+ Value v = memref::LoadOp::create(b, loc, input, indices);
+ memref::StoreOp::create(b, loc, v, output, indices);
+ }
+ scf::YieldOp::create(b, loc);
+ });
+ }
+ if (isStable) {
+ emitStableInsertionSort(b, state, sortDimSize);
+ } else {
+ emitHeapSort(b, state, sortDimSize);
+ }
+ scf::YieldOp::create(b, loc);
+ });
return success();
}
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/canonicalize.mlir b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/canonicalize.mlir
index 9ae12ec..9132c6d 100644
--- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/canonicalize.mlir
+++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/canonicalize.mlir
@@ -29,6 +29,199 @@
// -----
+// A stable sort with an operand that holds the positions along the sort
+// dimension: the comparator orders the elements it does not order itself by
+// position, and the sort does not have to be stable anymore.
+func.func @sort_fold_stability_into_comparator(%arg0: tensor<3x4xf32>)
+ -> (tensor<3x4xf32>, tensor<3x4xi64>) {
+ %empty_pos = tensor.empty() : tensor<3x4xi64>
+ %positions = linalg.generic {
+ indexing_maps = [affine_map<(d0, d1) -> (d0, d1)>],
+ iterator_types = ["parallel", "parallel"]}
+ outs(%empty_pos : tensor<3x4xi64>) {
+ ^bb0(%out: i64):
+ %i = linalg.index 1 : index
+ %i64 = arith.index_cast %i : index to i64
+ linalg.yield %i64 : i64
+ } -> tensor<3x4xi64>
+ %empty = tensor.empty() : tensor<3x4xf32>
+ %0:2 = iree_linalg_ext.sort dimension(1) is_stable(true)
+ ins(%arg0, %positions : tensor<3x4xf32>, tensor<3x4xi64>)
+ outs(%empty, %empty_pos : tensor<3x4xf32>, tensor<3x4xi64>) {
+ ^bb0(%arg2: f32, %arg3: f32, %arg4: i64, %arg5: i64):
+ %1 = arith.cmpf oge, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<3x4xf32>, tensor<3x4xi64>
+ return %0#0, %0#1 : tensor<3x4xf32>, tensor<3x4xi64>
+}
+// CHECK-LABEL: func.func @sort_fold_stability_into_comparator
+// CHECK: %[[POSITIONS:.+]] = linalg.generic
+// CHECK: iree_linalg_ext.sort
+// CHECK-NOT: is_stable
+// CHECK-SAME: dimension(1)
+// CHECK-SAME: ins(%{{.+}}, %[[POSITIONS]] : tensor<3x4xf32>, tensor<3x4xi64>)
+// CHECK: ^bb0(%[[LHS:.+]]: f32, %[[RHS:.+]]: f32, %[[LHS_POS:.+]]: i64, %[[RHS_POS:.+]]: i64):
+// CHECK: %[[BEFORE:.+]] = arith.cmpf oge, %[[LHS]], %[[RHS]] : f32
+// CHECK: %[[AFTER:.+]] = arith.cmpf oge, %[[RHS]], %[[LHS]] : f32
+// CHECK: %[[ORDERED:.+]] = arith.xori %[[BEFORE]], %[[AFTER]] : i1
+// CHECK: %[[LOWER_POS:.+]] = arith.cmpi slt, %[[LHS_POS]], %[[RHS_POS]] : i64
+// CHECK: %[[RESULT:.+]] = arith.select %[[ORDERED]], %[[BEFORE]], %[[LOWER_POS]] : i1
+// CHECK: iree_linalg_ext.yield %[[RESULT]] : i1
+
+// -----
+
+// Positions along another dimension than the sorted one do not tell the input
+// order of the elements of a sorted slice. The sort stays stable.
+func.func @sort_stable_positions_of_other_dimension(%arg0: tensor<3x4xf32>)
+ -> (tensor<3x4xf32>, tensor<3x4xi64>) {
+ %empty_pos = tensor.empty() : tensor<3x4xi64>
+ %positions = linalg.generic {
+ indexing_maps = [affine_map<(d0, d1) -> (d0, d1)>],
+ iterator_types = ["parallel", "parallel"]}
+ outs(%empty_pos : tensor<3x4xi64>) {
+ ^bb0(%out: i64):
+ %i = linalg.index 0 : index
+ %i64 = arith.index_cast %i : index to i64
+ linalg.yield %i64 : i64
+ } -> tensor<3x4xi64>
+ %empty = tensor.empty() : tensor<3x4xf32>
+ %0:2 = iree_linalg_ext.sort dimension(1) is_stable(true)
+ ins(%arg0, %positions : tensor<3x4xf32>, tensor<3x4xi64>)
+ outs(%empty, %empty_pos : tensor<3x4xf32>, tensor<3x4xi64>) {
+ ^bb0(%arg2: f32, %arg3: f32, %arg4: i64, %arg5: i64):
+ %1 = arith.cmpf oge, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<3x4xf32>, tensor<3x4xi64>
+ return %0#0, %0#1 : tensor<3x4xf32>, tensor<3x4xi64>
+}
+// CHECK-LABEL: func.func @sort_stable_positions_of_other_dimension
+// CHECK: iree_linalg_ext.sort
+// CHECK-SAME: dimension(1) is_stable(true)
+// CHECK: ^bb0(%[[LHS:.+]]: f32, %[[RHS:.+]]: f32, %{{.+}}: i64, %{{.+}}: i64):
+// CHECK-NEXT: %[[BEFORE:.+]] = arith.cmpf oge, %[[LHS]], %[[RHS]] : f32
+// CHECK-NEXT: iree_linalg_ext.yield %[[BEFORE]] : i1
+
+// -----
+
+// The sorted positions are not used. The operand is dropped instead of being
+// kept for the comparator, and the sort of the remaining operand stays stable.
+func.func @sort_stable_unused_positions(%arg0: tensor<3x4xf32>)
+ -> tensor<3x4xf32> {
+ %empty_pos = tensor.empty() : tensor<3x4xi64>
+ %positions = linalg.generic {
+ indexing_maps = [affine_map<(d0, d1) -> (d0, d1)>],
+ iterator_types = ["parallel", "parallel"]}
+ outs(%empty_pos : tensor<3x4xi64>) {
+ ^bb0(%out: i64):
+ %i = linalg.index 1 : index
+ %i64 = arith.index_cast %i : index to i64
+ linalg.yield %i64 : i64
+ } -> tensor<3x4xi64>
+ %empty = tensor.empty() : tensor<3x4xf32>
+ %0:2 = iree_linalg_ext.sort dimension(1) is_stable(true)
+ ins(%arg0, %positions : tensor<3x4xf32>, tensor<3x4xi64>)
+ outs(%empty, %empty_pos : tensor<3x4xf32>, tensor<3x4xi64>) {
+ ^bb0(%arg2: f32, %arg3: f32, %arg4: i64, %arg5: i64):
+ %1 = arith.cmpf oge, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<3x4xf32>, tensor<3x4xi64>
+ return %0#0 : tensor<3x4xf32>
+}
+// CHECK-LABEL: func.func @sort_stable_unused_positions
+// CHECK-SAME: %[[ARG0:.+]]: tensor<3x4xf32>
+// CHECK: iree_linalg_ext.sort
+// CHECK-SAME: dimension(1) is_stable(true)
+// CHECK-SAME: ins(%[[ARG0]] : tensor<3x4xf32>)
+// CHECK: ^bb0(%[[LHS:.+]]: f32, %[[RHS:.+]]: f32):
+// CHECK-NEXT: %[[BEFORE:.+]] = arith.cmpf oge, %[[LHS]], %[[RHS]] : f32
+// CHECK-NEXT: iree_linalg_ext.yield %[[BEFORE]] : i1
+
+// -----
+
+// A sort that is not stable is left alone.
+func.func @sort_unstable_with_positions(%arg0: tensor<3x4xf32>)
+ -> (tensor<3x4xf32>, tensor<3x4xi64>) {
+ %empty_pos = tensor.empty() : tensor<3x4xi64>
+ %positions = linalg.generic {
+ indexing_maps = [affine_map<(d0, d1) -> (d0, d1)>],
+ iterator_types = ["parallel", "parallel"]}
+ outs(%empty_pos : tensor<3x4xi64>) {
+ ^bb0(%out: i64):
+ %i = linalg.index 1 : index
+ %i64 = arith.index_cast %i : index to i64
+ linalg.yield %i64 : i64
+ } -> tensor<3x4xi64>
+ %empty = tensor.empty() : tensor<3x4xf32>
+ %0:2 = iree_linalg_ext.sort dimension(1)
+ ins(%arg0, %positions : tensor<3x4xf32>, tensor<3x4xi64>)
+ outs(%empty, %empty_pos : tensor<3x4xf32>, tensor<3x4xi64>) {
+ ^bb0(%arg2: f32, %arg3: f32, %arg4: i64, %arg5: i64):
+ %1 = arith.cmpf oge, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<3x4xf32>, tensor<3x4xi64>
+ return %0#0, %0#1 : tensor<3x4xf32>, tensor<3x4xi64>
+}
+// CHECK-LABEL: func.func @sort_unstable_with_positions
+// CHECK: iree_linalg_ext.sort
+// CHECK: ^bb0(%[[LHS:.+]]: f32, %[[RHS:.+]]: f32, %{{.+}}: i64, %{{.+}}: i64):
+// CHECK-NEXT: %[[BEFORE:.+]] = arith.cmpf oge, %[[LHS]], %[[RHS]] : f32
+// CHECK-NEXT: iree_linalg_ext.yield %[[BEFORE]] : i1
+
+// -----
+
+// Integers that an integer comparison does not order are the same value, so
+// their order cannot be observed and the sort does not have to be stable.
+func.func @sort_drop_unobservable_stability(%arg0: tensor<128xi32>)
+ -> tensor<128xi32> {
+ %empty = tensor.empty() : tensor<128xi32>
+ %0 = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%arg0 : tensor<128xi32>) outs(%empty : tensor<128xi32>) {
+ ^bb0(%arg1: i32, %arg2: i32):
+ %1 = arith.cmpi sle, %arg1, %arg2 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<128xi32>
+ return %0 : tensor<128xi32>
+}
+// CHECK-LABEL: func.func @sort_drop_unobservable_stability
+// CHECK: iree_linalg_ext.sort
+// CHECK-NOT: is_stable
+// CHECK-SAME: dimension(0)
+// CHECK-SAME: ins(
+
+// -----
+
+// Floats that compare equal can differ (0.0 and -0.0), and a comparator that
+// does more than comparing its arguments can leave different elements
+// unordered. These sorts stay stable.
+func.func @sort_keep_observable_stability(%arg0: tensor<128xf32>,
+ %arg1: tensor<128xi32>) -> (tensor<128xf32>, tensor<128xi32>) {
+ %empty0 = tensor.empty() : tensor<128xf32>
+ %0 = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%arg0 : tensor<128xf32>) outs(%empty0 : tensor<128xf32>) {
+ ^bb0(%arg2: f32, %arg3: f32):
+ %1 = arith.cmpf ole, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<128xf32>
+ %empty1 = tensor.empty() : tensor<128xi32>
+ %2 = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%arg1 : tensor<128xi32>) outs(%empty1 : tensor<128xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32):
+ %c4 = arith.constant 4 : i32
+ %lhs = arith.shrsi %arg2, %c4 : i32
+ %rhs = arith.shrsi %arg3, %c4 : i32
+ %3 = arith.cmpi sle, %lhs, %rhs : i32
+ iree_linalg_ext.yield %3 : i1
+ } -> tensor<128xi32>
+ return %0, %2 : tensor<128xf32>, tensor<128xi32>
+}
+// CHECK-LABEL: func.func @sort_keep_observable_stability
+// CHECK: iree_linalg_ext.sort
+// CHECK-SAME: dimension(0) is_stable(true)
+// CHECK: iree_linalg_ext.sort
+// CHECK-SAME: dimension(0) is_stable(true)
+
+// -----
+
func.func @gather_to_extract_slice_expand(%source : tensor<1024x128xi32>, %indices : tensor<1x1xi32>) -> (tensor<1x1x128xi32>) {
%empty = tensor.empty() : tensor<1x1x128xi32>
%result = iree_linalg_ext.gather dimension_map = [0]
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir
index c2ee092..c3f43d5 100644
--- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir
+++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir
@@ -21,6 +21,24 @@
// -----
+func.func @sort_stable_tensor(%arg0: tensor<128xi32>) -> tensor<128xi32> {
+ %empty = tensor.empty() : tensor<128xi32>
+ %0 = iree_linalg_ext.sort
+ dimension(0) is_stable(true)
+ ins(%arg0 : tensor<128xi32>) outs(%empty : tensor<128xi32>) {
+ ^bb0(%arg1: i32, %arg2: i32):
+ %1 = arith.cmpi sgt, %arg1, %arg2 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<128xi32>
+ return %0 : tensor<128xi32>
+}
+// CHECK-LABEL: func.func @sort_stable_tensor(
+// CHECK: iree_linalg_ext.sort
+// CHECK-SAME: dimension(0) is_stable(true)
+// CHECK-SAME: ins(%{{.+}} : tensor<128xi32>)
+
+// -----
+
func.func @sort_memref(%arg0: memref<128xi32>) {
iree_linalg_ext.sort dimension(0)
ins(%arg0 : memref<128xi32>) outs(%arg0 : memref<128xi32>) {
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/convert_to_loops.mlir b/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/convert_to_loops.mlir
index a938b46..36ae73e 100644
--- a/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/convert_to_loops.mlir
+++ b/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/convert_to_loops.mlir
@@ -1,5 +1,8 @@
// RUN: iree-opt --split-input-file --pass-pipeline="builtin.module(func.func(iree-linalg-ext-to-loops))" %s | FileCheck %s
+// Sorting lowers to an in-place heapsort that runs in the first iteration of
+// the loop over the sort dimension: build the heap, then repeatedly move its
+// first element behind it. Both loops sift an element down with a scf.while.
func.func @sort_1d(%arg0: memref<128xi32>) {
iree_linalg_ext.sort dimension(0)
ins(%arg0 : memref<128xi32>) outs(%arg0 : memref<128xi32>) {
@@ -12,19 +15,57 @@
// CHECK-LABEL: func.func @sort_1d
// CHECK-SAME: %[[BUF:[a-zA-Z0-9]+]]
// CHECK-DAG: %[[C128:.+]] = arith.constant 128 : index
+// CHECK-DAG: %[[C127:.+]] = arith.constant 127 : index
+// CHECK-DAG: %[[C64:.+]] = arith.constant 64 : index
+// CHECK-DAG: %[[C63:.+]] = arith.constant 63 : index
// CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index
// CHECK-DAG: %[[C1:.+]] = arith.constant 1 : index
-// CHECK-DAG: %[[C127:.+]] = arith.constant 127 : index
-// CHECK: scf.for %[[ARG1:.+]] = %[[C0]] to %[[C128]] step %[[C1]]
-// CHECK: scf.for %[[ARG2:.+]] = %[[C0]] to %[[C127]] step %[[C1]]
-// CHECK: %[[T1:.+]] = arith.addi %[[ARG2]], %[[C1]] : index
-// CHECK: %[[V1:.+]] = memref.load %[[BUF]][%[[ARG2]]]
-// CHECK: %[[V2:.+]] = memref.load %[[BUF]][%[[T1]]]
-// CHECK: %[[COND:.+]] = arith.cmpi sgt, %[[V1]], %[[V2]] : i32
-// CHECK: %[[NEW1:.+]] = arith.select %[[COND]], %[[V1]], %[[V2]] : i32
-// CHECK: %[[NEW2:.+]] = arith.select %[[COND]], %[[V2]], %[[V1]] : i32
-// CHECK: memref.store %[[NEW1]], %[[BUF]][%[[ARG2]]]
-// CHECK: memref.store %[[NEW2]], %[[BUF]][%[[T1]]]
+// CHECK-DAG: %[[C2:.+]] = arith.constant 2 : index
+// CHECK-DAG: %[[TRUE:.+]] = arith.constant true
+// CHECK-DAG: %[[FALSE:.+]] = arith.constant false
+// CHECK: scf.for %[[I:.+]] = %[[C0]] to %[[C128]] step %[[C1]]
+// CHECK: %[[FIRST:.+]] = arith.cmpi eq, %[[I]], %[[C0]] : index
+// CHECK: scf.if %[[FIRST]]
+// The operand is sorted in place, there is nothing to copy.
+// CHECK-NOT: memref.store
+// Build the heap.
+// CHECK: scf.for %[[J:.+]] = %[[C0]] to %[[C64]] step %[[C1]]
+// CHECK: %[[ROOT:.+]] = arith.subi %[[C63]], %[[J]] : index
+// CHECK: %[[X:.+]] = memref.load %[[BUF]][%[[ROOT]]]
+// CHECK: %[[W:.+]]:2 = scf.while (%[[HOLE:.+]] = %[[ROOT]], %[[GO:.+]] = %[[TRUE]])
+// CHECK: scf.condition(%[[GO]]) %[[HOLE]], %[[GO]]
+// CHECK: } do {
+// CHECK: ^bb0(%[[H:.+]]: index, %{{.+}}: i1):
+// CHECK: %[[H2:.+]] = arith.muli %[[H]], %[[C2]] : index
+// CHECK: %[[LEFT:.+]] = arith.addi %[[H2]], %[[C1]] : index
+// CHECK: %[[HAS_CHILD:.+]] = arith.cmpi slt, %[[LEFT]], %[[C128]] : index
+// CHECK: %[[R:.+]]:2 = scf.if %[[HAS_CHILD]] -> (index, i1)
+// CHECK: %[[LEFT1:.+]] = arith.addi %[[LEFT]], %[[C1]] : index
+// CHECK: %[[RIGHT:.+]] = arith.minsi %[[LEFT1]], %[[C127]] : index
+// CHECK: %[[LV:.+]] = memref.load %[[BUF]][%[[LEFT]]]
+// CHECK: %[[RV:.+]] = memref.load %[[BUF]][%[[RIGHT]]]
+// CHECK: %[[TAKE_RIGHT:.+]] = arith.cmpi sgt, %[[LV]], %[[RV]] : i32
+// CHECK: %[[NEXT:.+]] = arith.select %[[TAKE_RIGHT]], %[[RIGHT]], %[[LEFT]] : index
+// CHECK: %[[NV:.+]] = arith.select %[[TAKE_RIGHT]], %[[RV]], %[[LV]] : i32
+// CHECK: %[[MOVE:.+]] = arith.cmpi sgt, %[[X]], %[[NV]] : i32
+// CHECK: scf.if %[[MOVE]]
+// CHECK: memref.store %[[NV]], %[[BUF]][%[[H]]]
+// CHECK: %[[NEW_HOLE:.+]] = arith.select %[[MOVE]], %[[NEXT]], %[[H]] : index
+// CHECK: scf.yield %[[NEW_HOLE]], %[[MOVE]] : index, i1
+// CHECK: } else {
+// CHECK: scf.yield %[[H]], %[[FALSE]] : index, i1
+// CHECK: scf.yield %[[R]]#0, %[[R]]#1 : index, i1
+// CHECK: memref.store %[[X]], %[[BUF]][%[[W]]#0]
+// Move the first heap element behind the shrinking heap.
+// CHECK: scf.for %[[K:.+]] = %[[C0]] to %[[C127]] step %[[C1]]
+// CHECK: %[[END:.+]] = arith.subi %[[C127]], %[[K]] : index
+// CHECK: %[[TOP:.+]] = memref.load %[[BUF]][%[[C0]]]
+// CHECK: %[[LAST:.+]] = memref.load %[[BUF]][%[[END]]]
+// CHECK: memref.store %[[TOP]], %[[BUF]][%[[END]]]
+// CHECK: %[[W2:.+]]:2 = scf.while (%{{.+}} = %[[C0]], %{{.+}} = %[[TRUE]])
+// CHECK: arith.cmpi slt, %{{.+}}, %[[END]] : index
+// CHECK: arith.cmpi sgt, %[[LAST]], %{{.+}} : i32
+// CHECK: memref.store %[[LAST]], %[[BUF]][%[[W2]]#0]
// -----
@@ -41,26 +82,86 @@
// CHECK-SAME: %[[BUF:[a-zA-Z0-9]+]]
// CHECK-DAG: %[[C16:.+]] = arith.constant 16 : index
// CHECK-DAG: %[[C32:.+]] = arith.constant 32 : index
+// CHECK-DAG: %[[C15:.+]] = arith.constant 15 : index
+// CHECK-DAG: %[[C8:.+]] = arith.constant 8 : index
+// CHECK-DAG: %[[C7:.+]] = arith.constant 7 : index
// CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index
// CHECK-DAG: %[[C1:.+]] = arith.constant 1 : index
-// CHECK-DAG: %[[C15:.+]] = arith.constant 15 : index
-// CHECK: scf.for %[[ARG1:.+]] = %[[C0]] to %[[C16]] step %[[C1]]
-// CHECK: scf.for %[[ARG2:.+]] = %[[C0]] to %[[C32]] step %[[C1]]
-// CHECK: scf.for %[[ARG3:.+]] = %[[C0]] to %[[C15]] step %[[C1]]
-// CHECK: %[[T1:.+]] = arith.addi %[[ARG3]], %[[C1]] : index
-// CHECK: %[[V1:.+]] = memref.load %[[BUF]][%[[ARG3]], %[[ARG2]]]
-// CHECK: %[[V2:.+]] = memref.load %[[BUF]][%[[T1]], %[[ARG2]]]
-// CHECK: %[[COND:.+]] = arith.cmpi sgt, %[[V1]], %[[V2]] : i32
-// CHECK: %[[NEW1:.+]] = arith.select %[[COND]], %[[V1]], %[[V2]] : i32
-// CHECK: %[[NEW2:.+]] = arith.select %[[COND]], %[[V2]], %[[V1]] : i32
-// CHECK: memref.store %[[NEW1]], %[[BUF]][%[[ARG3]], %[[ARG2]]]
-// CHECK: memref.store %[[NEW2]], %[[BUF]][%[[T1]], %[[ARG2]]]
+// CHECK: scf.for %[[I:.+]] = %[[C0]] to %[[C16]] step %[[C1]]
+// CHECK: scf.for %[[J:.+]] = %[[C0]] to %[[C32]] step %[[C1]]
+// CHECK: %[[FIRST:.+]] = arith.cmpi eq, %[[I]], %[[C0]] : index
+// CHECK: scf.if %[[FIRST]]
+// CHECK: scf.for %[[K:.+]] = %[[C0]] to %[[C8]] step %[[C1]]
+// CHECK: %[[ROOT:.+]] = arith.subi %[[C7]], %[[K]] : index
+// CHECK: %[[X:.+]] = memref.load %[[BUF]][%[[ROOT]], %[[J]]]
+// CHECK: %[[W:.+]]:2 = scf.while
+// CHECK: %[[LV:.+]] = memref.load %[[BUF]][%[[LEFT:.+]], %[[J]]]
+// CHECK: %[[RV:.+]] = memref.load %[[BUF]][%[[RIGHT:.+]], %[[J]]]
+// CHECK: arith.cmpi sgt, %[[LV]], %[[RV]] : i32
+// CHECK: memref.store %[[X]], %[[BUF]][%[[W]]#0, %[[J]]]
+// CHECK: scf.for %[[K2:.+]] = %[[C0]] to %[[C15]] step %[[C1]]
+// CHECK: %[[END:.+]] = arith.subi %[[C15]], %[[K2]] : index
+// CHECK: %[[TOP:.+]] = memref.load %[[BUF]][%[[C0]], %[[J]]]
+// CHECK: %[[LAST:.+]] = memref.load %[[BUF]][%[[END]], %[[J]]]
+// CHECK: memref.store %[[TOP]], %[[BUF]][%[[END]], %[[J]]]
+// CHECK: %[[W2:.+]]:2 = scf.while
+// CHECK: memref.store %[[LAST]], %[[BUF]][%[[W2]]#0, %[[J]]]
// -----
-func.func @sort_multi(%arg0: memref<128xf32>, %arg1: memref<128xi32>) {
+// The first operand is not sorted in place and is copied to its output first.
+// All operands are moved together; the comparator only sees the keys.
+func.func @sort_multi(%arg0: memref<128xf32>, %arg1: memref<128xi32>,
+ %arg2: memref<128xf32>) {
iree_linalg_ext.sort
dimension(0)
+ ins(%arg0, %arg1 : memref<128xf32>, memref<128xi32>) outs(%arg2, %arg1 : memref<128xf32>, memref<128xi32>) {
+ ^bb0(%arg3: f32, %arg4: f32, %arg5: i32, %arg6: i32):
+ %0 = arith.cmpf ogt, %arg3, %arg4 : f32
+ iree_linalg_ext.yield %0 : i1
+ }
+ return
+}
+// CHECK-LABEL: func.func @sort_multi
+// CHECK-SAME: %[[IN1:[a-zA-Z0-9]+]]
+// CHECK-SAME: %[[BUF2:[a-zA-Z0-9]+]]
+// CHECK-SAME: %[[BUF1:[a-zA-Z0-9]+]]
+// CHECK-DAG: %[[C128:.+]] = arith.constant 128 : index
+// CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index
+// CHECK-DAG: %[[C1:.+]] = arith.constant 1 : index
+// CHECK: scf.for %[[I:.+]] = %[[C0]] to %[[C128]] step %[[C1]]
+// CHECK: %[[FIRST:.+]] = arith.cmpi eq, %[[I]], %[[C0]] : index
+// CHECK: scf.if %[[FIRST]]
+// CHECK: scf.for %[[J:.+]] = %[[C0]] to %[[C128]] step %[[C1]]
+// CHECK-NEXT: %[[V:.+]] = memref.load %[[IN1]][%[[J]]]
+// CHECK-NEXT: memref.store %[[V]], %[[BUF1]][%[[J]]]
+// CHECK-NEXT: }
+// CHECK: scf.for
+// CHECK: %[[X1:.+]] = memref.load %[[BUF1]][%[[ROOT:.+]]]
+// CHECK: %[[X2:.+]] = memref.load %[[BUF2]][%[[ROOT]]]
+// CHECK: %[[W:.+]]:2 = scf.while
+// CHECK: %[[L1:.+]] = memref.load %[[BUF1]][%[[LEFT:.+]]]
+// CHECK: %[[L2:.+]] = memref.load %[[BUF2]][%[[LEFT]]]
+// CHECK: %[[R1:.+]] = memref.load %[[BUF1]][%[[RIGHT:.+]]]
+// CHECK: %[[R2:.+]] = memref.load %[[BUF2]][%[[RIGHT]]]
+// CHECK: %[[TAKE_RIGHT:.+]] = arith.cmpf ogt, %[[L1]], %[[R1]] : f32
+// CHECK: %[[N1:.+]] = arith.select %[[TAKE_RIGHT]], %[[R1]], %[[L1]] : f32
+// CHECK: %[[N2:.+]] = arith.select %[[TAKE_RIGHT]], %[[R2]], %[[L2]] : i32
+// CHECK: %[[MOVE:.+]] = arith.cmpf ogt, %[[X1]], %[[N1]] : f32
+// CHECK: scf.if %[[MOVE]]
+// CHECK: memref.store %[[N1]], %[[BUF1]][%[[HOLE:.+]]]
+// CHECK: memref.store %[[N2]], %[[BUF2]][%[[HOLE]]]
+// CHECK: memref.store %[[X1]], %[[BUF1]][%[[W]]#0]
+// CHECK: memref.store %[[X2]], %[[BUF2]][%[[W]]#0]
+
+// -----
+
+// A stable sort lowers to a binary insertion sort: find the position of each
+// element in the sorted prefix, move the elements behind it up by one, and
+// store it. An element only goes in front of another one if the comparator
+// holds for that order and not for the opposite one.
+func.func @sort_stable(%arg0: memref<128xf32>, %arg1: memref<128xi32>) {
+ iree_linalg_ext.sort dimension(0) is_stable(true)
ins(%arg0, %arg1 : memref<128xf32>, memref<128xi32>) outs(%arg0, %arg1 : memref<128xf32>, memref<128xi32>) {
^bb0(%arg2: f32, %arg3: f32, %arg4: i32, %arg5: i32):
%0 = arith.cmpf ogt, %arg2, %arg3 : f32
@@ -68,29 +169,46 @@
}
return
}
-// CHECK-LABEL: func.func @sort_multi
+// CHECK-LABEL: func.func @sort_stable
// CHECK-SAME: %[[BUF1:[a-zA-Z0-9]+]]
// CHECK-SAME: %[[BUF2:[a-zA-Z0-9]+]]
// CHECK-DAG: %[[C128:.+]] = arith.constant 128 : index
// CHECK-DAG: %[[C0:.+]] = arith.constant 0 : index
// CHECK-DAG: %[[C1:.+]] = arith.constant 1 : index
-// CHECK-DAG: %[[C127:.+]] = arith.constant 127 : index
-// CHECK: scf.for %[[ARG1:.+]] = %[[C0]] to %[[C128]] step %[[C1]]
-// CHECK: scf.for %[[ARG2:.+]] = %[[C0]] to %[[C127]] step %[[C1]]
-// CHECK: %[[T1:.+]] = arith.addi %[[ARG2]], %[[C1]] : index
-// CHECK: %[[V1:.+]] = memref.load %[[BUF1]][%[[ARG2]]]
-// CHECK: %[[V2:.+]] = memref.load %[[BUF1]][%[[T1]]]
-// CHECK: %[[V3:.+]] = memref.load %[[BUF2]][%[[ARG2]]]
-// CHECK: %[[V4:.+]] = memref.load %[[BUF2]][%[[T1]]]
-// CHECK: %[[COND:.+]] = arith.cmpf ogt, %[[V1]], %[[V2]] : f32
-// CHECK: %[[NEW1:.+]] = arith.select %[[COND]], %[[V1]], %[[V2]] : f32
-// CHECK: %[[NEW2:.+]] = arith.select %[[COND]], %[[V2]], %[[V1]] : f32
-// CHECK: memref.store %[[NEW1]], %[[BUF1]][%[[ARG2]]]
-// CHECK: memref.store %[[NEW2]], %[[BUF1]][%[[T1]]]
-// CHECK: %[[NEW3:.+]] = arith.select %[[COND]], %[[V3]], %[[V4]] : i32
-// CHECK: %[[NEW4:.+]] = arith.select %[[COND]], %[[V4]], %[[V3]] : i32
-// CHECK: memref.store %[[NEW3]], %[[BUF2]][%[[ARG2]]]
-// CHECK: memref.store %[[NEW4]], %[[BUF2]][%[[T1]]]
+// CHECK-DAG: %[[C2:.+]] = arith.constant 2 : index
+// CHECK-DAG: %[[TRUE:.+]] = arith.constant true
+// CHECK: scf.for %[[I:.+]] = %[[C0]] to %[[C128]] step %[[C1]]
+// CHECK: %[[FIRST:.+]] = arith.cmpi eq, %[[I]], %[[C0]] : index
+// CHECK: scf.if %[[FIRST]]
+// CHECK: scf.for %[[J:.+]] = %[[C1]] to %[[C128]] step %[[C1]]
+// CHECK: %[[X1:.+]] = memref.load %[[BUF1]][%[[J]]]
+// CHECK: %[[X2:.+]] = memref.load %[[BUF2]][%[[J]]]
+// CHECK: %[[SEARCH:.+]]:2 = scf.while (%[[LO:.+]] = %[[C0]], %[[HI:.+]] = %[[J]])
+// CHECK: %[[CONTINUE:.+]] = arith.cmpi slt, %[[LO]], %[[HI]] : index
+// CHECK: scf.condition(%[[CONTINUE]]) %[[LO]], %[[HI]]
+// CHECK: } do {
+// CHECK: ^bb0(%[[LO2:.+]]: index, %[[HI2:.+]]: index):
+// CHECK: %[[SUM:.+]] = arith.addi %[[LO2]], %[[HI2]] : index
+// CHECK: %[[MID:.+]] = arith.divsi %[[SUM]], %[[C2]] : index
+// CHECK: %[[M1:.+]] = memref.load %[[BUF1]][%[[MID]]]
+// CHECK: %[[BEFORE:.+]] = arith.cmpf ogt, %[[X1]], %[[M1]] : f32
+// CHECK: %[[AFTER:.+]] = arith.cmpf ogt, %[[M1]], %[[X1]] : f32
+// CHECK: %[[NOT_AFTER:.+]] = arith.xori %[[AFTER]], %[[TRUE]] : i1
+// CHECK: %[[STRICT:.+]] = arith.andi %[[BEFORE]], %[[NOT_AFTER]] : i1
+// CHECK: %[[MID1:.+]] = arith.addi %[[MID]], %[[C1]] : index
+// CHECK: %[[NEW_LO:.+]] = arith.select %[[STRICT]], %[[LO2]], %[[MID1]] : index
+// CHECK: %[[NEW_HI:.+]] = arith.select %[[STRICT]], %[[MID]], %[[HI2]] : index
+// CHECK: scf.yield %[[NEW_LO]], %[[NEW_HI]] : index, index
+// CHECK: %[[COUNT:.+]] = arith.subi %[[J]], %[[SEARCH]]#0 : index
+// CHECK: scf.for %[[K:.+]] = %[[C0]] to %[[COUNT]] step %[[C1]]
+// CHECK: %[[TO:.+]] = arith.subi %[[J]], %[[K]] : index
+// CHECK: %[[FROM:.+]] = arith.subi %[[TO]], %[[C1]] : index
+// CHECK: %[[V1:.+]] = memref.load %[[BUF1]][%[[FROM]]]
+// CHECK: %[[V2:.+]] = memref.load %[[BUF2]][%[[FROM]]]
+// CHECK: memref.store %[[V1]], %[[BUF1]][%[[TO]]]
+// CHECK: memref.store %[[V2]], %[[BUF2]][%[[TO]]]
+// CHECK: memref.store %[[X1]], %[[BUF1]][%[[SEARCH]]#0]
+// CHECK: memref.store %[[X2]], %[[BUF2]][%[[SEARCH]]#0]
// -----
diff --git a/tests/e2e/linalg_ext_ops/sort.mlir b/tests/e2e/linalg_ext_ops/sort.mlir
index f1add0b..06595e6 100644
--- a/tests/e2e/linalg_ext_ops/sort.mlir
+++ b/tests/e2e/linalg_ext_ops/sort.mlir
@@ -10,3 +10,150 @@
check.expect_eq_const(%0, dense<[[3, 6], [5, 7]]> : tensor<2x2xi32>) : tensor<2x2xi32>
return
}
+
+// Odd length with duplicate and negative keys, descending.
+func.func @sort1D_duplicates() {
+ %input = util.unfoldable_constant dense<[3.5, -1.0, 7.25, 0.0, 3.5, 12.0, -8.5, 2.0, 2.0, 9.0, -1.0, 5.5, 0.5, 7.25, -3.0, 1.0, 4.0]> : tensor<17xf32>
+ %empty = tensor.empty() : tensor<17xf32>
+ %0 = iree_linalg_ext.sort dimension(0)
+ ins(%input : tensor<17xf32>) outs(%empty : tensor<17xf32>) {
+ ^bb0(%arg2: f32, %arg3: f32):
+ %1 = arith.cmpf ogt, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<17xf32>
+ check.expect_eq_const(%0, dense<[12.0, 9.0, 7.25, 7.25, 5.5, 4.0, 3.5, 3.5, 2.0, 2.0, 1.0, 0.5, 0.0, -1.0, -1.0, -3.0, -8.5]> : tensor<17xf32>) : tensor<17xf32>
+ return
+}
+
+func.func @sort1D_single_element() {
+ %input = util.unfoldable_constant dense<[42]> : tensor<1xi32>
+ %empty = tensor.empty() : tensor<1xi32>
+ %0 = iree_linalg_ext.sort dimension(0)
+ ins(%input : tensor<1xi32>) outs(%empty : tensor<1xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32):
+ %1 = arith.cmpi slt, %arg2, %arg3 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<1xi32>
+ check.expect_eq_const(%0, dense<[42]> : tensor<1xi32>) : tensor<1xi32>
+ return
+}
+
+// Sorts each row along the inner dimension.
+func.func @sort2D_inner() {
+ %input = util.unfoldable_constant dense<[[4, -2, 9, 0, 7], [1, 1, -5, 3, 2], [8, 6, 6, -1, 0]]> : tensor<3x5xi32>
+ %empty = tensor.empty() : tensor<3x5xi32>
+ %0 = iree_linalg_ext.sort dimension(1)
+ ins(%input : tensor<3x5xi32>) outs(%empty : tensor<3x5xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32):
+ %1 = arith.cmpi slt, %arg2, %arg3 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<3x5xi32>
+ check.expect_eq_const(%0, dense<[[-2, 0, 4, 7, 9], [-5, 1, 1, 2, 3], [-1, 0, 6, 6, 8]]> : tensor<3x5xi32>) : tensor<3x5xi32>
+ return
+}
+
+// Argsort: the indices are moved together with the keys. The keys are
+// distinct, so the result does not depend on how ties are ordered.
+func.func @sort1D_keys_and_indices() {
+ %keys = util.unfoldable_constant dense<[0.5, -2.0, 8.0, 3.0, -7.5, 6.0, 1.0, 4.5, 2.5]> : tensor<9xf32>
+ %indices = util.unfoldable_constant dense<[0, 1, 2, 3, 4, 5, 6, 7, 8]> : tensor<9xi32>
+ %empty_keys = tensor.empty() : tensor<9xf32>
+ %empty_indices = tensor.empty() : tensor<9xi32>
+ %0:2 = iree_linalg_ext.sort dimension(0)
+ ins(%keys, %indices : tensor<9xf32>, tensor<9xi32>)
+ outs(%empty_keys, %empty_indices : tensor<9xf32>, tensor<9xi32>) {
+ ^bb0(%arg2: f32, %arg3: f32, %arg4: i32, %arg5: i32):
+ %1 = arith.cmpf ogt, %arg2, %arg3 : f32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<9xf32>, tensor<9xi32>
+ check.expect_eq_const(%0#0, dense<[8.0, 6.0, 4.5, 3.0, 2.5, 1.0, 0.5, -2.0, -7.5]> : tensor<9xf32>) : tensor<9xf32>
+ check.expect_eq_const(%0#1, dense<[2, 5, 7, 3, 8, 6, 0, 1, 4]> : tensor<9xi32>) : tensor<9xi32>
+ return
+}
+
+// Many equal keys with a comparator that orders them by their index, the form
+// frontends use to get the result of a stable sort.
+func.func @sort1D_ties_ordered_by_index() {
+ %keys = util.unfoldable_constant dense<[2, 1, 2, 2, 0, 1, 2, 0, 1, 1, 2, 0, 1]> : tensor<13xi32>
+ %indices = util.unfoldable_constant dense<[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]> : tensor<13xi32>
+ %empty_keys = tensor.empty() : tensor<13xi32>
+ %empty_indices = tensor.empty() : tensor<13xi32>
+ %0:2 = iree_linalg_ext.sort dimension(0)
+ ins(%keys, %indices : tensor<13xi32>, tensor<13xi32>)
+ outs(%empty_keys, %empty_indices : tensor<13xi32>, tensor<13xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32, %arg4: i32, %arg5: i32):
+ %before = arith.cmpi sge, %arg2, %arg3 : i32
+ %after = arith.cmpi sge, %arg3, %arg2 : i32
+ %ordered = arith.xori %before, %after : i1
+ %lower_index = arith.cmpi slt, %arg4, %arg5 : i32
+ %1 = arith.select %ordered, %before, %lower_index : i1
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<13xi32>, tensor<13xi32>
+ check.expect_eq_const(%0#0, dense<[2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0]> : tensor<13xi32>) : tensor<13xi32>
+ check.expect_eq_const(%0#1, dense<[0, 2, 3, 6, 10, 1, 5, 8, 9, 12, 4, 7, 11]> : tensor<13xi32>) : tensor<13xi32>
+ return
+}
+
+// A stable sort keeps equal keys in input order, here visible in the payload.
+// The comparator is strict: it is false for equal keys in both orders.
+func.func @sort1D_stable_strict_comparator() {
+ %keys = util.unfoldable_constant dense<[2, 1, 2, 2, 0, 1, 2, 0, 1, 1, 2, 0, 1]> : tensor<13xi32>
+ %payload = util.unfoldable_constant dense<[50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62]> : tensor<13xi32>
+ %empty_keys = tensor.empty() : tensor<13xi32>
+ %empty_payload = tensor.empty() : tensor<13xi32>
+ %0:2 = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%keys, %payload : tensor<13xi32>, tensor<13xi32>)
+ outs(%empty_keys, %empty_payload : tensor<13xi32>, tensor<13xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32, %arg4: i32, %arg5: i32):
+ %1 = arith.cmpi sgt, %arg2, %arg3 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<13xi32>, tensor<13xi32>
+ check.expect_eq_const(%0#0, dense<[2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0]> : tensor<13xi32>) : tensor<13xi32>
+ check.expect_eq_const(%0#1, dense<[50, 52, 53, 56, 60, 51, 55, 58, 59, 62, 54, 57, 61]> : tensor<13xi32>) : tensor<13xi32>
+ return
+}
+
+// As above with a non-strict comparator, which is true for equal keys in both
+// orders.
+func.func @sort1D_stable_non_strict_comparator() {
+ %keys = util.unfoldable_constant dense<[2, 1, 2, 2, 0, 1, 2, 0, 1, 1, 2, 0, 1]> : tensor<13xi32>
+ %payload = util.unfoldable_constant dense<[50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62]> : tensor<13xi32>
+ %empty_keys = tensor.empty() : tensor<13xi32>
+ %empty_payload = tensor.empty() : tensor<13xi32>
+ %0:2 = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%keys, %payload : tensor<13xi32>, tensor<13xi32>)
+ outs(%empty_keys, %empty_payload : tensor<13xi32>, tensor<13xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32, %arg4: i32, %arg5: i32):
+ %1 = arith.cmpi sge, %arg2, %arg3 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<13xi32>, tensor<13xi32>
+ check.expect_eq_const(%0#0, dense<[2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0]> : tensor<13xi32>) : tensor<13xi32>
+ check.expect_eq_const(%0#1, dense<[50, 52, 53, 56, 60, 51, 55, 58, 59, 62, 54, 57, 61]> : tensor<13xi32>) : tensor<13xi32>
+ return
+}
+
+// A stable sort whose second operand holds the positions of the elements.
+func.func @sort1D_stable_keys_and_positions() {
+ %keys = util.unfoldable_constant dense<[2, 1, 2, 2, 0, 1, 2, 0, 1, 1, 2, 0, 1]> : tensor<13xi32>
+ %empty_keys = tensor.empty() : tensor<13xi32>
+ %empty_positions = tensor.empty() : tensor<13xi32>
+ %positions = linalg.generic {
+ indexing_maps = [affine_map<(d0) -> (d0)>],
+ iterator_types = ["parallel"]}
+ outs(%empty_positions : tensor<13xi32>) {
+ ^bb0(%out: i32):
+ %i = linalg.index 0 : index
+ %i32 = arith.index_cast %i : index to i32
+ linalg.yield %i32 : i32
+ } -> tensor<13xi32>
+ %0:2 = iree_linalg_ext.sort dimension(0) is_stable(true)
+ ins(%keys, %positions : tensor<13xi32>, tensor<13xi32>)
+ outs(%empty_keys, %empty_positions : tensor<13xi32>, tensor<13xi32>) {
+ ^bb0(%arg2: i32, %arg3: i32, %arg4: i32, %arg5: i32):
+ %1 = arith.cmpi sge, %arg2, %arg3 : i32
+ iree_linalg_ext.yield %1 : i1
+ } -> tensor<13xi32>, tensor<13xi32>
+ check.expect_eq_const(%0#0, dense<[2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0]> : tensor<13xi32>) : tensor<13xi32>
+ check.expect_eq_const(%0#1, dense<[0, 2, 3, 6, 10, 1, 5, 8, 9, 12, 4, 7, 11]> : tensor<13xi32>) : tensor<13xi32>
+ return
+}