Commit Graph

8190 Commits

Author SHA1 Message Date
Mogball 3131f80824 [mlir] Refactor LICM into a utility
LICM is refactored into a utility that is application on any region. The implementation is moved to Transform/Utils.
2022-04-15 22:07:01 +00:00
Arjun P ef8b2a7cea [MLIR][Presburger] addSymbolicCut: fix the integral symbols heuristic to match the docs
Previously this checked if the entire symbolic numerator was divisible by the
denominator, which is never the case when this function is called. Fixed this to
check only the non-const coefficients in the numerator, which was what was
intended and documented.

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123592
2022-04-15 20:34:06 +01:00
Thomas Raoux b4bcef05b7 [mlir][vector] Fix bug in extractFromBroadcast folding
extract was incorrectly folded when the source was coming from a
broadcast that was both adding new rank and broadcasting the inner
dimension.

Differential Revision: https://reviews.llvm.org/D123867
2022-04-15 19:21:45 +00:00
Arjun P 69c1a35488 [MLIR][Presburger][Simplex] moveRowUnknownToColumn: support the row sample value being zero
When the sample value is zero, everything is the same except that failure to
pivot does not imply emptiness. So, leave it to the user to mark as empty if
necessary, if they know the sample value is strictly negative. This is needed
for an upcoming symbolic lexmin heuristic.

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123604
2022-04-15 20:15:21 +01:00
William S. Moses 9a8bb4bc63 [NFC] Update comments 2022-04-15 14:33:13 -04:00
Mogball 3430ae1e7b [mlir] Update LICM to support Graph Regions
Changes the algorithm of LICM to support graph regions (no guarantee of topologically sorted order). Also fixes an issue where ops with recursive side effects and regions would not be hoisted if any nested ops used operands that were defined within the nested region.

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D122465
2022-04-15 17:30:27 +00:00
William S. Moses ed499ddcda [MLIR] Fix operation clone
Operation clone is currently faulty.

Suppose you have a block like as follows:

```
(%x0 : i32) {
   %x1 = f(%x0)
   return %x1
}
```

The test case we have is that we want to "unroll" this, in which we want to change this to compute `f(f(x0))` instead of just `f(x0)`. We do so by making a copy of the body at the end of the block and set the uses of the argument in the copy operations with the value returned from the original block.
This is implemented as follows:
1) map to the block arguments to the returned value (`map[x0] = x1`).
2) clone the body

Now for this small example, this works as intended and we get the following.

```
(%x0 : i32) {
   %x1 = f(%x0)
   %x2 = f(%x1)
   return %x2
}
```

This is because the current logic to clone `x1 = f(x0)` first looks up the arguments in the map (which finds `x0` maps to `x1` from the initialization), and then sets the map of the result to the cloned result (`map[x1] = x2`).

However, this fails if `x0` is not an argument to the op, but instead used inside the region, like below.

```
(%x0 : i32) {
   %x1 = f() {
      yield %x0
   }
   return %x1
}
```

This is because cloning an op currently first looks up the args (none), sets the map of the result (`map[%x1] = %x2`), and then clones the regions. This results in the following, which is clearly illegal:

```
(%x0 : i32) {
   %x1 = f() {
      yield %x0
   }
   %x2 = f() {
      yield %x2
   }
   return %x2
}
```

Diving deeper, this is partially due to the ordering (how this PR fixes it), as well as how region cloning works. Namely it will first clone with the mapping, and then it will remap all operands. Since the ordering above now has a map of `x0 -> x1` and `x1 -> x2`, we end up with the incorrect behavior here.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D122531
2022-04-15 13:09:13 -04:00
Alex Zinenko 6c5ae8e974 [mlir] Support opaque types in LLVM IR -> MLIR translation
LLVM IR is moving towards adoption of opaque pointer types. These require extra
information to be passed when constructing some operations, in particular GEP
and Alloca. Adapt the builders of said operations and modify the translation
code to handle both opaque and non-opaque pointers.

This incidentally adds the translation for Alloca alignment and fixes the translation
of struct-related GEP indices that must be constant.

Reviewed By: wsmoses

Differential Revision: https://reviews.llvm.org/D123792
2022-04-15 17:51:31 +02:00
Lei Zhang 4db65e279b [mlir][vector] Reorder elementwise(transpose)
Similar to the existing pattern for reodering cast(transpose),
this makes transpose following transpose and increases the chance
of embedding the transposition inside contraction op. Actually
cast ops are just special instances of elementwise ops.

Reviewed By: ThomasRaoux

Differential Revision: https://reviews.llvm.org/D123596
2022-04-15 09:05:35 -04:00
Mehdi Amini 7a80912dd8 Apply clang-tidy fixes for modernize-use-default-member-init in ControlFlowSinkUtils.cpp (NFC) 2022-04-15 08:01:04 +00:00
Chia-hung Duan 5232c5c5d4 [mlir] Fix verification order of nested ops.
In order to increase parallism, certain ops with regions and have the
IsIsolatedFromAbove trait will have their verification delayed. That
means the region verifier may access the invalid ops and may lead to a
crash.

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D122771
2022-04-15 04:41:10 +00:00
Thomas Raoux 59058c441a [mlir][vector] Add operations used for Vector distribution
Add vector op warp_execute_on_lane_0 that will be used to do incremental
vector distribution in order to target warp level vector programming for
architectures with GPU-like SIMT programming model.
The idea behing the op is discussed further on discourse:
https://discourse.llvm.org/t/vector-vector-distribution-large-vector-to-small-vector/1983/23

Differential Revision: https://reviews.llvm.org/D123703
2022-04-15 03:47:52 +00:00
Jacques Pienaar 35bd41916b [mlir] Add assert to fail with more info (NFC)
This would have assert before during tensor type construction with
opaque error, assert and fail earlier now.
2022-04-14 19:54:12 -07:00
Thomas Raoux 894a591cf6 [mlir][nvgpu] Move mma.sync and ldmatrix in nvgpu dialect
Move gpu operation mma.sync and ldmatrix in nvgpu as they are specific
to nvidia target.

