1# Table-driven Declarative Rewrite Rule (DRR) 2 3In addition to subclassing the `mlir::RewritePattern` C++ class, MLIR also 4supports defining rewrite rules in a declarative manner. Similar to 5[Op Definition Specification](OpDefinitions.md) (ODS), this is achieved via 6[TableGen][TableGen], which is a language to maintain records of domain-specific 7information. The rewrite rules are specified concisely in a TableGen record, 8which will be expanded into an equivalent `mlir::RewritePattern` subclass at 9compiler build time. 10 11This manual explains in detail all of the available mechanisms for defining 12rewrite rules in such a declarative manner. It aims to be a specification 13instead of a tutorial. Please refer to 14[Quickstart tutorial to adding MLIR graph rewrite](Tutorials/QuickstartRewrites.md) 15for the latter. 16 17Given that declarative rewrite rules depend on op definition specification, this 18manual assumes knowledge of the [ODS](OpDefinitions.md) doc. 19 20## Benefits 21 22Compared to the hand-written C++ classes, this declarative approach has several 23benefits, including but not limited to: 24 25* **Being declarative**: The pattern creator just needs to state the rewrite 26 pattern declaratively, without worrying about the concrete C++ methods to 27 call. 28* **Removing boilerplate and showing the very essence of the rewrite**: 29 `mlir::RewritePattern` is already good at hiding boilerplate for defining a 30 rewrite rule. But we still need to write the class and function structures 31 required by the C++ programming language, inspect ops for matching, and call 32 op `build()` methods for constructing. These statements are typically quite 33 simple and similar, so they can be further condensed with auto-generation. 34 Because we reduce the boilerplate to the bare minimum, the declarative 35 rewrite rule will just contain the very essence of the rewrite. This makes 36 it very easy to understand the pattern. 37 38## Strengths and Limitations 39 40The declarative rewrite rule is **operation-based**: it describes a rule to 41match against a directed acyclic graph (DAG) of operations and generate DAGs of 42operations. This gives DRR both its strengths and limitations: it is good at 43expressing op to op conversions, but not that well suited for, say, converting 44an op into a loop nest. 45 46Per the current implementation, DRR does not have good support for the following 47features: 48 49* Matching and generating ops with regions. 50* Matching and generating ops with block arguments. 51* Matching multi-result ops in nested patterns. 52* Matching and generating variadic operand/result ops in nested patterns. 53* Packing and unpacking variadic operands/results during generation. 54* [`NativeCodeCall`](#nativecodecall-transforming-the-generated-op) returning 55 more than one results. 56 57## Rule Definition 58 59The core construct for defining a rewrite rule is defined in 60[`OpBase.td`][OpBase] as 61 62```tablegen 63class Pattern< 64 dag sourcePattern, list<dag> resultPatterns, 65 list<dag> additionalConstraints = [], 66 dag benefitsAdded = (addBenefit 0)>; 67``` 68 69A declarative rewrite rule contains two main components: 70 71* A _source pattern_, which is used for matching a DAG of operations. 72* One or more _result patterns_, which are used for generating DAGs of 73 operations to replace the matched DAG of operations. 74 75We allow multiple result patterns to support 76[multi-result ops](#supporting-multi-result-ops) and 77[auxiliary ops](#supporting-auxiliary-ops), but frequently we just want to 78convert one DAG of operations to another DAG of operations. There is a handy 79wrapper of `Pattern`, `Pat`, which takes a single result pattern: 80 81```tablegen 82class Pat< 83 dag sourcePattern, dag resultPattern, 84 list<dag> additionalConstraints = [], 85 dag benefitsAdded = (addBenefit 0)> : 86 Pattern<sourcePattern, [resultPattern], additionalConstraints, benefitAdded>; 87``` 88 89Each pattern is specified as a TableGen `dag` object with the syntax of 90`(operator arg0, arg1, ...)`. 91 92`operator` is typically an MLIR op, but it can also be other 93[directives](#rewrite-directives). `argN` is for matching (if used in source 94pattern) or generating (if used in result pattern) the `N`-th argument for 95`operator`. If the `operator` is some MLIR operation, it means the `N`-th 96argument as specified in the `arguments` list of the op's definition. Therefore, 97we say op argument specification in pattern is **position-based**: the position 98where they appear matters. 99 100`argN` can be a `dag` object itself, thus we can have nested `dag` tree to model 101the def-use relationship between ops. 102 103### Source pattern 104 105The source pattern is for matching a DAG of operations. Arguments in the `dag` 106object are intended to **capture** the op arguments. They can also be used to 107**further limit** the match criteria. The capturing is done by specifying a 108symbol starting with the `$` sign, while further constraints are introduced by 109specifying a `TypeConstraint` (for an operand) or a `AttrConstraint` (for an 110attribute). 111 112#### Binding op arguments and limiting the match 113 114For example, 115 116```tablegen 117def AOp : Op<"a_op"> { 118 let arguments = (ins 119 AnyType:$a_input, 120 AnyAttr:$a_attr 121 ); 122 123 let results = (outs 124 AnyType:$a_output 125 ); 126} 127 128def : Pat<(AOp $input, F32Attr:$attr), ...>; 129``` 130 131In the above, we are matching an `AOp` whose `$input` can be anything valid as 132defined by the op and whose `$attr` must be a float attribute. If the match 133succeeds, we bind the `$input` symbol to the op's only input (`$a_input`) and 134`$attr` to the only attribute (`$a_attr`); we can reference them using `$input` 135and `$attr` in result patterns and additional constraints. 136 137The pattern is position-based: the symbol names used for capturing here do not 138need to match with the op definition as shown in the above example. As another 139example, the pattern can be written as `def : Pat<(AOp $a, F32Attr:$b), ...>;` 140and use `$a` and `$b` to refer to the captured input and attribute. But using 141the ODS name directly in the pattern is also allowed. Operands in the source 142pattern can have the same name. This bounds one operand to the name while 143verifying the rest are all equal. 144 145Also note that we only need to add `TypeConstraint` or `AttributeConstraint` 146when we need to further limit the match criteria. If all valid cases to the op 147are acceptable, then we can leave the constraint unspecified. 148 149`$_` is a special symbol to mean ignore capturing an argument. For example, 150`def : Pat<(AOp $_, $b), ...>` means only `$b` is interesting to capture and 151will be referenced later in result patterns. It's still possible to place 152additional constraints even if the symbol is not to be captured; for such case, 153you can simply use just the `TypeConstraint` or `AttributeConstraint` without a 154bound symbol, for example, `def : Pat<(AOp $a, F32Attr), ...>`. 155 156#### Matching DAG of operations 157 158To match a DAG of ops, use nested `dag` objects: 159 160```tablegen 161 162def BOp : Op<"b_op"> { 163 let arguments = (ins); 164 165 let results = (outs 166 AnyType:$b_output 167 ); 168} 169 170 171def : Pat<(AOp (BOp), $attr), ...>; 172``` 173 174The above pattern matches an `AOp` whose only operand is generated by a `BOp`, 175that is, the following MLIR code: 176 177```mlir 178%0 = "b_op"() : () -> (...) 179%1 = "a_op"(%0) {attr: ...} : () -> (...) 180``` 181 182#### Binding op results 183 184To bind a symbol to the results of a matched op for later reference, attach the 185symbol to the op itself: 186 187```tablegen 188def : Pat<(AOp (BOp:$b_result), $attr), ...>; 189``` 190 191The above will bind `$b_result` to the matched `BOp`'s result. (There are more 192details regarding multi-result ops, which is covered 193[later](#supporting-multi-result-ops).) 194 195### Result pattern 196 197The result pattern is for generating a DAG of operations. Arguments in the `dag` 198object are intended to **reference** values captured in the source pattern and 199potentially **apply transformations**. 200 201#### Referencing bound symbols 202 203For example, 204 205```tablegen 206def COp : Op<"c_op"> { 207 let arguments = (ins 208 AnyType:$c_input, 209 AnyAttr:$c_attr 210 ); 211 212 let results = (outs 213 AnyType:$c_output 214 ); 215} 216 217def : Pat<(AOp $input, $attr), (COp $input, $attr)>; 218``` 219 220In the above, `AOp`'s only operand and attribute are bound to `$input` and 221`$attr`, respectively. We then reference them in the result pattern for 222generating the `COp` by passing them in as arguments to `COp`'s `build()` 223method. 224 225We can also reference symbols bound to matched op's results: 226 227```tablegen 228def : Pat<(AOp (BOp:$b_result) $attr), (COp $b_result $attr)>; 229``` 230 231In the above, we are using `BOp`'s result for building `COp`. 232 233#### Building operations 234 235Given that `COp` was specified with table-driven op definition, there will be 236several `build()` methods generated for it. One of them has aggregated 237parameters for result types, operands, and attributes in the signature: `void 238COp::build(..., ArrayRef<Type> resultTypes, Array<Value> operands, 239ArrayRef<NamedAttribute> attr)`. The pattern in the above calls this `build()` 240method for constructing the `COp`. 241 242In general, arguments in the result pattern will be passed directly to the 243`build()` method to leverage the auto-generated `build()` method, list them in 244the pattern by following the exact same order as the ODS `arguments` definition. 245Otherwise, a custom `build()` method that matches the argument list is required. 246 247Right now all ODS-generated `build()` methods require specifying the result 248type(s), unless the op has known traits like `SameOperandsAndResultType` that we 249can use to auto-generate a `build()` method with result type deduction. When 250generating an op to replace the result of the matched root op, we can use the 251matched root op's result type when calling the ODS-generated builder. Otherwise 252(e.g., generating an [auxiliary op](#supporting-auxiliary-ops) or generating an 253op with a nested result pattern), DRR will not be able to deduce the result 254type(s). The pattern author will need to define a custom builder that has result 255type deduction ability via `OpBuilder` in ODS. For example, in the following 256pattern 257 258```tablegen 259def : Pat<(AOp $input, $attr), (COp (AOp $input, $attr) $attr)>; 260``` 261 262`AOp` is generated via a nested result pattern; DRR won't be able to deduce the 263result type for it. A custom builder for `AOp` should be defined and it should 264deduce the result type by itself. The builder should have the separate parameter 265for each operand and attribute and deduce the result type internally by itself. 266For example, for the above `AOp`, a possible builder is: 267 268```c++ 269 270void AOp::build(OpBuilder &builder, OperationState &state, 271 Value input, Attribute attr) { 272 state.addOperands({input}); 273 state.addAttribute("a_attr", attr); 274 Type type = ...; // Deduce result type here 275 state.addTypes({type}); 276} 277``` 278 279Failing to define such a builder will result in an error at C++ compilation time 280saying the call to `AOp::build()` cannot be resolved because of the number of 281parameters mismatch. 282 283#### Generating DAG of operations 284 285`dag` objects can be nested to generate a DAG of operations: 286 287```tablegen 288def : Pat<(AOp $input, $attr), (COp (BOp), $attr)>; 289``` 290 291In the above, we generate a `BOp`, and then use its result to generate the `COp` 292to replace the matched `AOp`. 293 294#### Binding op results 295 296In the result pattern, we can bind to the result(s) of a newly built op by 297attaching symbols to the op. (But we **cannot** bind to op arguments given that 298they are referencing previously bound symbols.) This is useful for reusing newly 299created results where suitable. For example, 300 301```tablegen 302def DOp : Op<"d_op"> { 303 let arguments = (ins 304 AnyType:$d_input1, 305 AnyType:$d_input2, 306 ); 307 308 let results = (outs 309 AnyType:$d_output 310 ); 311} 312 313def : Pat<(AOp $input, $ignored_attr), (DOp (BOp:$b_result) $b_result)>; 314``` 315 316In this pattern, an `AOp` is matched and replaced with a `DOp` whose two 317operands are from the result of a single `BOp`. This is only possible by binding 318the result of the `BOp` to a name and reuse it for the second operand of the 319`DOp` 320 321#### `NativeCodeCall`: transforming the generated op 322 323Sometimes the captured arguments are not exactly what we want so they cannot be 324directly fed in as arguments to build the new op. For such cases, we can apply 325transformations on the arguments by calling into C++ helper functions. This is 326achieved by `NativeCodeCall`. 327 328For example, if we want to capture some op's attributes and group them as an 329array attribute to construct a new op: 330 331```tablegen 332 333def TwoAttrOp : Op<"two_attr_op"> { 334 let arguments = (ins 335 AnyAttr:$op_attr1, 336 AnyAttr:$op_attr2 337 ); 338 339 let results = (outs 340 AnyType:$op_output 341 ); 342} 343 344def OneAttrOp : Op<"one_attr_op"> { 345 let arguments = (ins 346 ArrayAttr:$op_attr 347 ); 348 349 let results = (outs 350 AnyType:$op_output 351 ); 352} 353``` 354 355We can write a C++ helper function: 356 357```c++ 358Attribute createArrayAttr(Builder &builder, Attribute a, Attribute b) { 359 return builder.getArrayAttr({a, b}); 360} 361``` 362 363And then write the pattern as: 364 365```tablegen 366def createArrayAttr : NativeCodeCall<"createArrayAttr($_builder, $0, $1)">; 367 368def : Pat<(TwoAttrOp $attr1, $attr2), 369 (OneAttrOp (createArrayAttr $attr1, $attr2))>; 370``` 371 372And make sure the generated C++ code from the above pattern has access to the 373definition of the C++ helper function. 374 375In the above example, we are using a string to specialize the `NativeCodeCall` 376template. The string can be an arbitrary C++ expression that evaluates into some 377C++ object expected at the `NativeCodeCall` site (here it would be expecting an 378array attribute). Typically the string should be a function call. 379 380##### `NativeCodeCall` placeholders 381 382In `NativeCodeCall`, we can use placeholders like `$_builder`, `$N` and `$N...`. 383The former is called _special placeholder_, while the latter is called 384_positional placeholder_ and _positional range placeholder_. 385 386`NativeCodeCall` right now only supports three special placeholders: 387`$_builder`, `$_loc`, and `$_self`: 388 389* `$_builder` will be replaced by the current `mlir::PatternRewriter`. 390* `$_loc` will be replaced by the fused location or custom location (as 391 determined by location directive). 392* `$_self` will be replaced by the defining operation in a source pattern. 393 394We have seen how `$_builder` can be used in the above; it allows us to pass a 395`mlir::Builder` (`mlir::PatternRewriter` is a subclass of `mlir::OpBuilder`, 396which is a subclass of `mlir::Builder`) to the C++ helper function to use the 397handy methods on `mlir::Builder`. 398 399Here's an example how we should use `$_self` in source pattern, 400 401```tablegen 402 403def : Pat<(OneAttrOp (NativeCodeCall<"Foo($_self, &$0)"> I32Attr:$val)), 404 (TwoAttrOp $val, $val)>; 405``` 406 407In the above, `$_self` is substituted by the defining operation of the first 408operand of OneAttrOp. Note that we don't support binding name to NativeCodeCall 409in the source pattern. To carry some return values from helper function, put the 410names (constraint is optional) in the parameter list and they will be bound to 411the variables with correspoding type. Then these named must be either passed by 412reference or a pointer to variable used as argument so that the matched value 413can be returned. In the same example, `$val` will be bound to a variable with 414`Attribute` type(as `I32Attr`) and the type of the second argument in Foo() 415could be `Attribute&` or `Attribute*`. Names with attribute constraints will be 416captured as Attributes while everything else will be treated as Value. 417 418Positional placeholders will be substituted by the `dag` object parameters at 419the `NativeCodeCall` use site. For example, if we define `SomeCall : 420NativeCodeCall<"someFn($1, $2, $0)">` and use it like `(SomeCall $in0, $in1, 421$in2)`, then this will be translated into C++ call `someFn($in1, $in2, $in0)`. 422 423Positional range placeholders will be substituted by multiple `dag` object 424parameters at the `NativeCodeCall` use site. For example, if we define 425`SomeCall : NativeCodeCall<"someFn($1...)">` and use it like `(SomeCall $in0, 426$in1, $in2)`, then this will be translated into C++ call `someFn($in1, $in2)`. 427 428##### `NativeCodeCall` binding multi-results 429 430To bind multi-results and access the N-th result with `$<name>__N`, specify the 431number of return values in the template. Note that only `Value` type is 432supported for multiple results binding. For example, 433 434```tablegen 435 436def PackAttrs : NativeCodeCall<"packAttrs($0, $1)", 2>; 437def : Pattern<(TwoResultOp $attr1, $attr2), 438 [(OneResultOp (PackAttr:$res__0, $attr1, $attr2)), 439 (OneResultOp $res__1)]>; 440 441``` 442 443Use `NativeCodeCallVoid` for case has no return value. 444 445The correct number of returned value specified in NativeCodeCall is important. 446It will be used to verify the consistency of the number of result values. 447Additionally, `mlir-tblgen` will try to capture the return value of 448NativeCodeCall in the generated code so that it will trigger a later compilation 449error if a NativeCodeCall that doesn't return a result isn't labeled with 0 450returns. 451 452##### Customizing entire op building 453 454`NativeCodeCall` is not only limited to transforming arguments for building an 455op; it can be also used to specify how to build an op entirely. An example: 456 457If we have a C++ function for building an op: 458 459```c++ 460Operation *createMyOp(OpBuilder builder, Value input, Attribute attr); 461``` 462 463We can wrap it up and invoke it like: 464 465```tablegen 466def createMyOp : NativeCodeCall<"createMyOp($_builder, $0, $1)">; 467 468def : Pat<(... $input, $attr), (createMyOp $input, $attr)>; 469``` 470 471### Supporting auxiliary ops 472 473A declarative rewrite rule supports multiple result patterns. One of the 474purposes is to allow generating _auxiliary ops_. Auxiliary ops are operations 475used for building the replacement ops; but they are not directly used for 476replacement themselves. 477 478For the case of uni-result ops, if there are multiple result patterns, only the 479value generated from the last result pattern will be used to replace the matched 480root op's result; all other result patterns will be considered as generating 481auxiliary ops. 482 483Normally we want to specify ops as nested `dag` objects if their def-use 484relationship can be expressed in the way that an op's result can feed as the 485argument to consuming op. But that is not always possible. For example, if we 486want to allocate memory and store some computation (in pseudocode): 487 488```mlir 489%dst = addi %lhs, %rhs 490``` 491 492into 493 494```mlir 495%shape = shape %lhs 496%mem = alloc %shape 497%sum = addi %lhs, %rhs 498store %mem, %sum 499%dst = load %mem 500``` 501 502We cannot fit in with just one result pattern given `store` does not return a 503value. Instead we can use multiple result patterns: 504 505```tablegen 506def : Pattern<(AddIOp $lhs, $rhs), 507 [(StoreOp (AllocOp:$mem (ShapeOp $lhs)), (AddIOp $lhs, $rhs)), 508 (LoadOp $mem)]; 509``` 510 511In the above we use the first result pattern to generate the first four ops, and 512use the last pattern to generate the last op, which is used to replace the 513matched op. 514 515### Supporting multi-result ops 516 517Multi-result ops bring extra complexity to declarative rewrite rules. We use 518TableGen `dag` objects to represent ops in patterns; there is no native way to 519indicate that an op generates multiple results. The approach adopted is based on 520**naming convention**: a `__N` suffix is added to a symbol to indicate the 521`N`-th result. 522 523#### `__N` suffix 524 525The `__N` suffix is specifying the `N`-th result as a whole (which can be 526[variadic](#supporting-variadic-ops)). For example, we can bind a symbol to some 527multi-result op and reference a specific result later: 528 529```tablegen 530def ThreeResultOp : Op<"three_result_op"> { 531 let arguments = (ins ...); 532 533 let results = (outs 534 AnyTensor:$op_output1, 535 AnyTensor:$op_output2, 536 AnyTensor:$op_output3 537 ); 538} 539 540def : Pattern<(ThreeResultOp:$results ...), 541 [(... $results__0), ..., (... $results__2), ...]>; 542``` 543 544In the above pattern we bind `$results` to all the results generated by 545`ThreeResultOp` and references its `$input1` and `$input3` later in the result 546patterns. 547 548We can also bind a symbol and reference one of its specific result at the same 549time, which is typically useful when generating multi-result ops: 550 551```tablegen 552// TwoResultOp has similar definition as ThreeResultOp, but only has two 553// results. 554 555def : Pattern<(TwoResultOp ...), 556 [(ThreeResultOp:$results__2, ...), 557 (replaceWithValue $results__0)]>; 558``` 559 560In the above, we created a `ThreeResultOp` and bind `results` to its results, 561and uses its last result (`$output3`) and first result (`$output1`) to replace 562the `TwoResultOp`'s two results, respectively. 563 564#### Replacing multi-result ops 565 566The above example also shows how to replace a matched multi-result op. 567 568To replace an `N`-result op, the result patterns must generate at least `N` 569declared values (see [Declared vs. actual value](#declared-vs-actual-value) for 570definition). If there are more than `N` declared values generated, only the last 571`N` declared values will be used to replace the matched op. Note that because of 572the existence of multi-result op, one result pattern **may** generate multiple 573declared values. So it means we do not necessarily need `N` result patterns to 574replace an `N`-result op. For example, to replace an op with three results, you 575can have 576 577```tablegen 578// ThreeResultOp/TwoResultOp/OneResultOp generates three/two/one result(s), 579// respectively. 580 581// Replace each result with a result generated from an individual op. 582def : Pattern<(ThreeResultOp ...), 583 [(OneResultOp ...), (OneResultOp ...), (OneResultOp ...)]>; 584 585// Replace the first two results with two results generated from the same op. 586def : Pattern<(ThreeResultOp ...), 587 [(TwoResultOp ...), (OneResultOp ...)]>; 588 589// Replace all three results with three results generated from the same op. 590def : Pat<(ThreeResultOp ...), (ThreeResultOp ...)>; 591 592def : Pattern<(ThreeResultOp ...), 593 [(AuxiliaryOp ...), (ThreeResultOp ...)]>; 594``` 595 596But using a single op to serve as both auxiliary op and replacement op is 597forbidden, i.e., the following is not allowed because that the first 598`TwoResultOp` generates two results but only the second result is used for 599replacing the matched op's result: 600 601```tablegen 602def : Pattern<(ThreeResultOp ...), 603 [(TwoResultOp ...), (TwoResultOp ...)]>; 604``` 605 606### Supporting variadic ops 607 608#### Declared vs. actual value 609 610Before going into details on variadic op support, we need to define a few terms 611regarding an op's values. 612 613* _Value_: either an operand or a result 614* _Declared operand/result/value_: an operand/result/value statically declared 615 in ODS of the op 616* _Actual operand/result/value_: an operand/result/value of an op instance at 617 runtime 618 619The above terms are needed because ops can have multiple results, and some of 620the results can also be variadic. For example, 621 622```tablegen 623def MultiVariadicOp : Op<"multi_variadic_op"> { 624 let arguments = (ins 625 AnyTensor:$input1, 626 Variadic<AnyTensor>:$input2, 627 AnyTensor:$input3 628 ); 629 630 let results = (outs 631 AnyTensor:$output1, 632 Variadic<AnyTensor>:$output2, 633 AnyTensor:$output3 634 ); 635} 636``` 637 638We say the above op has 3 declared operands and 3 declared results. But at 639runtime, an instance can have 3 values corresponding to `$input2` and 2 values 640correspond to `$output2`; we say it has 5 actual operands and 4 actual results. 641A variadic operand/result is a considered as a declared value that can 642correspond to multiple actual values. 643 644[TODO] 645 646### Supplying additional constraints 647 648Constraints can be placed on op arguments when matching. But sometimes we need 649to also place constraints on the matched op's results or sometimes need to limit 650the matching with some constraints that cover both the arguments and the 651results. The third parameter to `Pattern` (and `Pat`) is for this purpose. 652 653For example, we can write 654 655```tablegen 656def HasNoUseOf: Constraint<CPred<"$_self.use_empty()">, "has no use">; 657 658def HasSameElementType : Constraint< 659 CPred<"$0.cast<ShapedType>().getElementType() == " 660 "$1.cast<ShapedType>().getElementType()">, 661 "has same element type">; 662 663def : Pattern<(TwoResultOp:$results $input), 664 [(...), (...)], 665 [(F32Tensor:$results__0), (HasNoUseOf:$results__1), 666 (HasSameElementShape $results__0, $input)]>; 667``` 668 669You can 670 671* Use normal `TypeConstraint`s on previous bound symbols (the first result of 672 `TwoResultOp` must be a float tensor); 673* Define new `Constraint` for previous bound symbols (the second result of 674 `TwoResultOp` must has no use); 675* Apply constraints on multiple bound symbols (`$input` and `TwoResultOp`'s 676 first result must have the same element type). 677 678### Adjusting benefits 679 680The benefit of a `Pattern` is an integer value indicating the benefit of 681matching the pattern. It determines the priorities of patterns inside the 682pattern rewrite driver. A pattern with a higher benefit is applied before one 683with a lower benefit. 684 685In DRR, a rule is set to have a benefit of the number of ops in the source 686pattern. This is based on the heuristics and assumptions that: 687 688* Larger matches are more beneficial than smaller ones. 689* If a smaller one is applied first the larger one may not apply anymore. 690 691The fourth parameter to `Pattern` (and `Pat`) allows to manually tweak a 692pattern's benefit. Just supply `(addBenefit N)` to add `N` to the benefit value. 693 694## Rewrite directives 695 696### `location` 697 698By default the C++ pattern expanded from a DRR pattern uses the fused location 699of all source ops as the location for all generated ops. This is not always the 700best location mapping relationship. For such cases, DRR provides the `location` 701directive to provide finer control. 702 703`location` is of the following syntax: 704 705```tablegen 706(location $symbol0, $symbol1, ...) 707``` 708 709where all `$symbol` should be bound previously in the pattern and one optional 710string may be specified as an attribute. The following locations are created: 711 712* If only 1 symbol is specified then that symbol's location is used, 713* If multiple are specified then a fused location is created; 714* If no symbol is specified then string must be specified and a NamedLoc is 715 created instead; 716 717`location` must be used as the last argument to an op creation. For example, 718 719```tablegen 720def : Pat<(LocSrc1Op:$src1 (LocSrc2Op:$src2 ...), 721 (LocDst1Op (LocDst2Op ..., (location $src2)), (location "outer"))>; 722``` 723 724In the above pattern, the generated `LocDst2Op` will use the matched location of 725`LocSrc2Op` while the root `LocDst1Op` node will used the named location 726`outer`. 727 728### `replaceWithValue` 729 730The `replaceWithValue` directive is used to eliminate a matched op by replacing 731all of it uses with a captured value. It is of the following syntax: 732 733```tablegen 734(replaceWithValue $symbol) 735``` 736 737where `$symbol` should be a symbol bound previously in the pattern. 738 739For example, 740 741```tablegen 742def : Pat<(Foo $input), (replaceWithValue $input)>; 743``` 744 745The above pattern removes the `Foo` and replaces all uses of `Foo` with 746`$input`. 747 748## Debugging Tips 749 750### Run `mlir-tblgen` to see the generated content 751 752TableGen syntax sometimes can be obscure; reading the generated content can be a 753very helpful way to understand and debug issues. To build `mlir-tblgen`, run 754`cmake --build . --target mlir-tblgen` in your build directory and find the 755`mlir-tblgen` binary in the `bin/` subdirectory. All the supported generators 756can be found via `mlir-tblgen --help`. 757 758To see the generated code, invoke `mlir-tblgen` with a specific generator by 759providing include paths via `-I`. For example, 760 761```sh 762# To see all the C++ pattern rewrite classes 763mlir-tblgen --gen-rewriters -I /path/to/mlir/include /path/to/input/td/file 764``` 765 766### Compilation error: no matching member function for call to 'build' 767 768This is because DRR is failing to call a `build()` method with result type 769deduction ability. See [building operations](#building-operations) for more 770details. 771 772[TableGen]: https://llvm.org/docs/TableGen/index.html 773[OpBase]: https://github.com/llvm/llvm-project/blob/main/mlir/include/mlir/IR/OpBase.td 774