Commit Graph

471 Commits

Author SHA1 Message Date
Tobias Gysi
f809eb4db2 [mlir] Argument and result attribute handling during inlining.
The revision adds the handleArgument and handleResult handlers that
allow users of the inlining interface to implement argument and result
conversions that take argument and result attributes into account. The
motivating use cases for this revision are taken from the LLVM dialect
inliner, which has to copy arguments that are marked as byval and that
also has to consider zeroext / signext when converting integers.

All type conversions are currently handled by the
materializeCallConversion hook. It runs before isLegalToInline and
supports only the introduction of a single cast operation since it may
have to rollback. The new handlers run shortly before and after
inlining and cannot fail. As a result, they can introduce more complex
ir such as copying a struct argument. At the moment, the new hooks
cannot be used to perform type conversions since all type conversions
have to be done using the materializeCallConversion. A follow up
revision will either relax this constraint or drop
materializeCallConversion in favor of the new and more flexible
handlers.

The revision also extends the CallableOpInterface to provide access
to the argument and result attributes if available.

Reviewed By: rriddle, Dinistro

Differential Revision: https://reviews.llvm.org/D145582
2023-03-22 09:02:15 +01:00
Sergio Afonso
0e9523efda [mlir] Support lowering of dialect attributes attached to top-level modules
This patch supports the processing of dialect attributes attached to top-level
module-type operations during MLIR-to-LLVMIR lowering.

This approach modifies the `mlir::translateModuleToLLVMIR()` function to call
`ModuleTranslation::convertOperation()` on the top-level operation, after its
body has been lowered. This, in turn, will get the
`LLVMTranslationDialectInterface` object associated to that operation's dialect
before trying to use it for lowering prior to processing dialect attributes
attached to the operation.

Since there are no `LLVMTranslationDialectInterface`s for the builtin and GPU
dialects, which define their own module-type operations, this patch also adds
and registers them. The requirement for always calling
`mlir::registerBuiltinDialectTranslation()` before any translation of MLIR to
LLVM IR where builtin module operations are present is introduced. The purpose
of these new translation interfaces is to succeed when processing module-type
operations, allowing the lowering process to continue and to prevent the
introduction of failures related to not finding such interfaces.

Differential Revision: https://reviews.llvm.org/D145932
2023-03-21 12:54:26 +00:00
Mark de Wever
d0398d3593 Revert "Reland "[CMake] Bumps minimum version to 3.20.0.""
This reverts commit a72165e5df.

Some buildbots have not been updated yet.
2023-03-18 20:32:43 +01:00
Mark de Wever
a72165e5df Reland "[CMake] Bumps minimum version to 3.20.0."
This reverts commit 92523a35a8.

Test whether all CI runners are updated.
2023-03-18 13:33:42 +01:00
Mehdi Amini
7de0804ea3 Make mlir-opt --show-dialects option print on a single line
Differential Revision: https://reviews.llvm.org/D145398
2023-03-08 01:17:51 +01:00
Mark de Wever
92523a35a8 Revert "[CMake] Bumps minimum version to 3.20.0."
Some build bots have not been updated to the new minimal CMake version.
Reverting for now and ping the buildbot owners.

This reverts commit 44c6b905f8.
2023-03-04 18:28:13 +01:00
Mark de Wever
44c6b905f8 [CMake] Bumps minimum version to 3.20.0.
This partly undoes D137724.

This change has been discussed on discourse
https://discourse.llvm.org/t/rfc-upgrading-llvms-minimum-required-cmake-version/66193

Note this does not remove work-arounds for older CMake versions, that
will be done in followup patches.

Reviewed By: mehdi_amini, MaskRay, ChuanqiXu, to268, thieta, tschuett, phosek, #libunwind, #libc_vendors, #libc, #libc_abi, sivachandra, philnik, zibi

Differential Revision: https://reviews.llvm.org/D144509
2023-03-04 12:40:57 +01:00
Marius Brehler
7c081a5675 [mlir][standalone] Enable to build as LLVM external project
In addition to the component build, this enables the standalone example
to be build as part of a monolithic LLVM build by using the LLVM
external projects mechanism (`LLVM_EXTERNAL_PROJECTS`).