Differential Revision: https://reviews.llvm.org/D123824
2022-04-14 23:44:52 +00:00
Mehdi Amini 72e2b4e7a7 Apply clang-tidy fixes for modernize-use-default-member-init in PDLLServer.cpp (NFC) 2022-04-14 22:59:14 +00:00
Mehdi Amini db6796dfa8 Apply clang-tidy fixes for modernize-use-default-member-init in SparseTensorUtils.cpp (NFC) 2022-04-14 22:59:14 +00:00
Thomas Raoux 4c564940a1 [mlir][nvgpu] Add NVGPU dialect (architectural specific gpu dialect)
This introduce a new dialect for vendro specific ptx operations. This
also adds the first operation ldmatrix as an example. More operations
will be added in follow up patches.
This new dialect is meant to be a bridge between GPU and Vector
dialectis and NVVM dialect.

This is based on the RFC proposed here:
https://discourse.llvm.org/t/rfc-add-nv-gpu-dialect-hw-specific-extension-of-gpu-dialect-for-nvidia-gpus/61466/8

Differential Revision: https://reviews.llvm.org/D123266
2022-04-14 16:33:46 +00:00
Lei Zhang e54236dfb5 [mlir][vector] Cast away leading one dims for insert ops
Reviewed By: ThomasRaoux

Differential Revision: https://reviews.llvm.org/D123621
2022-04-14 08:57:32 -04:00
Lei Zhang bc408afbfe [mlir][vector] Fold splat constant transpose
Reviewed By: ThomasRaoux

Differential Revision: https://reviews.llvm.org/D123595
2022-04-14 08:51:25 -04:00
Alex Zinenko d064c4801c [mlir] Introduce Transform dialect
This dialect provides operations that can be used to control transformation of
the IR using a different portion of the IR. It refers to the IR being
transformed as payload IR, and to the IR guiding the transformation as
transform IR.

The main use case for this dialect is orchestrating fine-grain transformations
on individual operations or sets thereof. For example, it may involve finding
loop-like operations with specific properties (e.g., large size) in the payload
IR, applying loop tiling to those and only those operations, and then applying
loop unrolling to the inner loops produced by the previous transformations. As
such, it is not intended as a replacement for the pass infrastructure, nor for
the pattern rewriting infrastructure. In the most common case, the transform IR
will be processed and applied to payload IR by a pass. Transformations
expressed by the transform dialect may be implemented using the pattern
infrastructure or any other relevant MLIR component.

This dialect is designed to be extensible, that is, clients of this dialect are
allowed to inject additional operations into this dialect using the newly
introduced in this patch `TransformDialectExtension` mechanism. This allows the
dialect to avoid a dependency on the implementation of the transformation as
well as to avoid introducing dialect-specific transform dialects.

See https://discourse.llvm.org/t/rfc-interfaces-and-dialects-for-precise-ir-transformation-control/60927.

Reviewed By: nicolasvasilache, Mogball, rriddle

Differential Revision: https://reviews.llvm.org/D123135
2022-04-14 13:48:45 +02:00
Alex Zinenko 09141f1adf [mlir] Split intrinsics out of LLVMOps.td
Move the operations that correspond to LLVM IR intrinsics in a separate .td
file. This makes it easier to maintain the intrinsics and decreases the compile
time of LLVMDialect.cpp by ~25%.

Depends On D123310

Reviewed By: wsmoses, jacquesguan

Differential Revision: https://reviews.llvm.org/D123315
2022-04-14 13:23:31 +02:00
Alex Zinenko 2366a43b3c [mlir] initial support for opaque pointers in the LLVM dialect
LLVM IR has introduced and is moving forward with the concept of opaque
pointers, i.e. pointer types that are not carrying around the pointee type.
Instead, memory-related operations indicate the type of the data being accessed
through the opaque pointer. Introduce the initial support for opaque pointers
in the LLVM dialect:

  - `LLVMPointerType` to support omitting the element type;
  - alloca/load/store/gep to support opaque pointers in their operands and
    results; this requires alloca and gep to store the element type as an
    attribute;
  - memory-related intrinsics to support opaque pointers in their operands;
  - translation to LLVM IR for the ops above is no longer using methods
    deprecated in LLVM API due to the introduction of opaque pointers.

Unlike LLVM IR, MLIR can afford to support both opaque and non-opaque pointers
at the same time and simplify the transition. Translation to LLVM IR of MLIR
that involves opaque pointers requires the LLVMContext to be configured to
always use opaque pointers.

Reviewed By: wsmoses

Differential Revision: https://reviews.llvm.org/D123310
2022-04-14 13:23:29 +02:00
Mehdi Amini 35f48edb91 Apply clang-tidy fixes for llvm-qualified-auto in VectorTransforms.cpp (NFC) 2022-04-14 09:42:37 +00:00
Mehdi Amini 2d06420879 Apply clang-tidy fixes for performance-for-range-copy in SCF.cpp (NFC) 2022-04-14 09:42:36 +00:00
Arnab Dutta 392d55c1e2 [MLIR][GPU] Add canonicalization patterns for folding simple gpu.wait ops.
* Fold away redundant %t = gpu.wait async + gpu.wait [%t] pairs.

* Fold away %t = gpu.wait async ... ops when %t has no uses.

* Fold away gpu.wait [] ops.

* In case of %t1 = gpu.wait async [%t0], replace all uses of %t1
  with %t0.

