72 Commits

Author SHA1 Message Date
Nikita Popov
c23b4fbdbb
[IR] Remove size argument from lifetime intrinsics (#150248)
Now that #149310 has restricted lifetime intrinsics to only work on
allocas, we can also drop the explicit size argument. Instead, the size
is implied by the alloca.

This removes the ability to only mark a prefix of an alloca alive/dead.
We never used that capability, so we should remove the need to handle
that possibility everywhere (though many key places, including stack
coloring, did not actually respect this).
2025-08-08 11:09:34 +02:00
Mehdi Amini
fec2c434ca
[MLIR] Migrate InlinerInterfaceImpl to the new LDBG() debug form (NFC) (#150853) 2025-07-30 17:54:49 +02:00
Maksim Levental
6056f942ab
[mlir][NFC] update LLVM create APIs (2/n) (#149667)
See https://github.com/llvm/llvm-project/pull/147168 for more info.
2025-07-19 18:15:54 -04:00
Kazu Hirata
d5def016b6
[llvm] Remove unused includes (NFC) (#148342)
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-12 11:28:55 -07:00
Jacques Pienaar
cd8094ebc1
[mlir] Translate nested debug information (#140915)
This backports changes from Triton with the exception that for fused
locations, use the first one with file info rather than just first.

---------

Co-authored-by: Sergei Lebedev <slebedev@google.com>
Co-authored-by: Keren Zhou <kerenzhou@openai.com>
2025-05-21 12:43:02 -07:00
lorenzo chelini
61536f2781
[mlir] Retire additional let constructor (NFC) (#139390)
Three main changes:

- The pass createRequestCWrappersPass is renamed as
createLLVMRequestCWrappersPass

- createOptimizeForTargetPass is now under the LLVM namespace. It’s
unclear why the NVVM namespace was used initially, as all passes in
LLVMIR/Transforms/Passes.h consistently reside in the LLVM namespace.

- DuplicateFunctionEliminationPass is now in the func namespace.
2025-05-13 11:15:29 +02:00
Bruno Cardoso Lopes
a168ddc470
[MLIR][LLVM] Block address support (#134335)
Add support for import and translate.

MLIR does not support using basic block references outside a function
(like LLVM does), This PR does not consider changes to MLIR to that
respect. It instead introduces two new ops: `llvm.blockaddress` and
`llvm.blocktag`. Here's an example:

```
llvm.func @ba() -> !llvm.ptr {
  %0 = llvm.blockaddress <function = @ba, tag = <id = 1>> : !llvm.ptr
  llvm.br ^bb1
^bb1:  // pred: ^bb0
  llvm.blocktag <id = 1>
  llvm.return %0 : !llvm.ptr
}
```

Value `%0` hold the address of block tagged as `id = 1` in function
`@ba`. Block tags need to be unique within a function and use of
`llvm.blockaddress` requires a matching tag in a `llvm.blocktag`.
2025-04-07 17:53:18 -07:00
Tobias Gysi
d9ccfd7568
[mlir][llvm] Respect call noinline attr in inliner (#134493)
This commit extends the LLVM dialect inliner interface to respect the
call op's noinline attribute. This is a follow-up to
https://github.com/llvm/llvm-project/pull/133726
which added the noinline attribute to the LLVM dialect call op.
2025-04-07 08:12:46 +02:00
Tobias Gysi
d0c9e70bcc
[MLIR][LLVM] Improve inlining debug information (#123520)
This commit improves the debug information for `alloca` and `memcpy`
operations generated by the LLVM dialect inlining interface.

When inlining by value parameters, the inliner creates `alloca` and
`memcpy` operations. This revision sets the location of these created
operations to the respective argument locations instead of the function
location. This change enables users to better identify the source code
location of the copied variables.
2025-01-20 09:30:28 +01:00
William Moses
b39c5cb697
[MLIR][LLVM] Fix inlining of a single block ending with unreachable (#122646)
alternate option to https://github.com/llvm/llvm-project/pull/122615
2025-01-13 12:37:16 -06:00
William Moses
8d306ccdef
[MLIR][NVVM] Enable inlining of func's calling nvvm intrinsics (#122650) 2025-01-13 11:00:04 -06:00
William Moses
b306eff56f
[MLIR] Enable inlining for private symbols (#122572)
The inlining code for llvm funcs seems to have needlessly forbidden
inlining of private (e.g. non-cloning) symbols.
2025-01-11 09:10:27 -05:00
Jacques Pienaar
09dfc5713d
[mlir] Enable decoupling two kinds of greedy behavior. (#104649)
The greedy rewriter is used in many different flows and it has a lot of
convenience (work list management, debugging actions, tracing, etc). But
it combines two kinds of greedy behavior 1) how ops are matched, 2)
folding wherever it can.

These are independent forms of greedy and leads to inefficiency. E.g.,
cases where one need to create different phases in lowering and is
required to applying patterns in specific order split across different
passes. Using the driver one ends up needlessly retrying folding/having
multiple rounds of folding attempts, where one final run would have
sufficed.

Of course folks can locally avoid this behavior by just building their
own, but this is also a common requested feature that folks keep on
working around locally in suboptimal ways.

For downstream users, there should be no behavioral change. Updating
from the deprecated should just be a find and replace (e.g., `find ./
-type f -exec sed -i
's|applyPatternsAndFoldGreedily|applyPatternsGreedily|g' {} \;` variety)
as the API arguments hasn't changed between the two.
2024-12-20 08:15:48 -08:00
Matthias Springer
b613a54075
[mlir][IR][NFC] Cleanup insertion point API usage (#115415)
Use `setInsertionPointToStart` / `setInsertionPointToEnd` when possible.
2024-11-08 14:31:27 +09:00
Observer007
d124b98eb6
[mlir] add overload createDIScopeForLLVMFuncOp function (#111689)
follow up work of https://github.com/llvm/llvm-project/pull/106229, add
create pass overload function to create pass.

---------

Co-authored-by: jingzec <jingzec@nvidia.com>
2024-10-10 17:11:14 +08:00
Tobias Gysi
8e2ccdc4de
[MLIR][LLVM] Use ViewLikeOpInterface (#111663)
This commit adds the ViewLikeOpInterface to the GEP and AddrSpaceCast
operations. This allows us to simplify the inliner interface. At the
same time, the change also makes the inliner interface more extensible
for downstream users that have custom view-like operations.
2024-10-09 14:37:01 +02:00
Walter Erquinigo
2918e779a9
[mlir][debuginfo] Add support for subprogram annotations (#110946)
LLVM already supports `DW_TAG_LLVM_annotation` entries for subprograms,
but this hasn't been surfaced to the LLVM dialect.
I'm doing the minimal amount of work to support string-based
annotations, which is useful for attaching metadata to
functions, which is useful for debuggers to offer features beyond basic
DWARF.
As LLVM already supports this, this patch is not controversial.
2024-10-07 17:51:08 -04:00
Longsheng Mou
a1b6daea2c
[mlir][LLVMIR] Add LLVMDialect check in DIScopeForLLVMFuncOp (#110427)
This PR adds an LLVMDialect check in `DIScopeForLLVMFuncOp` to prevent
crashes. Fixes #108390.
2024-10-04 19:51:09 +08:00
Tobias Gysi
751975530e
Reapply "[MLIR][LLVM] Make DISubprogramAttr cyclic" (#106571) with fixes (#106947)
This reverts commit fa93be4, restoring
commit d884b77, with fixes that ensure the CAPI declarations are
exported properly.

This commit implements LLVM_DIRecursiveTypeAttrInterface for the
DISubprogramAttr to ensure cyclic subprograms can be imported properly.
In the process multiple shortcuts around the recently introduced
DIImportedEntityAttr can be removed.
2024-09-02 12:26:15 +02:00
Tobias Gysi
fa93be4b1c
Revert "[MLIR][LLVM] Make DISubprogramAttr cyclic" (#106827)
Reverts llvm/llvm-project#106571

This commit breaks the following build bot:
https://lab.llvm.org/buildbot/#/builders/138/builds/2992
It looks like there is a missing dependency in this particular setup.
2024-08-31 07:51:53 +02:00
Tobias Gysi
d884b77c66
[MLIR][LLVM] Make DISubprogramAttr cyclic (#106571)
This commit implements LLVM_DIRecursiveTypeAttrInterface for the
DISubprogramAttr to ensure cyclic subprograms can be imported properly.
In the process multiple shortcuts around the recently introduced
DIImportedEntityAttr can be removed.
2024-08-31 07:23:24 +02:00
Observer007
097138f0ce
[mlir] Add option to control the emissionKind to DIScopeForLLVMFuncOp pass (#106229)
This is currently not controllable by the user and always set to
`DIEmissionKind::LineTablesOnly`.
The added option allows to set it to the other values accepted by LLVM
(`None`, `Full`, and `DebugDirectivesOnly`).

---------

Co-authored-by: jingzec <jingzec@nvidia.com>
2024-08-28 13:31:47 +08:00
Abid Qadeer
bc4bedd5ed
[mlir][debug] Handle DIImportedEntity. (#103055)
The `DIImporedEntity` can be used to represent imported entities like
C++'s namespace with using directive or fortran's moudule with use
statement.

This PR adds `DIImportedEntityAttr` and 2-way translation from
`DIImportedEntity` to `DIImportedEntityAttr` and vice versa.

When an entity is imported in a function, the `retainedNodes` field of
the `DISubprogram` contains all the imported nodes. See the C++ code and
the LLVM IR below.

```
void test() {
    using namespace n1;
 ...
}

!2 = !DINamespace(name: "n1", scope: null)
!16 = distinct !DISubprogram(name: "test", ..., retainedNodes: !19) !19 = !{!20}
!20 = !DIImportedEntity(tag: DW_TAG_imported_module, scope: !16, entity: !2 ...)
```

This PR makes sure that the translation from mlir to `retainedNodes`
field happens correctly both ways.

To side step the cyclic dependency between `DISubprogramAttr` and `DIImportedEntityAttr`,
we have decided to not have `scope` field in the `DIImportedEntityAttr` and it is inferred
from the entity which hold the list of `DIImportedEntityAttr`. A `retainedNodes` field has been
added in the `DISubprogramAttr` which contains the list of `DIImportedEntityAttr` for that
function.

This PR currently does not handle entities imported in a global scope
but that should be easy to handle in a subsequent PR.
2024-08-27 11:10:11 +01:00
Christian Ulmann
bf68e9047f
[MLIR] Introduce a SelectLikeOpInterface (#104751)
This commit introduces a `SelectLikeOpInterface` that can be used to
handle select-like operations generically. Select operations are similar
to control flow operations, as they forward operands depending on
conditions. This is the reason why it was placed to the already existing
control flow interfaces.
2024-08-20 07:32:12 +02:00
Christian Ulmann
065d2d9c60
[MLIR][LLVM] Improve the noalias propagation during inlining (#104750)
This commit changes the LLVM dialect's inliner interface to properly
propagate noalias information to memory accesses that have different
underlying object. By always introducing an SSACopy intrinsic, it's
possible to understand that specific memory operations are using
unrelated pointers. Previously, the backwards slice walk did continue
beyond the boundary of the original function and failed to reason about
the "underlying objects".
2024-08-19 11:27:30 +02:00
Christian Ulmann
141536544f
[MLIR][LLVM]: Add an IR utility to perform slice walking (#103053)
This commit introduces a slicing utility that can be used to walk
arbitrary IR slices. It additionally ships logic to determine control
flow predecessors, which allows users to walk backward slices without
dealing with both `RegionBranchOpInterface` and `BranchOpInterface`.

This utility is used to improve the `noalias` propagation in the LLVM
dialect's inliner interface. Before this change, it broke down as soon
as pointer were passed through region control flow operations.
2024-08-15 10:30:44 +02:00
Christian Ulmann
4c2f90f362
[MLIR][LLVM] Turn the inliner interface into a promised interface (#103927)
This commit changes the LLVM dialect's inliner interface to no longer be
registered at dialect initialization. Instead, it is now a promised
interface, that needs to be registered explicitly. This change is
desired to avoid pulling in a lot of dependencies into the
`MLIRLLVMDialect` library, especially considering future patches that
plan to extend it further with strong IR analysis.
2024-08-14 17:28:54 +02:00
Christian Ulmann
2171f34121
[MLIR][LLVM] Remove the type consistency pass (#93283)
This commit removes the LLVM dialect's type consistency pass. This pass
was originally introduced to make type information on memory operations
consistent. The main benefactor of this consistency where Mem2Reg and
SROA, which were in the meantime improved to no longer require
consistent type information.

Apart from providing a no longer required functionality, the pass had
some fundamental flaws that lead to issues:
* It introduced trivial GEPs (only zero indices) that could be folded
again.
* Aggressively splitting stores lead to substantial performance
regressions in some cases. Subsequent memory coalescing were not able to
recover this information, due to using non-trivial bit-fiddling.
2024-05-24 13:22:30 +02:00
Christian Sigg
a5757c5b65
Switch member calls to isa/dyn_cast/cast/... to free function calls. (#89356)
This change cleans up call sites. Next step is to mark the member
functions deprecated.

See https://mlir.llvm.org/deprecation and
https://discourse.llvm.org/t/preferred-casting-style-going-forward.
2024-04-19 15:58:27 +02:00
Billy Zhu
6f6336858e
[MLIR][LLVM] Add DebugNameTableKind to DICompileUnit (#87974)
Add the DebugNameTableKind field to DICompileUnit, along with its
importer & exporter.
2024-04-09 06:18:07 -07:00
Christian Ulmann
541962306d
[MLIR][LLVM] Remove bitcast pattern from type consistency pass (#87755)
This commit removes the no longer required bitcast inserting pattern in
LLVM dialect's type consistency pattern. This was previously required to
enable Mem2Reg and SROA to promote accesses that had different types.
Recent changes to both passes added direct support for this feature to
them, so the pattern has no further use.
2024-04-05 15:47:16 +02:00
Christian Ulmann
0289ae51aa
[MLIR][LLVM][SROA] Support incorrectly typed memory accesses (#85813)
This commit relaxes the assumption of type consistency for LLVM dialect
load and store operations in SROA. Instead, there is now a check that
loads and stores are in the bounds specified by the sub-slot they
access.

This commit additionally removes the corresponding patterns from the
type consistency pass, as they are no longer necessary.

Note: It will be necessary to extend Mem2Reg with the logic for
differently sized accesses as well. This is non-the-less a strict
upgrade for productive flows, as the type consistency pass can produce
invalid IR for some odd cases.
2024-03-22 08:31:17 +01:00
Andrei Golubev
89cd345667
[mlir][LLVM] Use int32_t to indirectly construct GEPArg (#79562)
GEPArg can only be constructed from int32_t and mlir::Value. Explicitly
cast other types (e.g. unsigned, size_t) to int32_t to avoid narrowing
conversion warnings on MSVC. Some recent examples of such are:

```
mlir\lib\Dialect\LLVMIR\Transforms\TypeConsistency.cpp: error C2398:
Element '1': conversion from 'size_t' to 'T' requires a narrowing
conversion
    with
    [
        T=mlir::LLVM::GEPArg
    ]

mlir\lib\Dialect\LLVMIR\Transforms\TypeConsistency.cpp: error C2398:
Element '1': conversion from 'unsigned int' to 'T' requires a narrowing
conversion
    with
    [
        T=mlir::LLVM::GEPArg
    ]
```

Co-authored-by: Nikita Kudriavtsev <nikita.kudriavtsev@intel.com>
2024-01-26 14:27:51 +01:00
Matthias Springer
5fcf907b34
[mlir][IR] Rename "update root" to "modify op" in rewriter API (#78260)
This commit renames 4 pattern rewriter API functions:
* `updateRootInPlace` -> `modifyOpInPlace`
* `startRootUpdate` -> `startOpModification`
* `finalizeRootUpdate` -> `finalizeOpModification`
* `cancelRootUpdate` -> `cancelOpModification`

The term "root" is a misnomer. The root is the op that a rewrite pattern
matches against
(https://mlir.llvm.org/docs/PatternRewriter/#root-operation-name-optional).
A rewriter must be notified of all in-place op modifications, not just
in-place modifications of the root
(https://mlir.llvm.org/docs/PatternRewriter/#pattern-rewriter). The old
function names were confusing and have contributed to various broken
rewrite patterns.

Note: The new function names use the term "modify" instead of "update"
for consistency with the `RewriterBase::Listener` terminology
(`notifyOperationModified`).
2024-01-17 11:08:59 +01:00
Christian Ulmann
fa5255eee2
[MLIR][LLVM] Enable export of DISubprograms on function declarations (#78026)
This commit changes the MLIR to LLVMIR export to also attach subprogram
debug attachements to function declarations.
This commit additonally fixes the two passes that produce subprograms to
not attach the "Definition" flag to function declarations. This
otherwise results in invalid LLVM IR.
2024-01-15 07:34:13 +01:00
Billy Zhu
422b84a771
[MLIR][LLVM] DI Expression Rewrite & Legalization (#77541)
Add a rewriter for DIExpressions & use it to run legalization patterns
before exporting to llvm (because LLVM dialect allows DI Expressions
that may not be valid in LLVM IR).

The rewriter driver works similarly to the existing mlir rewriter
drivers, except it operates on lists of DIExpressionElemAttr (i.e.
DIExpressionAttr). Each rewrite pattern transforms a range of
DIExpressionElemAttr into a new list of DIExpressionElemAttr.

In addition, this PR sets up a place to add legalization patterns that
are broadly applicable internally to the LLVM dialect, and they will
always be applied prior to export. This PR adds one pattern for merging
fragment operators.

---------

Co-authored-by: Tobias Gysi <tobias.gysi@nextsilicon.com>
2024-01-10 16:10:06 -08:00
Christian Ulmann
bae1fdea71
[MLIR][LLVM] Add distinct identifier to the DISubprogram attribute (#77093)
This commit adds an optional distinct attribute parameter to the
DISubprogramAttr. This enables modeling of distinct subprograms, as
required for LLVM IR. This change is required to avoid accidential
uniquing of subprograms on functions that would lead to invalid LLVM IR
post export.
2024-01-08 08:25:30 +01:00
Christian Ulmann
b3037ae1fc
[MLIR][LLVM] Add distinct identifier to DICompileUnit attribute (#77070)
This commit adds a distinct attribute parameter to the DICompileUnit to
enable the modeling of distinctness. LLVM requires DICompileUnits to be
distinct and there are cases where one gets two equivalent compilation
units but LLVM still requires differentiates them. We observed such
cases for combinations of LTO and inline functions.

This patch also changes the DIScopeForLLVMFuncOp pass to a module pass,
to ensure that only one distinct DICompileUnit is created, instead of
one for each function.
2024-01-08 07:42:33 +01:00
Rik Huijzer
3764f5e816
[mlir][llvm] Fix negative GEP crash in type consistency (#74859)
Fixes https://github.com/llvm/llvm-project/issues/74453.

The `gepToByteOffset` was implicitly casting an signed integer to an
unsigned integer even though negative dimensions are valid for
`llvm.getelementptr`.

---------

Co-authored-by: Tobias Gysi <tobias.gysi@nextsilicon.com>
2023-12-11 12:29:53 +01:00
Christian Ulmann
4983432f17
[MLIR][LLVM] Remove typed pointers from the LLVM dialect (#71285)
This commit removes the support for typed pointers from the LLVM
dialect. Typed pointers have been deprecated for a while and thus this
removal was announced in a PSA:

https://discourse.llvm.org/t/psa-removal-of-typed-pointers-from-the-llvm-dialect/74502

This change includes:
- Changing the ` LLVMPointerType`
- Removing remaining usages of the builders and the now removed element
type
- Fixing assembly formats that require fully qualified pointer types
- Updating ODS pointer constraints
2023-11-06 15:48:03 +01:00
David Truby
a6857156df
[mlir] Add pass to add comdat to all linkonce functions (#65270)
This adds a new pass to add an Any comdat to each linkonce
and linkonce_odr function in the LLVM dialect. These comdats are
necessary on Windows
to allow the default system linker to link binaries containing these
functions.
2023-09-13 13:05:05 +01:00
Markus Böck
569f073191 [mlir][LLVM] Add support for arrays in SplitStores pattern
The pattern so far has only supported splitting stores into struct types, marking arrays as explicitly unsupported. This would lead to stores into arrays not being made type-consistent like structs and therefore also not being properly split by SROA and mem2reg.

This patch adds support for array types by creating a common abstraction for both structs and arrays, making an array of size n essentially be treated like a struct with n fields of the arrays element type.
This gives us immediate feature parity without special casing for either of the types.

Differential Revision: https://reviews.llvm.org/D154840
2023-07-10 15:55:07 +02:00
Markus Böck
7786449334 [mlir][LLVM] Make SplitStores pattern capable of writing to sub-aggregates
The pattern was previously only capable of storing into struct fields which are primitive types. If the struct contained a nested struct it immediately aborted the pattern rewrite.

This patch introduces the capability of recursively splitting stores into sub-structs as well. This is achieved by splitting an aggregate sized integer from the original store argument and letting repeated pattern applications further split it into field stores.

Additionally, the pattern is also capable of handling partial writes into aggregates, which is a pattern clang may generate as well. Special care had to be taken to make sure no stores are created that weren't in the original code.

Differential Revision: https://reviews.llvm.org/D154707
2023-07-10 15:27:47 +02:00
Markus Böck
c10f8bd6c3 [mlir][LLVM] Add SplitGEP type-consistency pattern
The goal of this pattern is to eliminate all GEPs that have more than two indices by splitting it into multiple GEPs.
The advantage of this change is that the resulting GEPs only ever index into one aggregate at the time. This enables handling sub-aggregates in other patterns and also creates IR with easier to deduce pointer element types.

As a minor note, `getResultPtrElementType` for `GEPOp` was rewritten since it did not properly handle dynamic indices. The way GEPOp is specified, the resulting pointer element type can *always* be deduced from its base type and indices.

Differential Revision: https://reviews.llvm.org/D154692
2023-07-10 10:45:42 +02:00
Markus Böck
fd5387f44f [mlir][LLVM] Add BitcastStores type-consistency pattern
Current patterns attempt to immediately create type-consistent stores by bitcasting the value to the type-hint leading to needless code duplication.

This patch extracts that case into its own pattern, allowing other patterns to create type-inconsistent stores and have subsequent pattern applications turn it into a type-consistent store.

Differential Revision: https://reviews.llvm.org/D154587
2023-07-10 08:56:50 +02:00
Markus Böck
67c351f648 [mlir][LLVM] Make SplitIntegerStores capable of splitting vectors as well
The original plan was to turn this into its own pattern, but one of the difficulties was deeming when splitting the vector is required.
`SplitIntegerStores` essentially already did that by checking for field overlap.
Therefore, it was renamed to `SplitStores` and extended to splitting stores with values of vector and integer type.

The vector splitting is done in a simple manner by simply using `extractelement` to get each vector element. Subsequent pattern applications are responsible for further cleaning up the output and making it type-consistent.

Worst case, if the code cannot be transformed into a type-consistent form (due to e.g. the code explicitly doing partial writes to elements or similar), we might needlessly do a vector split.

Differential Revision: https://reviews.llvm.org/D154583
2023-07-06 15:39:41 +02:00
Markus Böck
f6df11568e [mlir][llvm] add basic type consistency pattern destructuring stores
This is a common pattern produced by clang and similar.
Essentially, it coalesces stores into adjacent integer fields into a single integer store.
This violates our definition of type-consistency that the pass is supposed to enforce and also prevents SROA and mem2reg from eliminating `alloca`s.

This patch fixes that by splitting these stores into multiple stores.
It does so by simply using logical shift rights and truncating the produced value to the size of the field, optionally bitcasting before storing into the field.

The implementation is currently very simple, only working on struct types of a single depth and adjacent fields in that struct, with no padding inbetween. Future work could improve on these once required.

Differential Revision: https://reviews.llvm.org/D154449
2023-07-05 13:57:08 +02:00
Théo Degioanni
fb047e4ae1 [mlir][llvm] Type consistency transformations
This revision introduces new rewrites to improve the type consistency of
a program expressed in the LLVM dialect.

Type consistency means that a given opaque pointer is consistently used
assuming the same pointee type, in a best effort basis. The introduced
rewrites modify the program to improve type consistency while preserving
the same semantics. This is useful for two main reasons:

- Transformation passes in the LLVM dialect like SROA or Mem2Reg can
  analyse code better if type information and structure is used in a
  consistent manner. Opaque pointers make this difficult to enforce, but
  type consistency improvements increase the amount of occurences where
  reasonable analysis can pick up on transformable patterns.
- While LLVM IR is not particularly picky about inconsistent type uses,
  it may be of interest to lift LLVM IR into higher level dialects.
  Having more instances of consistent type information would help
  lifting into dialects that do care about consistent types.

In order to detect cases of inconsistent uses, operations returning an
LLVMPointer can implement the GetResultPtrElementType interface, which
allows getting a hint of which type the provided pointer should see its
pointee as, if such hint is available. The provided rewrites will then
use this hint to attempt to modify operations using the pointers so they
use the hinted type when dealing with the pointer.

Two transformations have been implemented in this revision:

- When a load/store uses a struct ptr directly to write to the first
  element of the struct, introduce a GEP to the first element so the
  type structure is preserved.
- When a GEP statically indexes in a pointer with a base type
  inconsistent with the hint, try to find indices using the hint as a
  base type that would result in the same offset, and replace the GEP
  with this indexing.

More transformations are possible and I hope this is only a beginning
for this simplification effort.

Reviewed By: gysit

Differential Revision: https://reviews.llvm.org/D153973
2023-07-03 11:12:39 +02:00
Tres Popp
5550c82189 [mlir] Move casting calls from methods to function calls
The MLIR classes Type/Attribute/Operation/Op/Value support
cast/dyn_cast/isa/dyn_cast_or_null functionality through llvm's doCast
functionality in addition to defining methods with the same name.
This change begins the migration of uses of the method to the
corresponding function call as has been decided as more consistent.

Note that there still exist classes that only define methods directly,
such as AffineExpr, and this does not include work currently to support
a functional cast/isa call.

Caveats include:
- This clang-tidy script probably has more problems.
- This only touches C++ code, so nothing that is being generated.

Context:
- https://mlir.llvm.org/deprecation/ at "Use the free function variants
  for dyn_cast/cast/isa/…"
- Original discussion at https://discourse.llvm.org/t/preferred-casting-style-going-forward/68443

Implementation:
This first patch was created with the following steps. The intention is
to only do automated changes at first, so I waste less time if it's
reverted, and so the first mass change is more clear as an example to
other teams that will need to follow similar steps.

Steps are described per line, as comments are removed by git:
0. Retrieve the change from the following to build clang-tidy with an
   additional check:
   https://github.com/llvm/llvm-project/compare/main...tpopp:llvm-project:tidy-cast-check
1. Build clang-tidy
2. Run clang-tidy over your entire codebase while disabling all checks
   and enabling the one relevant one. Run on all header files also.
3. Delete .inc files that were also modified, so the next build rebuilds
   them to a pure state.
4. Some changes have been deleted for the following reasons:
   - Some files had a variable also named cast
   - Some files had not included a header file that defines the cast
     functions
   - Some files are definitions of the classes that have the casting
     methods, so the code still refers to the method instead of the
     function without adding a prefix or removing the method declaration
     at the same time.

```
ninja -C $BUILD_DIR clang-tidy

run-clang-tidy -clang-tidy-binary=$BUILD_DIR/bin/clang-tidy -checks='-*,misc-cast-functions'\
               -header-filter=mlir/ mlir/* -fix

rm -rf $BUILD_DIR/tools/mlir/**/*.inc

git restore mlir/lib/IR mlir/lib/Dialect/DLTI/DLTI.cpp\
            mlir/lib/Dialect/Complex/IR/ComplexDialect.cpp\
            mlir/lib/**/IR/\
            mlir/lib/Dialect/SparseTensor/Transforms/SparseVectorization.cpp\
            mlir/lib/Dialect/Vector/Transforms/LowerVectorMultiReduction.cpp\
            mlir/test/lib/Dialect/Test/TestTypes.cpp\
            mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp\
            mlir/test/lib/Dialect/Test/TestAttributes.cpp\
            mlir/unittests/TableGen/EnumsGenTest.cpp\
            mlir/test/python/lib/PythonTestCAPI.cpp\
            mlir/include/mlir/IR/
```

Differential Revision: https://reviews.llvm.org/D150123
2023-05-12 11:21:25 +02:00
Mehdi Amini
72429a42ac Add a pass that builds a debug info scope for LLVMFuncOp (adding a DISubprogramAttr)
This may be seen as a hack, but it allows for any piece of MLIR to be able
to end up with DWARF debug info through LLVM.
Assuming the operations in the function have location such as FileLineCol,
this provides backtraces with line tables and allows to step in a debugger.
That makes this pass a perfect companion to -snapshot-op-locations

It was also the default behavior of MLIR to LLVM IR translation until MLIR
got support for proper debug info attributes.

Differential Revision: https://reviews.llvm.org/D144069
2023-02-14 22:43:26 -08:00