Reviewed By: stephenneuendorffer, stellaraccident

Differential Revision: https://reviews.llvm.org/D143718
2023-03-01 14:15:17 +01:00
Marius Brehler
83e9ef7e51 [mlir][standalone] Extend sample with custom type
This extends the standalone example to illustrate how to structure the
files needed to create own types.

Reviewed By: jpienaar

Differential Revision: https://reviews.llvm.org/D143715
2023-02-17 15:14:56 +01: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
Markus Böck
ad48a0e573 [mlir] Switch default Fold API to using FoldAdaptors
As mentioned in https://discourse.llvm.org/t/psa-new-improved-fold-method-signature-has-landed-please-update-your-downstream-projects/67618, it has now been about one month since the new fold API has been introduced.

Any downstream users that have not yet switched, nor explicitly set useFoldAPI to kEmitRawAttributesFolder will experience a build break after this patch, requiring them to either switch to the new API or explicitly use the old one and live with the warning set by TableGen.

Differential Revision: https://reviews.llvm.org/D143497
2023-02-07 16:48:58 +01:00
Rahul Kayaith
0ce25b1235 [mlir] Require explicit casts when using TypedValue
Currently `TypedValue` can be constructed directly from `Value`, hiding
errors that could be caught at compile time. For example the following
will compile, but crash/assert at runtime:
```
void foo(TypedValue<IntegerType>);
void bar(TypedValue<FloatType> v) {
  foo(v);
}
```

This change removes the constructors and replaces them with explicit
llvm casts.

Depends on D142852

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D142855
2023-02-01 21:54:53 -05:00
Marius Brehler
75488a287b [mlir][nfc] Migrate standalone to new fold API
Migrates the standalone sample/dialect to the new fold API, see
https://discourse.llvm.org/t/psa-new-improved-fold-method-signature-has-landed-please-update-your-downstream-projects/67618
2023-01-30 10:05:59 +00:00
Quentin Colombet
cb4ccd38fa [mlir][Conversion] Rename the MemRefToLLVM pass
Since the recent MemRef refactoring that centralizes the lowering of
complex MemRef operations outside of the conversion framework, the
MemRefToLLVM pass doesn't directly convert these complex operations.

Instead, to fully convert the whole MemRef dialect space, MemRefToLLVM
needs to run after `expand-strided-metadata`.

Make this more obvious by changing the name of the pass and the option
associated with it from `convert-memref-to-llvm` to
`finalize-memref-to-llvm`.
The word "finalize" conveys that this pass needs to run after something
else and that something else is documented in its tablegen description.

This is a follow-up patch related to the conversation at:
https://discourse.llvm.org/t/psa-you-need-to-run-expand-strided-metadata-before-memref-to-llvm-now/66956/14

Differential Revision: https://reviews.llvm.org/D142463
2023-01-27 09:10:10 +00:00
rkayaith
94a309284d [mlir][Pass] Make PassManager default to op-agnostic
Currently `PassManager` defaults to being anchored on `builtin.module`.
Switching the default makes `PassManager` consistent with
`OpPassManager` and avoids the implicit dependency on `builtin.module`.

Specifying the anchor op type isn't strictly necessary when using
explicit nesting (existing pipelines will continue to work), but I've
updated most call sites to specify the anchor since it allows for better
error-checking during pipeline construction.

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D137731
2023-01-25 15:38:19 -05:00
Mehdi Amini
177a0e5916 Fix running MLIR tests when enabling examples but the native backends isn't configured (NFC) 2023-01-24 20:32:51 -08:00
River Riddle
b2bdb0ba0f [mlir] Make FunctionOpInterface inherit SymbolOpInterface
This lets users of FunctionOpInterface finally have the
name/visibility accessors from SymbolOpInterface. This also
lets us remove the clunky "getName" method from FunctionOpInterface.

Differential Revision: https://reviews.llvm.org/D140199
2023-01-18 19:16:30 -08:00
Markus Böck
355c547908 [mlir][NFC] Set useFoldAPI to kEmitRawAttributesFolder value for some dialects missed previously
Found these while working on https://reviews.llvm.org/D141604. These were previously not found due to the old implementation only emitting warnings if an Op has a `fold`.

