Using Table Driven Declarative Rewrite Rule (DRR)

Hi Folks:

I tried to use the mlir DRR (Table-driven Declarative Rewrite Rule (DRR) - MLIR) by defining a Pat but I am not clear when and how it gets ‘invoked’. To make my problem clearer I use an example below:
My Ops.td is something like:

def ReshapeTensorOp : MyDialect_Op<"reshape_tensor", [NoSideEffect]> {
  let summary = "reshapes a given shape (not underlying data)";
  let description = [{ ...}];
   let arguments = (ins MyTensorType:$src);
  let results = (outs MyTensorType:$dst);
}

The above has been working fine for me, i.e. I can read in a textual-ir and compile it down to my backend.
Then I tried adding a DRR

// Reshape(Reshape(x)) = Reshape(x)
def ReshapeReshapeOptPattern : Pat<(ReshapeTensorOp (ReshapeTensorOp $src)),
                                   (ReshapeTensorOp $src)>;

I have following Quickstart tutorial to adding MLIR graph rewrite - MLIR a mlir_tablegen(testPat.h.inc -gen-rewriters) in my cmake which generates the file with class

struct ReshapeReshapeOptPattern : public ::mlir::RewritePattern { ....

and, populateWithGenerated At this point though I am not sure next step exactly. Do I need to write a Pass that walks over every op and
(1) calls for every op the auto-generated in matchAndRewrite method;
(2) deletes the dead first reshape_tensor op in case of replace success;
(3) anything else for consistency of resulting IR;
Therefore pointers to any such existing good example would be very helpful to me.
Thanks a lot for the help.

Hey,

These currently just define the patterns and generate the methods to populate pattern list, to add these into a pass see https://github.com/llvm/llvm-project/blob/c0342a2de8aa9ffe129bce50e9c90647a772bb2b/mlir/lib/Conversion/ShapeToStandard/ShapeToStandard.cpp#L688 (there it is using the dialect conversion framework, one can also use greedy pattern rewriter or the like, eg.,. https://github.com/llvm/llvm-project/blob/02b6fb218e44490f3ea1597e35df1b1b66c6b869/mlir/test/lib/Dialect/Test/TestPatterns.cpp#L139 ). It’s on the wishlist to be able to automatically generate a pass for the simple case (these are used in different ways and the populate methods are the most general, so TBD if useful convenience or not)

– Jacques

2 Likes

Thank you Jacques. That worked fine for me. Sorry for late reply as i wanted to get it all working first.