Structured control flow ops have proven very useful for many transformations doing analysis on conditional flow and loops. Doing these transformations on CFGs requires repeated analysis of the IR possibly leading to more complicated or less capable implementations. With structured control flow, a lot of the information is already present in the structure.
This patch therefore adds a transformation making it possible to lift arbitrary control flow graphs to structured control flow operations. The algorithm used is outlined in https://dl.acm.org/doi/10.1145/2693261. The complexity in implementing the algorithm was mostly spent correctly handling block arguments in MLIR (the paper only addresses the control flow graph part of it).
Note that the transformation has been implemented fully generically and does not depend on any dialect. An interface implemented by the caller is used to construct any operation necessary for the transformation, making it possible to create an interface implementation purpose fit for ones IR.
For the purpose of testing and due to likely being a very common scenario, this patch adds an interface implementation lifting the control flow dialect to the SCF dialect.
Note the use of the word "lifting". Unlike other conversion passes, this pass is not 100% guaranteed to convert all ControlFlow ops.
Only if the input region being transformed contains a single kind of return-like operations is it guaranteed to replace all control flow ops. If that is not the case, exactly one control flow op will remain branching to regions terminating with a given return-like operation (e.g. one region terminates with llvm.return the other with llvm.unreachable).
Additional notes:
Special thanks to the numba-mlir developers for the inspiration and some valuable testcases.
Their implementation of the same algorithm can be found here https://github.com/numba/numba-mlir/blob/9a3356a7d0ab99c69591fd5d26a98a9c5b93133a/mlir/lib/Conversion/CfgToScf.cpp
No code has been taken from their implementation, however.
I am also unsure who else is interested in such a pass, feel free to add more reviewers if anyone knows.
Would it make sense to prefix all methods that create SCF operation with SCF? E.g., for this one it may make sense to rename to createSCFBranchOp and below createSCFLoopOp. That way it may be a bit easier to follow in the code when new SCF stuff is created.