Changing these values both avoid the deprecation warning and if new `fold`s were added to ops of these dialects, that they are already using the new API.

Differential Revision: https://reviews.llvm.org/D141795
2023-01-16 11:48:30 +01:00
Kazu Hirata
2140260d91 [mlir] Remove remaining uses of llvm::Optional (NFC)
This patch removes one "using" declaration and #include
"llvm/ADT/Optional.h".  It keeps several "using" declarations in
headers for downstream users.

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14 01:34:49 -08:00
Kazu Hirata
0a81ace004 [mlir] Use std::optional instead of llvm::Optional (NFC)
This patch replaces (llvm::|)Optional< with std::optional<.  I'll post
a separate patch to remove #include "llvm/ADT/Optional.h".

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14 01:25:58 -08:00
Kazu Hirata
a1fe1f5f77 [mlir] Add #include <optional> (NFC)
This patch adds #include <optional> to those files containing
llvm::Optional<...> or Optional<...>.

I'll post a separate patch to actually replace llvm::Optional with
std::optional.

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-13 21:05:06 -08:00
Jeff Niu
4d67b27817 [mlir] Add operations to BlockAndValueMapping and rename it to IRMapping
The patch adds operations to `BlockAndValueMapping` and renames it to `IRMapping`. When operations are cloned, old operations are mapped to the cloned operations. This allows mapping from an operation to a cloned operation. Example:

```
Operation *opWithRegion = ...
Operation *opInsideRegion = &opWithRegion->front().front();

IRMapping map
Operation *newOpWithRegion = opWithRegion->clone(map);
Operation *newOpInsideRegion = map.lookupOrNull(opInsideRegion);
```

Migration instructions:
All includes to `mlir/IR/BlockAndValueMapping.h` should be replaced with `mlir/IR/IRMapping.h`. All uses of `BlockAndValueMapping` need to be renamed to `IRMapping`.

Reviewed By: rriddle, mehdi_amini

Differential Revision: https://reviews.llvm.org/D139665
2023-01-12 13:16:05 -08:00
Markus Böck
bbfa7ef16d [mlir] Add a new fold API using Generic Adaptors
This is part of the RFC for a better fold API: https://discourse.llvm.org/t/rfc-a-better-fold-api-using-more-generic-adaptors/67374

This patch implements the required foldHook changes and the TableGen machinery for generating `fold` method signatures using `FoldAdaptor` for ops, based on the value of `useFoldAPI` of the dialect. It may be one of 2 values, with convenient named constants to create a quasi enum. The new `fold` method will then be generated if `kEmitFoldAdaptorFolder` is used.

Since the new `FoldAdaptor` approach is strictly better than the old signature, part of this patch updates the documentation and all example to encourage use of the new `fold` signature.
Included are also tests exercising the new API, ensuring proper construction of the `FoldAdaptor` and proper generation by TableGen.

Differential Revision: https://reviews.llvm.org/D140886
2023-01-11 14:32:21 +01:00
serge-sans-paille
984b800a03
Move from llvm::makeArrayRef to ArrayRef deduction guides - last part
This is a follow-up to https://reviews.llvm.org/D140896, split into
several parts as it touches a lot of files.

Differential Revision: https://reviews.llvm.org/D141298
2023-01-10 11:47:43 +01:00
Fangrui Song
76b1100372 [mlir] llvm::Optional::value() && => operator*/operator->
std::optional::value() has undesired exception checking semantics and is
unavailable in older Xcode (see _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS). The
call sites block std::optional migration.
2022-12-17 19:23:50 +00:00
Jeff Niu
53406427cd [mlir] FunctionOpInterface: turn required attributes into interface methods (Reland)
Reland D139447, D139471 With flang actually working

- FunctionOpInterface: make get/setFunctionType interface methods

This patch removes the concept of a `function_type`-named type attribute
as a requirement for implementors of FunctionOpInterface. Instead, this
type should be provided through two interface methods, `getFunctionType`
and `setFunctionTypeAttr` (*Attr because functions may use different
concrete function types), which should be automatically implemented by
ODS for ops that define a `$function_type` attribute.