Differential Revision: https://reviews.llvm.org/D121878
2022-04-14 12:30:55 +05:30
Stella Laurenzo 61352a580a [mlir] Introduce ml_program dialect.
Differential Revision: https://reviews.llvm.org/D120203
2022-04-13 21:38:14 -07:00
Arjun P 094ad0667c [MLIR][Presburger] change some `push_back`s to `emplace_back`s 2022-04-14 04:27:21 +01:00
Arjun P ef95a6e827 [MLIR][Presburger] change some post-increments/decrements to pre-increments/decrements 2022-04-14 04:26:29 +01:00
Mehdi Amini 93b23c8439 Apply clang-tidy fixes for llvm-else-after-return in SCF.cpp (NFC) 2022-04-13 23:14:44 +00:00
Mehdi Amini f19e90bc1f Apply clang-tidy fixes for readability-identifier-naming in OpenMPDialect.cpp (NFC) 2022-04-13 23:14:44 +00:00
Christopher Bate 77d2c815f5 [MLIR][GPU] Add GPU ops nvvm.mma.sync, nvvm.mma.ldmatrix, lane_id
This change adds three new operations to the GPU dialect: gpu.mma.sync,
gpu.mma.ldmatrix, and gpu.lane_id. The former two are meant to target
the lower level nvvm.mma.sync and nvvm.ldmatrix instructions, respectively.
Lowerings are added for the new GPU operations for conversion to
NVVM.

Reviewed By: ThomasRaoux

Differential Revision: https://reviews.llvm.org/D123647
2022-04-13 22:50:07 +00:00
Thomas Raoux 5b1b7108c8 [mlir][vector] Add unrolling pattern for TransposeOp
Support unrolling for vector.transpose following the same interface as
other vector unrolling ops.

