Commit Graph

849 Commits

Author SHA1 Message Date
xiaoleis-nv
8d6469b0e0 [mlir][vector] Add lower-vector-multi-reduction pass (#87333)
This MR adds the `lower-vector-multi-reduction` pass to lower the
vector.multi_reduction operation.

While the Transform Dialect includes an operation,
`transform.apply_patterns.vector.lower_multi_reduction`, intended for a
similar purpose, its utility is limited to projects that have adopted
the Transform Dialect. Recognizing that not all projects are equipped to
integrate this dialect, the proposed pass serves as a vital standalone
alternative. It ensures that projects solely dependent on the
traditional pass infrastructure can also benefit from the optimized
lowering of `multi_reduction` operation.

---------

Co-authored-by: Xiaolei Shi <xiaoleis@nvidia.com>
2024-04-09 10:04:25 -07:00
Matthias Springer
76435f2dca [mlir][SCF] ValueBoundsConstraintSet: Support scf.if (branches) (#87860)
This commit adds support for `scf.if` to `ValueBoundsConstraintSet`.

Example:
```
%0 = scf.if ... -> index {
  scf.yield %a : index
} else {
  scf.yield %b : index
}
```

The following constraints hold for %0:
* %0 >= min(%a, %b)
* %0 <= max(%a, %b)

Such constraints cannot be added to the constraint set; min/max is not
supported by `IntegerRelation`. However, if we know which one of %a and
%b is larger, we can add constraints for %0. E.g., if %a <= %b:
* %0 >= %a
* %0 <= %b

This commit required a few minor changes to the
`ValueBoundsConstraintSet` infrastructure, so that values can be
compared while we are still in the process of traversing the IR/adding
constraints.

Note: This is a re-upload of #85895, which was reverted. The bug that
caused the failure was fixed in #87859.
2024-04-06 13:04:49 +09:00
Mehdi Amini
8487e05967 Revert "[mlir][SCF] ValueBoundsConstraintSet: Support scf.if (branches) (#85895)"
This reverts commit 6b30ffef28.

gcc7 bot is broken
2024-04-05 03:00:35 -07:00
Matthias Springer
6b30ffef28 [mlir][SCF] ValueBoundsConstraintSet: Support scf.if (branches) (#85895)
This commit adds support for `scf.if` to `ValueBoundsConstraintSet`.

Example:
```
%0 = scf.if ... -> index {
  scf.yield %a : index
} else {
  scf.yield %b : index
}
```

The following constraints hold for %0:
* %0 >= min(%a, %b)
* %0 <= max(%a, %b)

Such constraints cannot be added to the constraint set; min/max is not
supported by `IntegerRelation`. However, if we know which one of %a and
%b is larger, we can add constraints for %0. E.g., if %a <= %b:
* %0 >= %a
* %0 <= %b

This commit required a few minor changes to the
`ValueBoundsConstraintSet` infrastructure, so that values can be
compared while we are still in the process of traversing the IR/adding
constraints.
2024-04-05 13:14:00 +09:00
Matthias Springer
5e4a44380e [mlir][Interfaces][NFC] ValueBoundsConstraintSet: Pass stop condition in the constructor (#86099)
This commit changes the API of `ValueBoundsConstraintSet`: the stop
condition is now passed to the constructor instead of `processWorklist`.
That makes it easier to add items to the worklist multiple times and
process them in a consistent manner. The current
`ValueBoundsConstraintSet` is passed as a reference to the stop
function, so that the stop function can be defined before the the
`ValueBoundsConstraintSet` is constructed.

This change is in preparation of adding support for branches.
2024-04-04 17:05:47 +09:00
Han-Chung Wang
ef5a710911 [mlir][vector] Skip 0D vectors in vector linearization. (#87577) 2024-04-03 17:00:56 -07:00
Kojo Acquah
66fed33db0 [mlir][vector] Update castAwayContractionLeadingOneDim to omit transposes solely on leading unit dims. (#85694)
Updates `castAwayContractionLeadingOneDim` to check for leading unit
dimensions before inserting `vector.transpose` ops.

Currently `castAwayContractionLeadingOneDim` removes all leading unit
dims based on the accumulator and transpose any subsequent operands to
match the accumulator indexing. This does not take into account if the
transpose is strictly necessary, for instance when given this
vector-matrix contract:
```mlir
  %result = vector.contract {indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d1, d2)>], iterator_types = ["parallel", "parallel", "parallel", "reduction"], kind = #vector.kind<add>} %lhs, %rhs, %acc : vector<1x1x8xi32>, vector<1x8x8xi32> into vector<1x8xi32>
```
Passing this through `castAwayContractionLeadingOneDim` pattern produces
the following:
```mlir
    %0 = vector.transpose %arg0, [1, 0, 2] : vector<1x1x8xi32> to vector<1x1x8xi32>
    %1 = vector.extract %0[0] : vector<1x8xi32> from vector<1x1x8xi32>
    %2 = vector.extract %arg2[0] : vector<8xi32> from vector<1x8xi32>
    %3 = vector.contract {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d2)>, affine_map<(d0, d1, d2) -> (d0, d1, d2)>, affine_map<(d0, d1, d2) -> (d1)>], iterator_types = ["parallel", "parallel", "reduction"], kind = #vector.kind<add>} %1, %arg1, %2 : vector<1x8xi32>, vector<1x8x8xi32> into vector<8xi32>
    %4 = vector.broadcast %3 : vector<8xi32> to vector<1x8xi32>
```
The `vector.transpose` introduced does not affect the underlying data
layout (effectively a no op), but it cannot be folded automatically.
This change avoids inserting transposes when only leading unit
dimensions are involved.

Fixes #85691
2024-04-03 19:27:01 -04:00
Jakub Kuderski
971b852546 [mlir][NFC] Simplify type checks with isa predicates (#87183)
For more context on isa predicates, see:
https://github.com/llvm/llvm-project/pull/83753.
2024-04-01 11:40:09 -04:00
Diego Caballero
13b3762608 [mlir][Vector] Fix crash in drop unit dims (#87104)
An `arith.select` may have a scalar condition and true/false vector values.
2024-03-29 14:15:30 -07:00
Andrzej Warzyński
d3aa92ed14 [mlir][vector] Add support for scalable vectors to VectorLinearize (#86786)
Adds support for scalable vectors to patterns defined in
VectorLineralize.cpp.

Linearization is disable in 2 notable cases:
  * vectors with more than 1 scalable dimension (we cannot represent
    vscale^2),
  * vectors initialised with arith.constant that's not a vector splat
    (such arith.constant Ops cannot be flattened).
2024-03-28 14:53:21 +00:00
Justin Fargnoli
35d55f2894 [NFC][mlir] Reorder declarePromisedInterface() operands (#86628)
Reorder the template operands of `declarePromisedInterface()` to match
`declarePromisedInterfaces()`.
2024-03-27 10:30:17 -07:00
Balaji V. Iyer
5f1f9cfaa4 [mlir][Vector] Fix an assertion on failing cast in vector-transfer-flatten-patterns (#86030)
When the result is not a vectorType, there is an assert. This patch will
do the check and bail when the result is not a VectorType.
2024-03-25 16:05:09 -05:00
Crefeda Rodrigues
465ea0bfa6 [mlir][vector] Propagate scalability in TransferWriteNonPermutationLowering (#85632)
Updates `extendVectorRank` so that scalability in patterns
that use it (in particular, `TransferWriteNonPermutationLowering`),
is correctly propagated.


Closed related previous PR
https://github.com/llvm/llvm-project/pull/85270

---------

Signed-off-by: Crefeda Rodrigues <crefeda.rodrigues@arm.com>
Co-authored-by: Benjamin Maxwell <macdue@dueutil.tech>
2024-03-22 10:08:03 +00:00
Andrzej Warzyński
5f1b2cffe5 [mlir][vector] Add support for masks in castAwayContractionLeadingOneDim (#81906)
Updates `castAwayContractionLeadingOneDim` to inherit from
`MaskableOpRewritePattern` so that this pattern can support masking.

Builds on top of #83827
2024-03-22 09:37:43 +00:00
Benjamin Maxwell
2861856baf [mlir][Vector] Add utility for computing scalable value bounds (#83876)
This adds a new API built with the `ValueBoundsConstraintSet` to compute
the bounds of possibly scalable quantities. It uses knowledge of the
range of vscale (which is defined by the target architecture), to solve
for the bound as either a constant or an expression in terms of vscale.

The result is an `AffineMap` that will always take at most one
parameter, vscale, and returns a single result, which is the bound of
`value`.

The API is defined as follows:

```c++
FailureOr<ConstantOrScalableBound>
vector::ScalableValueBoundsConstraintSet::computeScalableBound(
  Value value, std::optional<int64_t> dim,
  unsigned vscaleMin, unsigned vscaleMax,
  presburger::BoundType boundType, 
  bool closedUB = true,
  StopConditionFn stopCondition = nullptr);
```

Note: `ConstantOrScalableBound` is a thin wrapper over the `AffineMap`
with a utility for converting the bound to a single quantity (i.e. a
size and scalable flag).

We believe this API could prove useful downstream in IREE (which uses a
similar analysis to hoist allocas, which currently fails for scalable
vectors).
2024-03-21 14:18:56 +00:00
Oleksandr "Alex" Zinenko
5a9bdd85ee [mlir] split transform interfaces into a separate library (#85221)
Transform interfaces are implemented, direction or via extensions, in
libraries belonging to multiple other dialects. Those dialects don't
need to depend on the non-interface part of the transform dialect, which
includes the growing number of ops and transitive dependency footprint.

Split out the interfaces into a separate library. This in turn requires
flipping the dependency from the interface on the dialect that has crept
in because both co-existed in one library. The interface shouldn't
depend on the transform dialect either.

As a consequence of splitting, the capability of the interpreter to
automatically walk the payload IR to identify payload ops of a certain
kind based on the type used for the entry point symbol argument is
disabled. This is a good move by itself as it simplifies the interpreter
logic. This functionality can be trivially replaced by a
`transform.structured.match` operation.
2024-03-20 22:15:17 +01:00
Andrzej Warzyński
b7324b6a9c [mlir][vector] Adds pattern rewrite for maskable Ops (#83827)
Adds a generic pattern rewrite for maskable Ops, `MaskableOpRewritePattern`,
that will work for both masked and un-masked cases, e.g. for both:

* `vector.mask {vector.contract}` (masked), and
* `vector.contract` (not masked).

This helps to reduce code-duplication and standardise how we implement such
patterns.

Fixes #78787
2024-03-20 21:04:06 +00:00
Matthias Springer
53c4418753 [mlir][linalg, tosa] Fix memory leaks in integration tests (#85366)
Buffers are no longer deallocation by One-Shot Bufferize. This is now
done by a separate buffer deallocation pass.

Also fix a bug in the `vector.mask` folding, which was triggered by
`-buffer-deallocation-pipeline`, which runs the canonicalizer.
2024-03-16 12:23:44 +09:00
Justin Fargnoli
513cdb8222 [mlir] Declare promised interfaces for all dialects (#78368)
This PR adds promised interface declarations for all interfaces declared
in `InitAllDialects.h`.

Promised interfaces allow a dialect to declare that it will have an
implementation of a particular interface, crashing the program if one
isn't provided when the interface is used.
2024-03-15 20:23:20 -07:00
Andrzej Warzyński
c56bd7ab79 [mlir][linalg] Enable masked vectorisation for depthwise convolutions (#81625)
This patch adds support for masked vectorisation of depthwise 1D WC
convolutions,`linalg.depthwise_conv_1d_nwc_wc`. This is implemented by
adding support for masking.

Two major assumptions are made:
  * only the channel dimension can be dynamic/scalable (i.e. the
    trailing dim),
  * when specifying vector sizes to use in the vectoriser, only the size
    corresponding to the channel dim is effectively used (other dims are
    inferred from the context).

In terms of scalable vectorisation, this should be sufficient to cover
all practical cases (i.e. making arbitrary dim scalable wouldn't make
much sense). As for more generic cases with dynamic shapes (e.g. W or N
dims being dynamic), more work would be needed. In particular, one would
have to consider the filter and input/output tensors separately.
2024-03-14 20:19:46 +00:00
Han-Chung Wang
7c83d1bd61 [mlir][vector] Use inferRankReducedResultType for subview type inference. (#84395)
Fixes https://github.com/openxla/iree/issues/16475
2024-03-12 11:46:05 -07:00
Benjamin Maxwell
c4979c935f [mlir][VectorOps] Add fold vector.shuffle -> vector.interleave (#80968)
This folds fixed-size vector.shuffle ops that perform a 1-D interleave
to a vector.interleave operation.

For example:

```mlir
%0 = vector.shuffle %a, %b [0, 2, 1, 4] : vector<2xi32>, vector<2xi32>
```

folds to:

```mlir
%0 = vector.interleave %a, %b : vector<2xi32>
```

Depends on: #80967
2024-03-06 13:36:29 +00:00
Balaji V. Iyer
6f5c4f2eac [mlir][vector]Add Vector bitwidth target to Linearize Vectorizable and Constant Ops (#83314)
Added a new flag `targetVectorBitwidth` to capture bit-width input.
2024-03-04 19:17:51 -06:00
Diego Caballero
4623c114fb [mlir][Vector] Support vector.insert in bubbling bitcast patterns (#82843)
This PR is adds support for `vector.insert` to the patterns that bubble up and down `vector.bitcat` ops across `vector.extract/extract_slice/insert_slice` ops.
2024-02-28 08:15:47 -08:00
Quinn Dawkins
6067129fbe Revert "[mlir][vector] Add a pattern to fuse extract(constant_mask) (#81057)" (#83275)
This reverts commit 5cdb8c0c88.

This pattern is producing incorrect IR. For example,

```mlir
func.func @extract_subvector_from_constant_mask() -> vector<16xi1> {
  %mask = vector.constant_mask [2, 3] : vector<16x16xi1>
  %extract = vector.extract %mask[8] : vector<16xi1> from vector<16x16xi1>
  return %extract : vector<16xi1>
}
```

Canonicalizes to

```mlir
func.func @extract_subvector_from_constant_mask() -> vector<16xi1> {
  %0 = vector.constant_mask [3] : vector<16xi1>
  return %0 : vector<16xi1>
}
```

Where it should be a zero mask because the extraction index (8) is
greater than the constant mask size along that dim (2).
2024-02-28 10:52:57 -05:00
Quinn Dawkins
c2b952926f [mlir][vector] Fix n-d transfer write distribution (#83215)
Currently n-d transfer write distribution can be inconsistent with
distribution of reductions if a value has multiple users, one of which
is a transfer_write with a non-standard distribution map, and the other
of which is a vector.reduction.

We may want to consider removing the distribution map functionality in
the future for this reason.
2024-02-28 00:11:28 -05:00
Diego Caballero
9d0acb872a [mlir][Vector] Add support for trunci to narrow type emulation (#82565)
This PR add support for `arith.trunci` to vector narrow type emulation for iX -> i4 truncations, for X >= 8. For now, the pattern only works for 1D vectors and is based on `vector.shuffle` ops. We would need `vector.deinterleave` to add n-D vector support.
2024-02-27 15:27:31 -08:00
Hsiangkai Wang
5cdb8c0c88 [mlir][vector] Add a pattern to fuse extract(constant_mask) (#81057)
This pattern will rewrite
ExtractOp(ConstantMaskOp) -> ConstantMaskOp
or
ExtractOp(ConstantMaskOp) -> Constant
2024-02-26 19:00:15 +00:00
Diego Caballero
847048f497 [mlir][Vector] Fix bug in vector xfer op flattening transformation (#81964)
It looks like the affine map generated to compute the indices of the
collapsed dimensions used the wrong dim size. For indices `[idx0][idx1]`
we computed the collapsed index as `idx0*size0 + idx1` instead of
`idx0*size1 + idx1`. This led to correctness issues in convolution tests
when enabling this transformation internally.
2024-02-22 12:37:32 -08:00
Diego Caballero
386aa7b169 [mlir][Vector] Replace vector.shuffle with vector.interleave in vector narrow type emulation (#82550)
This PR replaces the generation of `vector.shuffle` with
`vector.interleave` in the i4 conversions in vector narrow type
emulation. The multi dimensional semantics of `vector.interleave` allow
us to enable these conversion emulations also for multi dimensional
vectors.
2024-02-21 22:52:02 -08:00
Diego Caballero
71441ed171 [mlir][Vector] Add vector bitwidth target to xfer op flattening (#81966)
This PR adds an optional bitwidth parameter to the vector xfer op
flattening transformation so that the flattening doesn't happen if the
trailing dimension of the read/writen vector is larger than this
bitwidth (i.e., we are already able to fill at least one vector register
with that size).
2024-02-21 09:22:48 -08:00
Benjamin Maxwell
a1a6860314 [mlir][VectorOps] Add unrolling for n-D vector.interleave ops (#80967)
This unrolls n-D vector.interleave ops like:

```mlir
vector.interleave %i, %j : vector<6x3xf32>
```

To a sequence of 1-D operations:
```mlir
%i_0 = vector.extract %i[0] 
%j_0 = vector.extract %j[0] 
%res_0 = vector.interleave %i_0, %j_0 : vector<3xf32>
vector.insert %res_0, %result[0] :
// ... repeated x6
```

The 1-D operations can then be directly lowered to LLVM.

Depends on: #80966
2024-02-20 14:33:33 +00:00
Andrzej Warzyński
9478bf0ce6 [mlir] Introduce trailingNDimsContiguous for MemRefs (#78247)
Extracts logic from `vector::isContiguousSlice` to check whether
the trailing dim of a memref are contiguous into a dedicated hook
in BuiitinTypes.{h|cpp}.

Follow-up for https://github.com/llvm/llvm-project/pull/76848.
2024-02-17 08:47:10 +00:00
Diego Caballero
d592c8ec8f Reapply "[mlir][vector] Drop inner unit dims for transfer ops on dynamic shapes." (#80712) (#81778)
This reverts commit b4c7152eb4.

Downstream regression due to another issue that this PR exposes. We have identified the work-items to fix the new issue here: https://github.com/openxla/iree/issues/16406

Co-authored-by: Han-Chung Wang <hanchung@google.com>
2024-02-14 11:38:52 -08:00
Mehdi Amini
89dc313af9 Apply clang-tidy fixes for llvm-qualified-auto in VectorUnroll.cpp (NFC) 2024-02-14 10:11:37 -08:00
Ivan Butygin
35ef3994bf [mlir][vector] ND vectors linearization pass (#81159)
Common backends (LLVM, SPIR-V) only supports 1D vectors, LLVM conversion
handles ND vectors (N >= 2) as `array<array<... vector>>` and SPIR-V
conversion doesn't handle them at all at the moment. Sometimes it's
preferable to treat multidim vectors as linearized 1D. Add pass to do
this. Only constants and simple elementwise ops are supported for now.

@krzysz00 I've extracted yours result type conversion code from
LegalizeToF32 and moved it to common place.

Also, add ConversionPattern class operating on traits.
2024-02-13 15:30:58 +03:00
Andrzej Warzyński
0d72f0beab [mlir][Vector] Fix "scalability" in CastAwayExtractStridedSliceLeadingOneDim (#81187)
Makes sure that "scalability" flags in the
`CastAwayExtractStridedSliceLeadingOneDim` pattern are correctly
updated.
2024-02-09 17:13:37 +00:00
Uday Bondhugula
fe8a62c463 [MLIR] Fix crash in AffineMap::replace for zero result maps (#80930)
Fix obvious bug in AffineMap::replace for the case of zero result maps.
Extend/complete inferExprsFromList to work with empty expression lists.
2024-02-08 19:16:29 +05:30
Han-Chung Wang
d193ac4f71 [mlir][vector] Drop inner unit dims for xWrite on dynamic shapes. (#80725)
This is part of
66347e516e

The regression in downstream projects is about transfer_read patterns,
which needs more investigation. Add the support for transfer_write for
now.
2024-02-05 20:03:24 -08:00
Han-Chung Wang
b4c7152eb4 Revert "[mlir][vector] Drop inner unit dims for transfer ops on dynamic shapes." (#80712)
Reverts llvm/llvm-project#79752 because it is causing regressions in
downstream projects.
2024-02-05 09:32:03 -08:00
Diego Caballero
8ba018d72a [mlir][Vector] Add support for sub-byte transpose emulation (#80110)
This PR adds patterns to convert a sub-byte vector transpose into a
sequence of instructions that perform the transpose on i8 vector
elements. Whereas this rewrite may not lead to the absolute peak
performance, it should ensure correctness when dealing with sub-byte
transposes.
2024-01-31 17:26:50 -08:00
Benjamin Maxwell
88610b7951 [mlir][vector] Disable transpose -> shuffle lowering for scalable vectors (#79979)
vector.shuffle is not supported for scalable vectors (outside of splats)
2024-01-31 09:21:44 +00:00
Jie Fu
8ca90b29ee [mlir] Remove unused variable 'byteBitwidth' in VectorEmulateNarrowType.cpp (NFC)
llvm-project/mlir/lib/Dialect/Vector/Transforms/VectorEmulateNarrowType.cpp:763:12:
error: unused variable 'byteBitwidth' [-Werror,-Wunused-variable]
  unsigned byteBitwidth = 8;
           ^
1 error generated.
2024-01-30 10:06:40 +08:00
Diego Caballero
a694104022 [mlir][Vector] Add patterns for efficient i4 -> i8 conversion emulation (#79494)
This PR adds new patterns to improve the generated vector code for the emulation of any conversion that have to go through an i4 -> i8 type extension (only signed extensions are supported for now). This will impact any i4 -> i8/i16/i32/i64 signed extensions as well as sitofp i4 -> f8/f16/f32/f64.

The asm code generated for the supported cases is significantly better after this PR for both x86 and aarch64.
2024-01-29 17:44:06 -08:00
Han-Chung Wang
66347e516e [mlir][vector] Drop inner unit dims for transfer ops on dynamic shapes. (#79752) 2024-01-29 00:30:19 -08:00
Andrzej Warzyński
9ddbcee25e [mlir][vector] Extend vector.{insert|extract}_strided_slice (#79052)
Extends `vector.insert_strided_slice` and `vector.insert_strided_slice`
to allow scalable input and output vectors. For scalable sizes, the
corresponding slice size has to match the corresponding dimension in the
output/input vector (insert/extract, respectively).

This is supported:
```mlir
vector.extract_strided_slice %1 {
  offsets = [0, 3, 0],
  sizes = [1, 1, 4],
  strides = [1, 1, 1] } : vector<1x4x[4]xi32> to vector<1x1x[4]xi32>
```

This is not supported:
```mlir
vector.extract_strided_slice %1 {
  offsets = [0, 3, 0],
  sizes = [1, 1, 2],
  strides = [1, 1, 1] } : vector<1x4x[4]xi32> to vector<1x1x[2]xi32>
```
2024-01-25 19:01:28 +00:00
Andrzej Warzyński
d50705ed5d [mlir][vector] Support scalable vec in TransferReadAfterWriteToBroadcast (#79162)
Makes `TransferReadAfterWriteToBroadcast` correctly propagate
scalability flags.
2024-01-24 08:18:08 +00:00
Andrzej Warzynski
75b0c913a5 [mlir][nfc] Update comments
1. Updates and clarifies a few comments related to hooks for
   vector.{insert|extract}_strided_slice.

2. For consistency with vector.insert_strided_slice, removes a TODO from
   vector.extract_strided_slice Op def. It's self-explenatory that
   adding support for non-unit strides is a "TODO".
2024-01-22 14:25:27 +00:00
Jerry Wu
dedc7d4d36 [mlir] Exclude masked ops in VectorDropLeadUnitDim (#76468)
Don't insert cast ops for ops in `vector.mask` region in
`VectorDropLeadUnitDim`.
2024-01-20 19:37:46 -05:00
Benjamin Chetioui
35121add2e [mlir][NFC] Remove unused variable. 2024-01-19 11:32:19 +00:00