This also allows FunctionOpInterface to materialize function types if
they don't carry them in an attribute, for example.

Importantly, all the function "helper" still accept an attribute name to
use in parsing and printing functions, for example.

- FunctionOpInterface: arg and result attrs dispatch to interface

This patch removes the `arg_attrs` and `res_attrs` named attributes as a
requirement for FunctionOpInterface and replaces them with interface
methods for the getters, setters, and removers of the relevent
attributes. This allows operations to use their own storage for the
argument and result attributes.

Reviewed By: jpienaar

Differential Revision: https://reviews.llvm.org/D139736
2022-12-10 15:17:09 -08:00
David Spickett
cf98e8273c Revert "[mlir] FunctionOpInterface: make get/setFunctionType interface methods"
and "[mlir] Fix examples build"

This reverts commit fbc253fe81 and
96cf183bcc.

Which I missed in the first revert in f3379feabe.
2022-12-09 15:36:48 +00:00
David Spickett
f3379feabe Revert "[mlir] FunctionOpInterface: arg and result attrs dispatch to interface"
and "[flang] Fix flang after MLIR update"

This reverts commit dd74e6b6f4 and
1897b67ae8 due to ongoing test failures on flang
bots e.g. https://lab.llvm.org/buildbot/#/builders/179/builds/5050
2022-12-09 15:02:39 +00:00
Jeff Niu
96cf183bcc [mlir] Fix examples build
Missing two extra parameters.
2022-12-08 21:32:58 -08:00
Jeff Niu
dd74e6b6f4 [mlir] FunctionOpInterface: arg and result attrs dispatch to interface
This patch removes the `arg_attrs` and `res_attrs` named attributes as a
requirement for FunctionOpInterface and replaces them with interface
methods for the getters, setters, and removers of the relevent
attributes. This allows operations to use their own storage for the
argument and result attributes.

Depends on D139471

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D139472
2022-12-08 11:32:38 -08:00
Jeff Niu
fbc253fe81 [mlir] FunctionOpInterface: make get/setFunctionType interface methods
This patch removes the concept of a `function_type`-named type attribute
as a requirement for implementors of FunctionOpInterface. Instead, this
type should be provided through two interface methods, `getFunctionType`
and `setFunctionTypeAttr` (*Attr because functions may use different
concrete function types), which should be automatically implemented by
ODS for ops that define a `$function_type` attribute.

This also allows FunctionOpInterface to materialize function types if
they don't carry them in an attribute, for example.

Importantly, all the function "helper" still accept an attribute name to
use in parsing and printing functions, for example.

Reviewed By: rriddle, lattner

Differential Revision: https://reviews.llvm.org/D139447
2022-12-08 11:32:27 -08:00
Kazu Hirata
e823abab48 [mlir] Use std::nullopt instead of None in comments (NFC)
This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-12-06 00:03:44 -08:00
Mehdi Amini
5060abb6d3 Apply clang-tidy fixes for readability-identifier-naming in StandaloneExtension.cpp (NFC) 2022-11-17 06:23:30 +00:00
rkayaith
ed90f8026e [mlir-translate] Support parsing operations other than 'builtin.module' as top-level
This adds a '--no-implicit-module' option, which disables the insertion
of a top-level 'builtin.module' during parsing.

The translation APIs are also updated to take/return 'Operation*'
instead of 'ModuleOp', to allow other operation types to be used. To
simplify translations which are restricted to specific operation types,
'TranslateFromMLIRRegistration' has an overload which performs the
necessary cast and error checking.

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D134237
2022-10-21 15:54:06 -04:00
Sanjoy Das
86771d0b65 Introduce a ConditionallySpeculatable op interface
This patch takes the first step towards a more principled modeling of undefined behavior in MLIR as discussed in the following discourse threads:

 1. https://discourse.llvm.org/t/semantics-modeling-undefined-behavior-and-side-effects/4812
 2. https://discourse.llvm.org/t/rfc-mark-tensor-dim-and-memref-dim-as-side-effecting/65729