Differential Revision: https://reviews.llvm.org/D123688
2022-04-13 19:44:16 +00:00
Mogball 60e34f8ddd [mlir][ods] Remove StrEnumAttr
StrEnumAttr has been deprecated in favour of EnumAttr, a solution based on AttrDef (https://reviews.llvm.org/D115181). This patch removes StrEnumAttr, along with all the custom ODS logic required to handle it.

See https://discourse.llvm.org/t/psa-stop-using-strenumattr-do-use-enumattr/5710 on how to transition to EnumAttr. In short,

```
// Before
def MyEnumAttr : StrEnumAttr<"MyEnum", "", [
  StrEnumAttrCase<"A">,
  StrEnumAttrCase<"B">
]>;

// After (pick an integer enum of your choice)
def MyEnum : I32EnumAttr<"MyEnum", "", [
  I32EnumAttrCase<"A", 0>,
  I32EnumAttrCase<"B", 1>
]> {
  // Don't generate a C++ class! We want to use the AttrDef
  let genSpecializedAttr = 0;
}
// Define the AttrDef
def MyEnum : EnumAttr<MyDialect, MyEnum, "my_enum">;
```

Reviewed By: rriddle, jpienaar

Differential Revision: https://reviews.llvm.org/D120834
2022-04-13 17:49:02 +00:00
Jacques Pienaar 5a236e69f2 [mlir][pdll] Include string in PDLLServer.h 2022-04-13 10:31:06 -07:00
Jacques Pienaar a9d7598ef8 [mlir][pdll] Rename extra dir flag
Not sure why this is overlapping, need to repro locally, but just rename
to something more explicit instead.
2022-04-13 10:00:10 -07:00
Jacques Pienaar aa9da11f5d [mlir][pdll] Add extra-dirs for LSP includes.
Enable specifying additional include directories to search. This is
consistent with what one can do with clangd (although there it is more
general compilation options) and Python LSP. We would in general expect
these to be provided by compilation database equivalent.

Differential Revision: https://reviews.llvm.org/D123474
2022-04-13 09:41:45 -07:00
Shraiysh Vaishay f0ba32d666 [mlir][LLVM-IR] Added support for global variable attributes
This patch adds thread_local to llvm.mlir.global and adds translation for dso_local and addr_space to and from LLVM IR.

Reviewed By: Mogball

Differential Revision: https://reviews.llvm.org/D123412
2022-04-13 08:31:01 +05:30
jacquesguan 605fc89a61 [mlir][Arithmetic] Add common constant folder function for type cast ops.
This revision replaces current type cast constant folder with a new common type cast constant folder function template.
It will cover all former folder and support fold the constant splat and vector.

Differential Revision: https://reviews.llvm.org/D123489
2022-04-13 02:11:59 +00:00
Mahesh Ravishankar b40e901333 [mlir][Linalg] Allow collapsing subset of the reassociations when fusing by collapsing.
This change generalizes the fusion of `tensor.expand_shape` ->
`linalg.generic` op by collapsing to handle cases where only a subset
of the reassociations specified in the `tensor.expand_shape` are valid
to be collapsed.
The method that does the collapsing is refactored to allow it to be a
generic utility when required.

Reviewed By: gysit

Differential Revision: https://reviews.llvm.org/D123153
2022-04-12 18:56:32 +00:00
Shraiysh Vaishay b18e82186f [mlir][OpenMP] Added omp.task
This patch adds tasking construct according to Section 2.10.1 of OpenMP 5.0

Reviewed By: peixin, kiranchandramohan, abidmalikwaterloo

Differential Revision: https://reviews.llvm.org/D123575
2022-04-12 23:55:47 +05:30
Groverkss 20aedb148b [MLIR][Presburger] Remove inheritance from PresburgerSpace in IntegerRelation, PresburgerRelation and PWMAFunction
This patch removes inheritence from PresburgerSpace in IntegerRelation and
instead makes it a member of these classes.

This is required for three reasons:
  - It prevents implicit casting to PresburgerSpace.
  - Not all functions of PresburgerSpace need to be exposed by the deriving classes.
  - IntegerRelation and IntegerPolyhedron are defined in a PresburgerSpace. It
    makes more sense for the space to be a member instead of them inheriting from
    a space.

Reviewed By: arjunp, ftynse

Differential Revision: https://reviews.llvm.org/D123585
2022-04-12 22:48:52 +05:30
Arjun P 0ac213667d [MLIR][Presburger] normalizeDiv: add assert that denom > 0 2022-04-12 13:06:53 +01:00
jacquesguan 83bd4fe2e8 [mlir][Math] Replace some constant folder functions with common folder functions.
Differential Revision: https://reviews.llvm.org/D123485
2022-04-12 11:34:47 +00:00
Arjun P 4aeb2a57f4 [MLIR][Presburger][Simplex] addSymbolicCut: don't add symbol div if denom is 1
This is unncessary, so we remove it as an optimization.

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123540
2022-04-12 12:27:27 +01:00
Andrzej Warzynski fb16ed258c [mlir] Prefix pass manager options with `mlir-`
With this change, there's going to be a clear distinction between LLVM
and MLIR pass maanger options (e.g. `-mlir-print-after-all` vs
`-print-after-all`). This change is desirable from the point of view of
projects that depend on both LLVM and MLIR, e.g. Flang.

For consistency, all pass manager options in MLIR are prefixed with
`mlir-`, even options that don't have equivalents in LLVM .

Differential Revision: https://reviews.llvm.org/D123495
2022-04-12 09:32:44 +00:00
Matthias Springer fa087b4352 [mlir][scf][bufferize][NFC] Lookup buffer using helper function
Lookup iter_arg buffers using `lookupBuffer` instead of always creating a new `ToMemrefOp`. Also cast all yielded buffers (if necessary), regardless of whether they are an equivalent buffer or a new allocation.

Note: This should have been part of D123369.

Differential Revision: https://reviews.llvm.org/D123383
2022-04-12 18:09:30 +09:00
Mehdi Amini eeef40a6cd Apply clang-tidy fixes for performance-unnecessary-value-param in LLVMDialect.cpp (NFC) 2022-04-12 07:47:04 +00:00
Mehdi Amini e188ad8bf0 Apply clang-tidy fixes for performance-unnecessary-value-param in SplitReduction.cpp (NFC) 2022-04-12 07:47:04 +00:00
Mehdi Amini 30846d2916 Guard copy of std::function to llvm::function_ref (fix crash)
This is a footgun: assigning a null std::function to a function_ref
does not yield a null function_ref...
2022-04-12 07:44:04 +00:00
Mehdi Amini 07db69effe Use std::function instead of function_ref in MLIR JitRunner
This fixes an ASAN failure.
2022-04-12 07:28:19 +00:00
Mehdi Amini 6b7e6ea489 Revert "Fix CUDA runtime wrapper for GPU mem alloc/free to async"
This reverts commit b4117fede2.
This broke one of the MLIR bot, a test is failing.
2022-04-12 06:50:27 +00:00
Mehdi Amini 3c9e09036c Apply clang-tidy fixes for readability-identifier-naming in LinalgOps.cpp (NFC) 2022-04-12 05:30:01 +00:00
Mehdi Amini 47286e17ed Apply clang-tidy fixes for performance-for-range-copy in LinalgOps.cpp (NFC) 2022-04-12 05:30:01 +00:00
Mehdi Amini 0149a437e2 Apply clang-tidy fixes for llvm-qualified-auto in LinalgOps.cpp (NFC) 2022-04-12 04:39:58 +00:00
Mehdi Amini bf62a4b9c5 Apply clang-tidy fixes for performance-move-const-arg in ArithmeticOps.cpp (NFC) 2022-04-12 04:39:57 +00:00
Uday Bondhugula 56245cc18c [MLIR] NFC. Address clang-tidy warning in AffineOps.cpp
NFC. Address clang-tidy warning in AffineOps.cpp.
2022-04-12 09:58:29 +05:30
Uday Bondhugula b4117fede2 Fix CUDA runtime wrapper for GPU mem alloc/free to async
Switch CUDA runtime wrapper for GPU mem alloc/free to async. The
semantics of the GPU dialect ops (gpu.alloc/dealloc) and the wrappers it
lowered to (gpu-to-llvm) was for the async versions -- however, this was
being incorrectly mapped to cuMemAlloc/cuMemFree instead of
cuMemAllocAsync/cuMemFreeAsync.

Reviewed By: csigg

Differential Revision: https://reviews.llvm.org/D123482
2022-04-12 09:04:02 +05:30
Peixin-Qiao 139c5b8a96 [MLIR][OpenMP] Add support for threadprivate directive
This supports the threadprivate directive in OpenMP dialect following
the OpenMP 5.1 [2.21.2] standard. Also lowering to LLVM IR using OpenMP
IRBduiler.

Reviewed By: kiranchandramohan, shraiysh, arnamoy10

Differential Revision: https://reviews.llvm.org/D123350
2022-04-12 10:15:15 +08:00
jacquesguan 920527f4b5 [mlir][NFC] Remove some redundant code.
Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D123487
2022-04-12 02:10:04 +00:00
Eugene Zhulenev b35b9e307f [mlir] Add msan memory unpoisoning macros to mlir ExecutionEngine
Adding annotations on as-needed bases, currently only for memrefCopy, but in general all C API functions that take pointers to memory allocated/initialized inside the jit-compiled code must be annotated, to be able to run with msan.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D123557
2022-04-11 18:58:28 -07:00
Arthur Eubanks 7ccd026cf2 Reland [mlir] Remove uses of LLVM's legacy pass manager
Use the new pass manager.

This also removes the ability to run arbitrary sets of passes. Not sure if this functionality is used, but it doesn't seem to be tested.

No need to initialize passes outside of constructing the PassBuilder with the new pass manager.

Reland: Fixed custom calls to `-lower-matrix-intrinsics` in integration tests by replacing them with `-O0 -enable-matrix`.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D123425
2022-04-11 16:53:32 -07:00
Arthur Eubanks c3efb75061 Revert "[mlir] Remove uses of LLVM's legacy pass manager"
This reverts commit b0f7f6f78d.

Causes test failures: https://lab.llvm.org/buildbot#builders/61/builds/24879
2022-04-11 16:45:19 -07:00
Mahesh Ravishankar 2291705d2b [mlir][Linalg] Split `populateElementwiseOpsFusionPatterns`.
The method to add elementwise ops fusion patterns pulls in many other
patterns by default. The patterns to pull in along with the
elementwise op fusion should be upto the caller. Split the method to
pull in just the elementwise ops fusion pattern. Other cleanup changes
include
- Move the pattern for constant folding of generic ops (currently only
  constant folds transpose) into a separate file, cause it is not
  related to fusion
- Drop the uber LinalgElementwiseFusionOptions. With the
  populateElementwiseOpsFusionPatterns being split, this has no
  utility now.
- Drop defaults for the control function.
- Fusion of splat constants with generic ops doesnt need a control
  function. It is always good to do.

Differential Revision: https://reviews.llvm.org/D123236
2022-04-11 23:37:23 +00:00
Arthur Eubanks b0f7f6f78d [mlir] Remove uses of LLVM's legacy pass manager
Use the new pass manager.

This also removes the ability to run arbitrary sets of passes. Not sure if this functionality is used, but it doesn't seem to be tested.

No need to initialize passes outside of constructing the PassBuilder with the new pass manager.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D123425
2022-04-11 16:18:45 -07:00
Mehdi Amini f74569b37c Apply clang-tidy fixes for llvm-qualified-auto in AffineOps.cpp (NFC) 2022-04-11 23:14:47 +00:00
Mehdi Amini ceefc26145 Apply clang-tidy fixes for llvm-qualified-auto in ConvertShapeConstraints.cpp (NFC) 2022-04-11 23:14:46 +00:00
Arjun P aafb428237 [MLIR][Presburger][Simplex] symbolic lexmin: add some normalization heuristics
Normalize some of the division and inequality expressions used,
which can improve performance. Also deduplicate some of the
normalization functionality throughout the Presburger library.

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123314
2022-04-11 20:46:30 +01:00
Arjun P a2b212bafc [MLIR][Presburger] subtract: fix bug in the non-recursive implementation
When making the subtract implementation non-recursive, tail calls were
implemented by incrementing the level but not pushing a frame, and returning
was implemented as returning to the level corresponding to the number of frames in the stack.

This is incorrect, as there could be a case where we tail-recurse at `level`,
and then recurse at `level + 1`, pushing a frame. However, because the previous
frame was missing, this new frame would be interpreted as corresponding to
`level` and not `level + 1`. Fix this by removing the special handling of tail
calls and just doing them as normal recursion, as this is the simplest correct
implementation and handling them specifically would be a premature optimization.

The impact of this bug is only on performance as this can only lead to
unnecessary subtractions of the same disjuncts multiples times. As subtraction
is idempotent, and rationally empty disjuncts are always discarded, this
does not affect the output, so this patch does not include a regression test.
(This also does not affect termination.)

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123327
2022-04-11 20:45:29 +01:00
gysit 973dbe20f6 [mlir][tensor] Add pattern to fold ExtractSliceOp, PadOp chains.
The pattern folds chains of tensor::ExtractSliceOp, tensor::PadOp pairs if they pad different dimensions. Repeated tiling and padding of the tiled dimensions may introduce such chains. This canonicalization pattern folds these chains to a single tensor::ExtractSliceOp, tensor::PadOp pair that pads all dimensions at once, which simplifies vectorization and bufferization.

Example:
```mlir
   %0 = tensor.extract_slice %input[16, 0] [%sz0, 64] [1, 1]
       : tensor<64x64xf32> to tensor<?x64xf32>
   %1 = tensor.pad %0 low[0, 0] high[%pw0, 0] { ...
     } : tensor<?x64xf32> to tensor<8x64xf32>
   %2 = tensor.extract_slice %1[0, 4] [8, %sz1] [1, 1]
        : tensor<8x64xf32> to tensor<8x?xf32>
   %res = tensor.pad %2 nofold low[0, 0] high[0, %pw1] { ...
     } : tensor<8x?xf32> to tensor<8x4xf32>
```
folds into:
 ```mlir
   %0 = tensor.extract_slice %input[16, 4] [%sz0, %sz1] [1, 1]
        : tensor<64x64xf32> to tensor<?x?xf32>
   %res = tensor.pad %0 nofold low[0, 0] high[%pw0, %pw1] { ...
     } : tensor<?x?xf32> to tensor<8x4xf32>
 ```

Reviewed By: nicolasvasilache, hanchung

Differential Revision: https://reviews.llvm.org/D122722
2022-04-11 14:28:59 +00:00
gysit 39b9336474 [mlir][vector] Swap ExtractSliceOp(TransferWriteOp).
Rewrite tensor::ExtractSliceOp(vector::TransferWriteOp) to vector::TransferWriteOp(tensor::ExtractSliceOp) if the full slice is overwritten and inserted into another tensor. After this rewrite, the operations bufferize in-place since all of them work on the same %iter_arg slice.

For example:
```mlir
  %0 = vector.transfer_write %vec, %init_tensor[%c0, %c0]
       : vector<8x16xf32>, tensor<8x16xf32>
  %1 = tensor.extract_slice %0[0, 0] [%sz0, %sz1] [1, 1]
       : tensor<8x16xf32> to tensor<?x?xf32>
  %r = tensor.insert_slice %1 into %iter_arg[%iv0, %iv1] [%sz0, %sz1] [1, 1]
       : tensor<?x?xf32> into tensor<27x37xf32>
```
folds to
```mlir
  %0 = tensor.extract_slice %iter_arg[%iv0, %iv1] [%sz0, %sz1] [1, 1]
       : tensor<27x37xf32> to tensor<?x?xf32>
  %1 = vector.transfer_write %vec, %0[%c0, %c0]
       : vector<8x16xf32>, tensor<?x?xf32>
  %r = tensor.insert_slice %1 into %iter_arg[%iv0, %iv1] [%sz0, %sz1] [1, 1]
       : tensor<?x?xf32> into tensor<27x37xf32>

Reviewed By: nicolasvasilache, hanchung

Differential Revision: https://reviews.llvm.org/D123190
2022-04-11 10:28:53 +00:00
wren romano 8d8b566f0c [mlir][sparse] Moving <P,I,V>-invariant parts of SparseTensorStorage to base
This reorganization helps to clean up the changes needed for D122060.

Work towards fixing: https://github.com/llvm/llvm-project/issues/51652

Depends On D122625

Reviewed By: aartbik

Differential Revision: https://reviews.llvm.org/D122928
2022-04-08 11:44:17 -07:00
Matthias Springer d7a9bf9143 [mlir][tensor] Fix verifier and bufferization of collapse_shape
Insert a buffer copy unless the dims are guaranteed to be collapsible. In the verifier, accept collapses unless they are guaranteed to be non-collapsible.

Differential Revision: https://reviews.llvm.org/D123316
2022-04-08 18:20:40 +09:00
Matthias Springer d2608adf49 [mlir][bufferize] Do not insert useless casts for newly allocated buffers
Differential Revision: https://reviews.llvm.org/D123369
2022-04-08 18:12:02 +09:00
Matthias Springer 8b09141909 [mlir][arith][bufferize] Fix tensors with different layouts after bufferization
Insert a cast if the two tensors with identical layout (that are passed to `arith.select`) have different layout maps after bufferization.

Differential Revision: https://reviews.llvm.org/D123321
2022-04-08 18:11:10 +09:00
jacquesguan e79b7f501c [mlir][Vector] Fold extractelement splat.
This revision supports to fold vector.extractelement (splat X) -> X.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D122960
2022-04-08 07:54:37 +00:00
jacquesguan 088d38890c [mlir][Arithmetic] Add constant folder for negf.
Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D123293
2022-04-08 07:36:29 +00:00
River Riddle 36d3efea15 [mlir][NFC] Drop a few unnecessary includes from Pass.h 2022-04-07 23:42:47 -07:00
Markus Böck 0c789db541 [mlir] Add support for operation-produced successor arguments in BranchOpInterface
This patch revamps the BranchOpInterface a bit and allows a proper implementation of what was previously `getMutableSuccessorOperands` for operations, which internally produce arguments to some of the block arguments. A motivating example for this would be an invoke op with a error handling path:
```
invoke %function(%0)
  label ^success ^error(%1 : i32)

^error(%e: !error, %arg0 : i32):
  ...
```
The advantages of this are that any users of `BranchOpInterface` can still argue over remaining block argument operands (such as `%1` in the example above), as well as make use of the modifying capabilities to add more operands, erase an operand etc.

The way this patch implements that functionality is via a new class called `SuccessorOperands`, which is now returned by `getSuccessorOperands`. It basically contains an `unsigned` denoting how many operator produced operands exist, as well as a `MutableOperandRange`, which are the usual forwarded operands we are used to. The produced operands are assumed to the first few block arguments, followed by the forwarded operands afterwards. The role of `SuccessorOperands` is to provide various utility functions to modify and query the successor arguments from a `BranchOpInterface`.

Differential Revision: https://reviews.llvm.org/D123062
2022-04-08 08:28:16 +02:00
Stella Laurenzo 497f87bb7b NFC: Silence unused function 'scaleAndAdd' in release build.
Differential Revision: https://reviews.llvm.org/D123354
2022-04-07 21:19:19 -07:00
River Riddle af371f9f98 Reland [GreedPatternRewriter] Preprocess constants while building worklist when not processing top down
Reland Note: Adds a fix to properly mark a commutative operation as folded if we change the order
             of its operands. This was uncovered by the fact that we no longer re-process constants.

This avoids accidentally reversing the order of constants during successive
application, e.g. when running the canonicalizer. This helps reduce the number
of iterations, and also avoids unnecessary changes to input IR.

Fixes #51892

Differential Revision: https://reviews.llvm.org/D122692
2022-04-07 11:31:42 -07:00
natashaknk fac9f45e05 [tosa][mlir] Add dynamic width/height support for depthwise convolution in tosa-to-linalg
In addition, fixed a small bug with padding incorrectly inferring output shape for dynaic inputs in convolution

Reviewed By: jpienaar

Differential Revision: https://reviews.llvm.org/D121872
2022-04-07 10:50:06 -07:00
Lei Zhang 7becf0f6cd [mlir][vector] Fold extract(broadcast) of same rank
This case is handled in neither the folding or canonicalization
patterns. The folding pattern cannot generate new broadcast ops,
so it should be handled by the canonicalization pattern.

Reviewed By: ThomasRaoux

Differential Revision: https://reviews.llvm.org/D123307
2022-04-07 12:59:54 -04:00
Arjun P 00b293e83f [MLIR][Presburger] refactor subtraction to be non-recursive
Subtraction was previously implemented recursively. This refactors it to be
non-recursive to avoid issues with potential stack overflows.

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123248
2022-04-07 15:20:19 +01:00
Valentin Clement 02da964350
[mlir][CSE] Remove duplicated operations with MemRead side-effect
This patch enhances the CSE pass to deal with simple cases of duplicated
operations with MemoryEffects.

It allows the CSE pass to remove safely duplicate operations with the
MemoryEffects::Read that have no other side-effecting operations in
between. Other MemoryEffects::Read operation are allowed.

The use case is pretty simple so far so we can build on top of it to add
more features.

This patch is also meant to avoid a dedicated CSE pass in FIR and was
brought together afetr discussion on https://reviews.llvm.org/D112711.
It does not currently cover the full range of use cases described in
https://reviews.llvm.org/D112711 but the idea is to gradually enhance
the MLIR CSE pass to handle common use cases that can be used by
other dialects.

This patch takes advantage of the new CSE capabilities in Fir.

Reviewed By: mehdi_amini, rriddle, schweitz

Differential Revision: https://reviews.llvm.org/D122801
2022-04-07 10:08:55 +02:00
River Riddle 5520e07f46 [mlir:Parser][NFC] Replace SSAUseInfo with OpAsmParser::UnresolvedOperand
These are functionally identical, and merging the two removes the number of
redundant conversions within the parser.
2022-04-06 18:25:08 -07:00
River Riddle ea64828a10 [mlir:PDL] Expand how native constraint/rewrite functions can be defined
This commit refactors the expected form of native constraint and rewrite
functions, and greatly reduces the necessary user complexity required when
defining a native function. Namely, this commit adds in automatic processing
of the necessary PDLValue glue code, and allows for users to define
constraint/rewrite functions using the C++ types that they actually want to
use.

As an example, lets see a simple example rewrite defined today:

```
static void rewriteFn(PatternRewriter &rewriter, PDLResultList &results,
                      ArrayRef<PDLValue> args) {
  ValueRange operandValues = args[0].cast<ValueRange>();
  TypeRange typeValues = args[1].cast<TypeRange>();
  ...
  // Create an operation at some point and pass it back to PDL.
  Operation *op = rewriter.create<SomeOp>(...);
  results.push_back(op);
}
```

After this commit, that same rewrite could be defined as:

```
static Operation *rewriteFn(PatternRewriter &rewriter ValueRange operandValues,
                            TypeRange typeValues) {
  ...
  // Create an operation at some point and pass it back to PDL.
  return rewriter.create<SomeOp>(...);
}
```

Differential Revision: https://reviews.llvm.org/D122086
2022-04-06 17:41:59 -07:00
Aart Bik 0b55f94d2b [mlir][sparse] replace stack-based access pattern with dyn-alloc
Rationale:
Allocating the temporary buffers for access pattern expansion on the stack
(using alloca) is a bit too agressive, since it easily runs out of stack space
for large enveloping tensor dimensions. This revision changes the dynamic
allocation of these buffers with explicit alloc/dealloc pairs.

Reviewed By: bixia, wrengr

Differential Revision: https://reviews.llvm.org/D123253
2022-04-06 17:10:43 -07:00
John Demme 8d8738f6fe [MLIR] Add block detach func to CAPI and use it in Python bindings
Adds `mlirBlockDetach` to the CAPI to remove a block from its parent
region. Use it in the Python bindings to implement
`Block.append_to(region)`.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D123165
2022-04-06 13:11:56 -07:00
Matthias Springer 7e6de86ff6 [mlir][bufferize][NFC] Remove caller map and ordered func list from FuncAnalysisState
These can be local variables. No need to store them in the struct.

Differential Revision: https://reviews.llvm.org/D123210
2022-04-07 00:49:24 +09:00
Matthias Springer cb186bc508 [mlir][bufferize][NFC] Rename ModuleAnalysisState to FuncAnalysisState
This is for consistency reasons. `*AnalysisState` always starts with the name of the dialect.

Differential Revision: https://reviews.llvm.org/D123209
2022-04-07 00:48:53 +09:00
Arjun P 1ba6043332 [MLIR][Presburger] Refactor subtraction in preparation for making it iterative
Refactor the operation of subtraction by
- removing the usage of SimplexRollbackScopeExit since this
  can't be used in the iterative version
- reducing the number of stack variables to make the
  iterative version easier to follow

Reviewed By: Groverkss

Differential Revision: https://reviews.llvm.org/D123156
2022-04-06 16:35:28 +01:00
Matthias Springer f4f1cf6c31 [mlir][bufferize] Better analysis for return values of CallOps
Support returning arbitrary tensors from functions. Even those that are
not equivalent. To that end, additional information is gathered during
the analysis phase. In particular, which function args are aliasing with
which return values.

Also fix bugs in the current implementation when returning equivalent
tensors. Various unit tests are added to ensure that we have better test
coverage.

Note: Returning non-equivalent tensors is only allowed when
allowReturnAllocs is enabled. This functionality is useful for unit
testing and compatibility with other bufferizations such as the sparse
compiler. This is also towards using ModuleBufferization as a
replacement for --func-bufferize.

Differential Revision: https://reviews.llvm.org/D119120
2022-04-06 23:54:32 +09:00
Matthias Springer cd7de446fd [mlir][bufferize] Simplify ModuleBufferization driver
* Bufferize FuncOp bodies and boundaries in the same loop. This is in preparation of moving FuncOp bufferization into an external model implementation.
* As a side effect, stop bufferization earlier if there was an error. (Do not continue bufferization, fewer error messages.)
* Run equivalence analysis of CallOps before the main analysis. This is needed so that equialvence info is propagated properly.

Differential Revision: https://reviews.llvm.org/D123208
2022-04-06 23:53:07 +09:00
Matthias Springer 5ab34492d6 [mlir][bufferize] Fix dropped return type in ModuleBufferization
Differential Revision: https://reviews.llvm.org/D123192
2022-04-06 23:48:15 +09:00
Alexander Belyaev 747b10be95 Revert "Revert "[mlir] Rewrite canonicalization of collapse(expand) and expand(collapse).""
This reverts commit 96e9b6c9dc.
2022-04-06 12:18:30 +02:00
Matthias Springer 7a50560354 [mlir][bufferize][NFC] Clean up ModuleBufferizationState
* Store bbArg indices instead of BlockArguments, so that args can be changed during bufferizationn.
* Use type aliases for better readability.

Differential Revision: https://reviews.llvm.org/D123191
2022-04-06 18:32:53 +09:00
Nicolas Vasilache fc8f465a00 [mlir][MemRef] Allow transposed layouts in ExpandShapeOp.
https://reviews.llvm.org/D122641 introduced fixes to the ExpandShapeOp verifier
but also introduced an artificial layout limitation that prevents the consideration of transposed layouts.

This revision fixes the omissions and reimplements the logic using saturated arithmetic which is more
idiomatic and avoids leaking internal implementation details.

Tests cases are added for transposed layouts.

Reviewed By: springerm

Differential Revision: https://reviews.llvm.org/D122845
2022-04-06 04:19:30 -04:00
Argyrios Kyrtzidis 330268ba34 [Support/Hash functions] Change the `final()` and `result()` of the hashing functions to return an array of bytes
Returning `std::array<uint8_t, N>` is better ergonomics for the hashing functions usage, instead of a `StringRef`:

* When returning `StringRef`, client code is "jumping through hoops" to do string manipulations instead of dealing with fixed array of bytes directly, which is more natural
* Returning `std::array<uint8_t, N>` avoids the need for the hasher classes to keep a field just for the purpose of wrapping it and returning it as a `StringRef`

As part of this patch also:

* Introduce `TruncatedBLAKE3` which is useful for using BLAKE3 as the hasher type for `HashBuilder` with non-default hash sizes.
* Make `MD5Result` inherit from `std::array<uint8_t, 16>` which improves & simplifies its API.

Differential Revision: https://reviews.llvm.org/D123100
2022-04-05 21:38:06 -07:00
Aart Bik 175b9af484 [mlir][sparse] avoid reserving dense storage for ptr/idx
This avoids a rather big bug where we were reserving
dense space for the ptx/idx in the first sparse dimension.
For example, using CSR for a 140874 x 140874 matrix with
3977139 nonzero would reserve the full 19845483876 space.
This revision fixes this for now, but we need to revisit
the reservation heuristic to make this better.

Reviewed By: bixia

Differential Revision: https://reviews.llvm.org/D123166
2022-04-05 17:40:01 -07:00
Hanhan Wang 96e9b6c9dc Revert "[mlir] Rewrite canonicalization of collapse(expand) and expand(collapse)."
This reverts commit 64f659bee6.

An invalid tensor.expand_shape op is generated with the commit. To repro:

$ mlir-opt -canonicalize a.mlir

```
func @foo(%0: tensor<1x1xf32>, %1: tensor<1x1xf32>, %2: tensor<1x1xf32>) -> tensor<1x1xf32> {
  %cst = arith.constant 0.000000e+00 : f32
  %3 = linalg.init_tensor [8, 1] : tensor<8x1xf32>
  %4 = linalg.fill ins(%cst : f32) outs(%3 : tensor<8x1xf32>) -> tensor<8x1xf32>
  %5 = tensor.collapse_shape %0 [] : tensor<1x1xf32> into tensor<f32>
  %6 = tensor.insert_slice %5 into %4[0, 0] [1, 1] [1, 1] : tensor<f32> into tensor<8x1xf32>
  %7 = linalg.init_tensor [8, 1] : tensor<8x1xf32>
  %8 = linalg.fill ins(%cst : f32) outs(%7 : tensor<8x1xf32>) -> tensor<8x1xf32>
  %9 = tensor.collapse_shape %2 [] : tensor<1x1xf32> into tensor<f32>
  %10 = tensor.insert_slice %9 into %8[0, 0] [1, 1] [1, 1] : tensor<f32> into tensor<8x1xf32>
  %11 = tensor.collapse_shape %6 [[0, 1]] : tensor<8x1xf32> into tensor<8xf32>
  %12 = linalg.init_tensor [8] : tensor<8xf32>
  %13 = linalg.generic {indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], iterator_types = ["parallel"]} ins(%11 : tensor<8xf32>) outs(%12 : tensor<8xf32>) {
  ^bb0(%arg3: f32, %arg4: f32):
    linalg.yield %arg3 : f32
  } -> tensor<8xf32>
  %14 = tensor.expand_shape %13 [[0, 1, 2, 3]] : tensor<8xf32> into tensor<1x1x8x1xf32>
  %15 = tensor.collapse_shape %1 [] : tensor<1x1xf32> into tensor<f32>
  %16 = linalg.init_tensor [] : tensor<f32>
  %17 = linalg.generic {indexing_maps = [affine_map<() -> ()>, affine_map<() -> ()>], iterator_types = []} ins(%15 : tensor<f32>) outs(%16 : tensor<f32>) {
  ^bb0(%arg3: f32, %arg4: f32):
    linalg.yield %arg3 : f32
  } -> tensor<f32>
  %18 = tensor.expand_shape %17 [] : tensor<f32> into tensor<1x1x1x1xf32>
  %19 = tensor.collapse_shape %10 [[0, 1]] : tensor<8x1xf32> into tensor<8xf32>
  %20 = linalg.init_tensor [8] : tensor<8xf32>
  %21 = linalg.generic {indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], iterator_types = ["parallel"]} ins(%19 : tensor<8xf32>) outs(%20 : tensor<8xf32>) {
  ^bb0(%arg3: f32, %arg4: f32):
    linalg.yield %arg3 : f32
  } -> tensor<8xf32>
  %22 = tensor.expand_shape %21 [[0, 1, 2, 3]] : tensor<8xf32> into tensor<1x1x8x1xf32>
  %23 = linalg.mmt4d {comment = "f32*f32->f32, aarch64, matrix*vector"} ins(%14, %18 : tensor<1x1x8x1xf32>, tensor<1x1x1x1xf32>) outs(%22 : tensor<1x1x8x1xf32>) -> tensor<1x1x8x1xf32>
  %24 = tensor.collapse_shape %23 [[0, 1, 2, 3]] : tensor<1x1x8x1xf32> into tensor<8xf32>
  %25 = linalg.init_tensor [8] : tensor<8xf32>
  %26 = linalg.generic {indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], iterator_types = ["parallel"]} ins(%24 : tensor<8xf32>) outs(%25 : tensor<8xf32>) {
  ^bb0(%arg3: f32, %arg4: f32):
    linalg.yield %arg3 : f32
  } -> tensor<8xf32>
  %27 = tensor.expand_shape %26 [[0, 1]] : tensor<8xf32> into tensor<8x1xf32>
  %28 = tensor.extract_slice %27[0, 0] [1, 1] [1, 1] : tensor<8x1xf32> to tensor<f32>
  %29 = tensor.expand_shape %28 [] : tensor<f32> into tensor<1x1xf32>
  return %29 : tensor<1x1xf32>
}
```

Differential Revision: https://reviews.llvm.org/D123161
2022-04-05 15:05:41 -07:00