148 Commits

Author SHA1 Message Date
Matthias Springer
0ff92fe2f0
[mlir][LLVM][NFC] Simplify computeSizes function (#153588)
Rename `computeSizes` to `computeSize` and make it compute just a single
size. This is in preparation of adding 1:N support to the Func->LLVM
lowering patterns.
2025-08-14 17:00:03 +02:00
Scott Manley
e72335192d
[Arith][MemRef] add AtomicRMWKind::xori to enum (#151701)
Add missing xor AtomicRMWKind enum in arith. Also add support for xor to
memref.atomic_rmw so the change can be tested.

This does NOT add it for all users of the enum (e.g. Affine, Vector)
2025-08-11 08:46:06 -04:00
Erick Ochoa Lopez
d72e58e422
[MLIR][LLVM] Propagate alignment attribute from memref to LLVM (#151380)
Propagate alignment attribute from operations in the memref dialect to
the LLVM dialect.

Possible improvements: maybe the alignment attribute in LLVM's store and
load operations should be confined/constrained to i64? I believe that
way one can avoid typing the value in the attribute dictionary. I.e.,
from `{ alignment = 32 : i64 }` to `{ alignment = 32}`
2025-08-05 12:06:57 -04:00
Mehdi Amini
75e5a70577
[MLIR] Migrate some conversion passes and dialects to LDBG() macro (NFC) (#151349) 2025-07-30 17:58:54 +02:00
Maksim Levental
258daf5395
[mlir][NFC] update mlir create APIs (34/n) (#150660)
See https://github.com/llvm/llvm-project/pull/147168 for more info.
2025-07-25 12:36:54 -05:00
Maksim Levental
4ae9fdca8a
[mlir][NFC] update Conversion create APIs (6/n) (#149888)
See https://github.com/llvm/llvm-project/pull/147168 for more info.
2025-07-22 08:16:53 -04:00
Matthias Springer
4cca22ffae
[mlir][memref] Do not access erased op in memref.global lowering (#148355)
Do not access the erased `memref.global` operation in the lowering
pattern. That won't work anymore in a One-Shot Dialect Conversion and
triggers a use-after-free sanitizer error.

After the One-Shot Dialect Conversion refactoring, a
`ConversionPatternRewriter` will behave more like a normal
`PatternRewriter`.
2025-07-12 16:13:12 +02:00
Jakub Kuderski
6512ca7ddb
[mlir] Add isStatic* size check for ShapedTypes. NFCI. (#147085)
The motivation is to avoid having to negate `isDynamic*` checks, avoid
double negations, and allow for `ShapedType::isStaticDim` to be used in
ADT functions without having to wrap it in a lambda performing the
negation.

Also add the new functions to C and Python bindings.
2025-07-07 14:57:27 -04:00
Kazu Hirata
fa9adbfda9
[mlir] Remove unused includes (NFC) (#147101)
These are identified by misc-include-cleaner.  I've filtered out those
that break builds.  Also, I'm staying away from llvm-config.h,
config.h, and Compiler.h, which likely cause platform- or
compiler-specific build failures.
2025-07-04 13:30:21 -07:00
Twice
c3e08c9b89
[MLIR] Replace getVoidPtrType with getPtrType in ConvertToLLVMPattern (#145657)
`ConversionPattern::getVoidPtrType` looks a little confusion since the
opaque pointer migration is already done. Also we cannot specify address
space in this method.

Maybe we can mark them as deprecated and add new method `getPtrType()`,
as this PR did : )
2025-06-27 12:31:53 +02:00
Kazu Hirata
dec93ae454
[mlir] Migrate away from ValueRange(std::nullopt) (NFC) (#145210)
ArrayRef has a constructor that accepts std::nullopt.  This
constructor dates back to the days when we still had llvm::Optional.

Since the use of std::nullopt outside the context of std::optional is
kind of abuse and not intuitive to new comers, I would like to move
away from the constructor and eventually remove it.

One of the common uses of std::nullopt is in one of the constructors
for ValueRange.  This patch takes care of the migration where we need
ValueRange() to facilitate perfect forwarding.  Note that {} would be
ambiguous for perfecting forwarding to work.
2025-06-22 06:30:17 -07:00
Michele Scuttari
bb372963df
[MLIR] Add optional cached symbol tables to LLVM conversion patterns (#144032)
This PR allows to optionally speed up the lookup of symbols by providing a `SymbolTableCollection` instance to the interested conversion patterns. It is follow-up on the discussion about symbol / symbol table management carried on [Discourse](https://discourse.llvm.org/t/symbol-table-as-first-class-citizen-in-builders/86813).
2025-06-21 10:55:44 +02:00
Oleksandr "Alex" Zinenko
875b36a874
[mlir] fix MemRefToLLVM lowering of atomic operations (#139045)
We have been confusingly, and arguably incorrectly, lowering `m**imumf`
atomic RMW operations in the MemRef dialect to `fm**` atomic RMW
operations in the LLVM dialect, which have different NaN-propagation
semantics: `m**imumf` propagates NaNs from either operand whereas
`fm**`, which lowers to the `fm**num` intrinsic returns the non-NaN
operand. This also contradicts the lowering of `arith.m**imumf` and
`arith.m**numf` operations.

Change the lowering to match the terminology in arith.

Add tests for these lowerings.

Keep a debug message in case of surprising behavior downstream (the code
may be producing more NaNs now).
2025-06-17 13:40:57 +02:00
Andrzej Warzyński
dca74f794a
[mlir][memref] Revert #140730 (#141406)
Reverts #140730 - that turned out not to be an NFC as we originally
thought. See the attached test for an example. Many thanks to @Garra1980
for reporting!

Note, without this change, the newly added test would be incorrectly
converted to:
```mlir
  func.func @view_memref_as_rank0(%arg0: index, %arg1: memref<2xi8>) {
    %0 = llvm.mlir.poison : !llvm.struct<(ptr, ptr, i64)>
    return
  }
```
2025-05-25 17:46:46 +01:00
Javed Absar
fd86e732fa
[mlir][memref][nfc] push early-exit to earlier (#140730)
Move early exit check to as early as possible,

quic_mabsar@quicinc.com
2025-05-21 11:37:57 +01:00
Peiyong Lin
04ad8d4900
Emit inbounds and nuw attributes in memref. (#138984)
Now that MLIR accepts nuw and nusw in getelementptr, this patch emits
the inbounds and nuw attributes when lower memref to LLVM in load and
store operators.

This patch also strengthens the memref.load and memref.store spec about
undefined behaviour during lowering.

This patch also lifts the |rewriter| parameter in getStridedElementPtr
ahead so that LLVM::GEPNoWrapFlags can be added at the end with a
default value and grouped together with other operators' parameters.

Signed-off-by: Lin, Peiyong <linpyong@gmail.com>
2025-05-20 14:16:22 -07:00
Shay Kleiman
ffb9bbfd07
[mlir][MemRef] Changed AssumeAlignment into a Pure ViewLikeOp (#139521)
Made AssumeAlignment a ViewLikeOp that returns a new SSA memref equal
to its memref argument and made it have Pure trait. This
gives it a defined memory effect that matches what it does in practice
and makes it behave nicely with optimizations which won't get rid of it
unless its result isn't being used.
2025-05-18 13:50:29 +03:00
Max Graey
8aaac80ddd
[NFC] Use more isa and isa_and_nonnull instead dyn_cast for predicates (#137393)
Also fix some typos in comments

---------

Co-authored-by: Mehdi Amini <joker.eph@gmail.com>
2025-05-13 22:34:42 +08:00
Matthias Springer
bb21a6819b
[mlir][memref] Move AllocLikeConversion.h helpers into MemRefToLLVM.cpp (#136424)
This commit moves code around: The helper functions/classes are moved
into `MemRefToLLVM.cpp`. This simplifies the code a bit: fewer
templatized functions, fewer function calls, fewer lines of code.

This commit also moves checks in `matchAndRewrite` to the beginning of
the functions, such that patterns bail out (`return failure()`) before
starting to modify any IR. (Apart from that, this change is NFC.) This
is in preparation of the One-Shot Dialect Conversion refactoring, which
will disallow pattern rollbacks.
2025-04-20 12:35:47 +02:00
Matthias Springer
8553efd2e9
[mlir][LLVM] Add OpBuilder & to lookupOrCreateFn functions (#136421)
These functions are called from lowering patterns. All IR modifications
in a pattern must be performed through the provided rewriter, but these
functions used to instantiate a new `OpBuilder`, bypassing the provided
rewriter.
2025-04-20 10:06:22 +02:00
Longsheng Mou
894b27a746
[mlir][MemRefToLLVM] Fix crash with unconvertable memory space (#132323)
This PR adds handling when the `memref.alloca` with unconvertable memory
space to prevent a crash. Fixes #131439.
2025-03-26 16:51:26 +08:00
Matthias Springer
a21cfca320
[mlir][IR] Deprecate match and rewrite functions (#130031)
Deprecate the `match` and `rewrite` functions. They mainly exist for
historic reasons. This PR also updates all remaining uses of in the MLIR
codebase.

This is addressing a
[comment](https://github.com/llvm/llvm-project/pull/129861#pullrequestreview-2662696084)
on an earlier PR.

Note for LLVM integration: `SplitMatchAndRewrite` will be deleted soon,
update your patterns to use `matchAndRewrite` instead of separate
`match` / `rewrite`.

---------

Co-authored-by: Jakub Kuderski <jakub@nod-labs.com>
2025-03-07 08:43:01 +01:00
Matthias Springer
a6151f4e23
[mlir][IR] Move match and rewrite functions into separate class (#129861)
The vast majority of rewrite / conversion patterns uses a combined
`matchAndRewrite` instead of separate `match` and `rewrite` functions.

This PR optimizes the code base for the most common case where users
implement a combined `matchAndRewrite`. There are no longer any `match`
and `rewrite` functions in `RewritePattern`, `ConversionPattern` and
their derived classes. Instead, there is a `SplitMatchAndRewriteImpl`
class that implements `matchAndRewrite` in terms of `match` and
`rewrite`.

Details:
* The `RewritePattern` and `ConversionPattern` classes are simpler
(fewer functions). Especially the `ConversionPattern` class, which now
has 5 fewer functions. (There were various `rewrite` overloads to
account for 1:1 / 1:N patterns.)
* There is a new class `SplitMatchAndRewriteImpl` that derives from
`RewritePattern` / `OpRewritePatern` / ..., along with a type alias
`RewritePattern::SplitMatchAndRewrite` for convenience.
* Fewer `llvm_unreachable` are needed throughout the code base. Instead,
we can use pure virtual functions. (In cases where users previously had
to implement `rewrite` or `matchAndRewrite`, etc.)
* This PR may also improve the number of [`-Woverload-virtual`
warnings](https://discourse.llvm.org/t/matchandrewrite-hiding-virtual-functions/84933)
that are produced by GCC. (To be confirmed...)

Note for LLVM integration: Patterns with separate `match` / `rewrite`
implementations, must derive from `X::SplitMatchAndRewrite` instead of
`X`.

---------

Co-authored-by: River Riddle <riddleriver@gmail.com>
2025-03-06 08:48:51 +01:00
Krzysztof Drewniak
f4e3b8783c
[mlir][LLVM] Switch undef for poison for uninitialized values (#125629)
LLVM itself is generally moving away from using `undef` and towards
using `poison`, to the point of having a lint that caches new uses of
`undef` in tests.

In order to not trip the lint on new patterns and to conform to the
evolution of LLVM
- Rename valious ::undef() methods on StructBuilder subclasses to
::poison()
- Audit the uses of UndefOp in the MLIR libraries and replace almost all
of them with PoisonOp

The remaining uses of `undef` are initializing `uninitialized` memrefs,
explicit conversions to undef from SPIR-V, and a few cases in
AMDGPUToROCDL where usage like

    %v = insertelement <M x iN> undef, iN %v, i32 0
    %arg = bitcast <M x iN> %v to i(M * N)

is used to handle "i32" arguments that are are really packed vectors of
smaller types that won't always be fully initialized.
2025-02-06 12:49:30 -06:00
Luohao Wang
e84f6b6a88
[mlir] Fix conflict of user defined reserved functions with internal prototypes (#123378)
On lowering from `memref` to LLVM, `malloc` and other intrinsic
functions from `libc` will be declared in the current module. User's
redefinition of these reserved functions will poison the internal
analysis with wrong prototype. This patch adds assertion on the found
function's type and reports if it mismatch with the intended type.

Related to #120950


---------

Co-authored-by: Luohao Wang <Luohaothu@users.noreply.github.com>
2025-01-28 14:40:47 +01:00
Matthias Springer
6aaa8f25b6
[mlir][IR][NFC] Move free-standing functions to MemRefType (#123465)
Turn free-standing `MemRefType`-related helper functions in
`BuiltinTypes.h` into member functions.
2025-01-21 08:48:09 +01:00
Krzysztof Drewniak
3359806817
[mlir][LLVM][MemRef] Lower assume_alignment with operand bundles (#117800)
Now that LLVM allows a operand bundle on assume calls to directly
specify alignment assumptions, change the lowering of
memref.assume_alignment to use that feature instead of the ptrtoint
method.

This makes LLVM's job easier and prevents issues when dealing with
cases where ptrtoint isn't a desired operation (like those with poiner
provenance)
2024-11-26 17:20:39 -06:00
Matthias Springer
206fad0e21
[mlir][NFC] Mark type converter in populate... functions as const (#111250)
This commit marks the type converter in `populate...` functions as
`const`. This is useful for debugging.

Patterns already take a `const` type converter. However, some
`populate...` functions do not only add new patterns, but also add
additional type conversion rules. That makes it difficult to find the
place where a type conversion was added in the code base. With this
change, all `populate...` functions that only populate pattern now have
a `const` type converter. Programmers can then conclude from the
function signature that these functions do not register any new type
conversion rules.

Also some minor cleanups around the 1:N dialect conversion
infrastructure, which did not always pass the type converter as a
`const` object internally.
2024-10-05 21:32:40 +02:00
Ramkumar Ramachandra
e843f029b4
mlir: fix incorrect usages of divideCeilSigned (#95680)
Follow up on #95087 to fix incorrect usage instances of
divideCeilSigned.
2024-06-17 11:43:57 +01:00
Spenser Bauman
846103c7e3
[mlir][memref] Unranked support for extract_aligned_pointer_as_index (#93908)
memref.extract_aligned_pointer_as_index currently does not support
unranked inputs. This lack of support interferes with the folding
operations in the expand-strided-metadata pass.

    %r = memref.reinterpret_cast %arg0 to
        offset: [0],
        sizes: [],
        strides: [] : memref<*xf32> to memref<f32>

%i = memref.extract_aligned_pointer_as_index %r : memref<f32> -> index

Patterns like this occur when bufferizing operations on unranked
tensors.

This change modifies the extract_aligned_pointer_as_index operation to
support unranked inputs with corresponding support in the MemRef->LLVM
conversion.

Co-authored-by: Spenser Bauman <sabauma@fastmail>
2024-06-13 09:12:18 -04:00
Ramkumar Ramachandra
0fb216fb2f
mlir/MathExtras: consolidate with llvm/MathExtras (#95087)
This patch is part of a project to move the Presburger library into
LLVM.
2024-06-11 23:00:02 +01:00
Matthias Springer
91d5653e3a
[mlir] Use OpBuilder::createBlock in op builders and patterns (#82770)
When creating a new block in (conversion) rewrite patterns,
`OpBuilder::createBlock` must be used. Otherwise, no
`notifyBlockInserted` notification is sent to the listener.

Note: The dialect conversion relies on listener notifications to keep
track of IR modifications. Creating blocks without the builder API can
lead to memory leaks during rollback.
2024-02-24 09:10:07 +01:00
Max191
ce6ef990fe
[mlir] Remove convertible identity restriction for memref.atomic_rmw to LLVM (#72262)
memref.atomic_rmw will fail to convert for memref types that have an offset because they do not have identity maps. This restriction is overly conservative, so this changes the restriction to only strided memref types.
2023-11-14 22:45:14 -05:00
long.chen
1609f1c2a5
[mlir][affine][nfc] cleanup deprecated T.cast style functions (#71269)
detail see the docment: https://mlir.llvm.org/deprecation/

Not all changes are made manually, most of them are made through a clang
tool I wrote https://github.com/lipracer/cpp-refactor.
2023-11-14 13:01:19 +08:00
Christian Ulmann
b28a296cdf
[MLIR][MemRefToLLVM] Remove typed pointer support (#70909)
This commit removes the support for lowering MemRefToLLVM to LLVM
dialect with typed pointers. Typed pointers have been deprecated for a
while now and it's planned to soon remove them from the LLVM dialect.

Related PSA:
https://discourse.llvm.org/t/psa-removal-of-typed-pointers-from-the-llvm-dialect/74502
2023-11-02 07:35:58 +01:00
Krzysztof Drewniak
73c6248cc2
[mlir][MemRefToLLVM] Fix crashes with unconvertable memory spaces (#70694)
Fixes #70160

The issue is resolved by:
1. Changing the call to address space conversion to use the correct
return type, preventing the code from moving past the if and into the
crashing optional dereference.
2. Adding handling to the AllocLikeOp rewriter for the case where the
underlying buffer allocation fails.
2023-10-31 09:01:43 -05:00
Felix Schneider
c336a06144 [mlir] [memref] Fix alignment bug in memref.copy lowering
memref.copy gets lowered to a function call sometimes, this function
is passed the element size of the memref in bytes as an argument.
The element size passed to the copyMemRef() function call can be
miscalculated if the LLVM IR uses aligned access to the memory.

This can be fixed by using llvm.getelementptr to calculate the element
size natively. This is also done in the other lowering path that lowers
to an intrinsic.

Fix https://github.com/llvm/llvm-project/issues/64072

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D156126
2023-09-14 13:18:12 +02:00
Felix Schneider
55088efe06 [mlir][memref] Fix MemrefToLLVM lowering pattern for memref.transpose
The lowering pattern to LLVM for memref.transpose has a bug where
instead of transposing from (source) -> (dest) it actually transposes
(dest) -> (source). This patch fixes the bug and updates the test.

Fix https://github.com/llvm/llvm-project/issues/65145

Reviewed By: nicolasvasilache

Differential Revision: https://reviews.llvm.org/D159290
2023-09-14 13:12:55 +02:00
Daniil Dudkin
c46a04339a
[mlir][arith] Rename AtomicRMWKind's maxfmaximumf, minfminimumf (#66135)
This patch is part of a larger initiative aimed at fixing floating-point
`max` and `min` operations in MLIR:
https://discourse.llvm.org/t/rfc-fix-floating-point-max-and-min-operations-in-mlir/72671.

This commit renames `maxf` and `minf` enumerators of `AtomicRMWKind`
to better reflect the current naming scheme and the goals of the RFC.
2023-09-14 01:09:37 +03:00
Martin Erhart
8037deb7af [mlir][memref] Add pass to expand realloc operations, simplify lowering to LLVM
There are two motivations for this change:
1. It considerably simplifies adding support for the realloc operation to the
   new buffer deallocation pass by lowering the realloc such that no
   deallocation operation is inserted and the deallocation pass itself can
   insert that dealloc
2. The lowering is expressed on a higher level and thus easier to understand,
   and the lowerings of the memref operations it is composed of don't have to
   be duplicated in the MemRefToLLVM lowering (also see discussion in
   https://reviews.llvm.org/D133424)

Reviewed By: springerm

Differential Revision: https://reviews.llvm.org/D159430
2023-09-05 08:58:40 +00:00
Mikhail Goncharov
0a0aff2d24 fix unused variable warnings in conditionals
warning was updated in 92023b15099012a657da07ebf49dd7d94a260f84
2023-08-30 19:09:27 +02:00
Krzysztof Drewniak
7db18533b9 [mlir][MemRefToLLVM] Add fmin, fmax to AtomicRMW lowering
Add cases to the memref.atomicrmw lowering for floating-point min and
max, since LLVM supports these.

Reviewed By: bondhugula

Differential Revision: https://reviews.llvm.org/D158283
2023-08-21 21:20:52 +00:00
Matthias Springer
ce254598b7 [mlir][Conversion] Store const type converter in ConversionPattern
ConversionPatterns do not (and should not) modify the type converter that they are using.

* Make `ConversionPattern::typeConverter` const.
* Make member functions of the `LLVMTypeConverter` const.
* Conversion patterns take a const type converter.
* Various helper functions (that are called from patterns) now also take a const type converter.

Differential Revision: https://reviews.llvm.org/D157601
2023-08-14 09:03:11 +02:00
Markus Böck
f3b1361f35 [mlir] Generate constructor in generic adaptors allowing construction from an op instance
In essentially all occurrences of adaptor constructions in the codebase, an instance of the op is available and only a different value range is being used. Nevertheless, one had to perform the ritual of calling and pass `getAttrDictionary()`, `getProperties` and `getRegions` manually.

This patch changes that by teaching TableGen to generate a new constructor in the adaptor that is constructable using `GenericAdaptor(valueRange, op)`. The (discardable) attr dictionary, properties and the regions are then taken directly from the passed op, with only the value range being taken from the first parameter.

This simplifies a lot of code and also guarantees that all the various getters of the adaptor work in all scenarios.

Differential Revision: https://reviews.llvm.org/D157516
2023-08-10 12:38:54 +02:00
Matthias Springer
876a480cac [mlir][Conversion] Add type converter parameter to ConvertToLLVMPatternInterface
Most `*-to-llvm` conversion patterns require a type converter. This
revision adds a type converter to the
`populateConvertToLLVMConversionPatterns` function and implements the
interface for the MemRef dialect.

Differential Revision: https://reviews.llvm.org/D157387
2023-08-09 09:00:46 +02:00
Alex Zinenko
fcb0294b58 Revert "[mlir][conversion] NFC - Relax convert-cf-to-llvm and finalize-memref-to-llvm to also work on non-builtin module ops"
This reverts commit cc6b8d8077699916728053dfa760e69e146271cb.

Seems to have been committed accidentally.
2023-08-04 13:30:13 +00:00
Alex Zinenko
e98e59955e Revert "Foo"
This reverts commit 3c9aa10c57cf0833ff108ecf9ffbb512bd96cc89.

No proper description of the commit.
2023-08-04 13:30:12 +00:00
Nicolas Vasilache
3c9aa10c57 Foo 2023-08-04 11:06:17 +00:00
Nicolas Vasilache
cc6b8d8077 [mlir][conversion] NFC - Relax convert-cf-to-llvm and finalize-memref-to-llvm to also work on non-builtin module ops
This is a prerequisite for unentangling LowerGpuOpsToNVVMOps which explicitly populates its conversion with
`populateControlFlowToLLVMConversionPatterns` and `populateFinalizeMemRefToLLVMConversionPatterns`.

However those patterns cannot be generally added to a pass anchored on a non-ModuleOp.

Instead, LowerGpuOpsToNVVMOps should stop including the world, in a future commit.

Differential Revision: https://reviews.llvm.org/D156860
2023-08-04 11:06:17 +00:00
Nicolas Vasilache
620e2bb20c [mlir][LLVM] NFC - Remove createIndexConstant method
This revision removes the createIndexConstant method, which implicitly creates constants of the
getIndexType type and updates all uses to the more explicit createIndexAttrConstant which requires
an explicit Type parameter.

This is an NFC step towards entangling index type conversion in LLVM lowering.

The selection of which index type to use requires finer granularity than the existing
implementations which all rely on pass level flags and end up in mismatches, especially on GPUs
with multiple address spaces of different capacities.

This revision also includes an NFC fix to MemRefToLLVM.cpp that prevents a crash in cases where
an integer memory space cannot be derived for a MemRef.

Differential Revision: https://reviews.llvm.org/D156854
2023-08-02 07:24:29 +00:00