This patch in particular does the following:

 1. Introduces a ConditionallySpeculatable OpInterface that dynamically determines whether an Operation can be speculated.
 2. Re-defines `NoSideEffect` to allow undefined behavior, making it necessary but not sufficient for speculation.  Also renames it to `NoMemoryEffect`.
 3. Makes LICM respect the above semantics.
 4. Changes all ops tagged with `NoSideEffect` today to additionally implement ConditionallySpeculatable and mark themselves as always speculatable.  This combined trait is named `Pure`.  This makes this change NFC.

For out of tree dialects:

 1. Replace `NoSideEffect` with `Pure` if the operation does not have any memory effects, undefined behavior or infinite loops.
 2. Replace `NoSideEffect` with `NoSideEffect` otherwise.

The next steps in this process are (I'm proposing to do these in upcoming patches):

 1. Update operations like `tensor.dim`, `memref.dim`, `scf.for`, `affine.for` to implement a correct hook for `ConditionallySpeculatable`.  I'm also happy to update ops in other dialects if the respective dialect owners would like to and can give me some pointers.
 2. Update other passes that speculate operations to consult `ConditionallySpeculatable` in addition to `NoMemoryEffect`.  I could not find any other than LICM on a quick skim, but I could have missed some.
 3. Add some documentation / FAQs detailing the differences between side effects, undefined behavior, speculatabilty.

Reviewed By: rriddle, mehdi_amini

Differential Revision: https://reviews.llvm.org/D135505
2022-10-12 10:56:12 -07:00
changkaiyan
c4cc755c72 [mlir][mlir-translation] patch for standalone-translation command line description missing.
Differential Revision: https://reviews.llvm.org/D134696

	modified:   mlir/examples/standalone/standalone-translate/standalone-translate.cpp
	modified:   mlir/include/mlir/Tools/mlir-translate/Translation.h
	modified:   mlir/lib/Target/Cpp/TranslateRegistration.cpp
	modified:   mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp
	modified:   mlir/lib/Target/LLVMIR/ConvertToLLVMIR.cpp
	modified:   mlir/lib/Target/SPIRV/TranslateRegistration.cpp
	modified:   mlir/lib/Tools/mlir-translate/Translation.cpp
2022-10-04 09:14:40 +08:00
Jakub Kuderski
abc362a107 [mlir][arith] Change dialect name from Arithmetic to Arith
Suggested by @lattner in https://discourse.llvm.org/t/rfc-define-precise-arith-semantics/65507/22.

Tested with:
`ninja check-mlir check-mlir-integration check-mlir-mlir-spirv-cpu-runner check-mlir-mlir-vulkan-runner check-mlir-examples`

and `bazel build --config=generic_clang @llvm-project//mlir:all`.

Reviewed By: lattner, Mogball, rriddle, jpienaar, mehdi_amini

Differential Revision: https://reviews.llvm.org/D134762
2022-09-29 11:23:28 -04:00
River Riddle
bb6d12b5ce [mlir] Flip default value of emitAccessorPrefix to kEmitAccessorPrefix_Prefixed
Most dialects have already flipped to prefixed, and the intention to switch
has been telegraphed for a while.

Differential Revision: https://reviews.llvm.org/D133179
2022-09-06 15:56:57 -07:00
Christian Sigg
9f358c8ef7 Resubmit "[MLIR] Remove unused config attributes from lit.site.cfg.py"
This resubmits commit 0816b62, reverted in commit 328bbab, but without removing the config.target_triple.

Lit checks UNSUPPORTED tags in the input against the config.target_triple (https://llvm.org/docs/TestingGuide.html#constraining-test-execution).

The original commit made the following bots start failing, because unsupported tests were no longer skipped:
- s390x: https://lab.llvm.org/buildbot/#/builders/199/builds/9247
- Windows: https://lab.llvm.org/buildbot/#/builders/13/builds/25321
- Sanitizer: https://lab.llvm.org/buildbot/#/builders/5/builds/27187
2022-09-03 09:02:37 +02:00
Mitch Phillips
328bbab542 Revert "[MLIR] Remove unused config attributes from lit.site.cfg.py"
This reverts commit 0816b629c9.

Reason: Broke the sanitizer buildbots. More information available in the
original phabricator review: https://reviews.llvm.org/D132726
2022-09-02 14:40:28 -07:00
Christian Sigg
0816b629c9 [MLIR] Remove unused config attributes from lit.site.cfg.py
Reviewed By: herhut

Differential Revision: https://reviews.llvm.org/D132726
2022-09-02 11:05:39 +02:00
Jeff Niu
2f0e50c69b [mlir] Fix build of toyc-ch6 (NFC) 2022-08-09 15:58:49 -04:00
Jeff Niu
0af643f3ce [mlir][LLVMIR] (NFC) Add convenience builders for ConstantOp
And clean up some of the user code
2022-08-09 15:34:36 -04:00
Markus Böck
26d811b3ec [mlir] Make use of C++17 language features
Now that C++17 is enabled in LLVM, a lot of the TODOs and patterns to emulate C++17 features can be eliminated.
The steps I have taken were essentially:
```
git grep C++17
git grep c++17
git grep "initializer_list<int>"
```
and address given comments and patterns.
Most of the changes boiled down to just using fold expressions rather than initializer_list.

While doing this I also discovered that Clang by default restricts the depth of fold expressions to 256 elements. I specifically hit this with `TestDialect` in `addOperations`. I opted to not replace it with fold expressions because of that but instead adding a comment documenting the issue.
If any other functions may be called with more than 256 elements in the future we might have to revert other parts as well.
I don't think this is a common occurence besides the `TestDialect` however. If need be, this could potentially be fixed via `mlir-tblgen` in the future.

Differential Revision: https://reviews.llvm.org/D131323
2022-08-07 11:16:49 +02:00
Fangrui Song
7430894a65 Replace Optional::hasValue with has_value or operator bool. NFC 2022-07-29 10:57:25 -07:00
Fangrui Song
0595edd80f [mlir][toy] Replace Optional::getValue with value. NFC 2022-07-29 01:10:51 -07:00
Mehdi Amini
d04c2b2fd9 Revert "[MLIR] Generic 'malloc', 'aligned_alloc' and 'free' functions"
This reverts commit 3e21fb616d.

A lot of integration tests are failing on the bot.
2022-07-18 18:07:36 +00:00
Michele Scuttari
3e21fb616d [MLIR] Generic 'malloc', 'aligned_alloc' and 'free' functions
When converted to the LLVM dialect, the memref.alloc and memref.free operations were generating calls to hardcoded 'malloc' and 'free' functions. This didn't leave any freedom to users to provide their custom implementation. Those operations now convert into calls to '_mlir_alloc' and '_mlir_free' functions, which have also been implemented into the runtime support library as wrappers to 'malloc' and 'free'. The same has been done for the 'aligned_alloc' function.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D128791
2022-07-18 17:58:58 +02:00
Stella Laurenzo
5e83a5b475 [mlir] Overhaul C/Python registration APIs to properly scope registration/loading activities.
Since the very first commits, the Python and C MLIR APIs have had mis-placed registration/load functionality for dialects, extensions, etc. This was done pragmatically in order to get bootstrapped and then just grew in. Downstreams largely bypass and do their own thing by providing various APIs to register things they need. Meanwhile, the C++ APIs have stabilized around this and it would make sense to follow suit.

The thing we have observed in canonical usage by downstreams is that each downstream tends to have native entry points that configure its installation to its preferences with one-stop APIs. This patch leans in to this approach with `RegisterEverything.h` and `mlir._mlir_libs._mlirRegisterEverything` being the one-stop entry points for the "upstream packages". The `_mlir_libs.__init__.py` now allows customization of the environment and Context by adding "initialization modules" to the `_mlir_libs` package. If present, `_mlirRegisterEverything` is treated as such a module. Others can be added by downstreams by adding a `_site_initialize_{i}.py` module, where '{i}' is a number starting with zero. The number will be incremented and corresponding module loaded until one is not found. Initialization modules can:

* Perform load time customization to the global environment (i.e. registering passes, hooks, etc).
* Define a `register_dialects(registry: DialectRegistry)` function that can extend the `DialectRegistry` that will be used to bootstrap the `Context`.
* Define a `context_init_hook(context: Context)` function that will be added to a list of callbacks which will be invoked after dialect registration during `Context` initialization.

Note that the `MLIRPythonExtension.RegisterEverything` is not included by default when building a downstream (its corresponding behavior was prior). For downstreams which need the default MLIR initialization to take place, they must add this back in to their Python CMake build just like they add their own components (i.e. to `add_mlir_python_common_capi_library` and `add_mlir_python_modules`). It is perfectly valid to not do this, in which case, only the things explicitly depended on and initialized by downstreams will be built/packaged. If the downstream has not been set up for this, it is recommended to simply add this back for the time being and pay the build time/package size cost.

CMake changes:
* `MLIRCAPIRegistration` -> `MLIRCAPIRegisterEverything` (renamed to signify what it does and force an evaluation: a number of places were incidentally linking this very expensive target)
* `MLIRPythonSoure.Passes` removed (without replacement: just drop)
* `MLIRPythonExtension.AllPassesRegistration` removed (without replacement: just drop)
* `MLIRPythonExtension.Conversions` removed (without replacement: just drop)
* `MLIRPythonExtension.Transforms` removed (without replacement: just drop)

Header changes:
* `mlir-c/Registration.h` is deleted. Dialect registration functionality is now in `IR.h`. Registration of upstream features are in `mlir-c/RegisterEverything.h`. When updating MLIR and a couple of downstreams, I found that proper usage was commingled so required making a choice vs just blind S&R.

Python APIs removed:
  * mlir.transforms and mlir.conversions (previously only had an __init__.py which indirectly triggered `mlirRegisterTransformsPasses()` and `mlirRegisterConversionPasses()` respectively). Downstream impact: Remove these imports if present (they now happen as part of default initialization).
  * mlir._mlir_libs._all_passes_registration, mlir._mlir_libs._mlirTransforms, mlir._mlir_libs._mlirConversions. Downstream impact: None expected (these were internally used).

C-APIs changed:
  * mlirRegisterAllDialects(MlirContext) now takes an MlirDialectRegistry instead. It also used to trigger loading of all dialects, which was already marked with a TODO to remove -- it no longer does, and for direct use, dialects must be explicitly loaded. Downstream impact: Direct C-API users must ensure that needed dialects are loaded or call `mlirContextLoadAllAvailableDialects(MlirContext)` to emulate the prior behavior. Also see the `ir.c` test case (e.g. `  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));`).
  * mlirDialectHandle* APIs were moved from Registration.h (which now is restricted to just global/upstream registration) to IR.h, arguably where it should have been. Downstream impact: include correct header (likely already doing so).

C-APIs added:
  * mlirContextLoadAllAvailableDialects(MlirContext): Corresponds to C++ API with the same purpose.

Python APIs added:
  * mlir.ir.DialectRegistry: Mapping for an MlirDialectRegistry.
  * mlir.ir.Context.append_dialect_registry(MlirDialectRegistry)
  * mlir.ir.Context.load_all_available_dialects()
  * mlir._mlir_libs._mlirAllRegistration: New native extension that exposes a `register_dialects(MlirDialectRegistry)` entry point and performs all upstream pass/conversion/transforms registration on init. In this first step, we eagerly load this as part of the __init__.py and use it to monkey patch the Context to emulate prior behavior.
  * Type caster and capsule support for MlirDialectRegistry

This should make it possible to build downstream Python dialects that only depend on a subset of MLIR. See: https://github.com/llvm/llvm-project/issues/56037

Here is an example PR, minimally adapting IREE to these changes: https://github.com/iree-org/iree/pull/9638/files In this situation, IREE is opting to not link everything, since it is already configuring the Context to its liking. For projects that would just like to not think about it and pull in everything, add `MLIRPythonExtension.RegisterEverything` to the list of Python sources getting built, and the old behavior will continue.

Reviewed By: mehdi_amini, ftynse

Differential Revision: https://reviews.llvm.org/D128593
2022-07-16 17:27:50 -07:00
Jeff Niu
b7f93c2809 [mlir] (NFC) run clang-format on all files 2022-07-14 13:32:13 -07:00