26 Pattern Rewriter
PatternRewriter is the mutation API used inside MLIR rewrite patterns. It is more than a convenience wrapper around IR lists: it keeps operation insertion, replacement, erasure, listener notifications, and rewrite-driver bookkeeping consistent.
26.1 Why Direct Mutation Is Risky
A rewrite driver needs to know which operations changed so it can revisit local neighbors, maintain worklists, and avoid traversing erased objects. Directly splicing operations while a pattern runs can leave stale worklist entries or miss follow-up opportunities. PatternRewriter makes the transformation visible to the driver.
Its core operations are conceptually simple: create a replacement at a chosen insertion point, replace an operation’s results, erase an operation with no live uses, and modify an operation in place only after declaring that modification. Use the most specific API that reflects the semantic action.
26.2 Replacement Is Graph Editing
Replacing an operation redirects each result’s use list to corresponding new values. The replacement values must have types accepted by every use and must dominate those uses. When result arity differs, a pattern needs an explicit mapping or a different representation; it cannot pretend one value replaces two unrelated results.
For operations with regions, replacing the outer operation also transfers or recreates the region contract. Do not erase an operation merely because its visible result has been replaced if its nested region, symbol identity, or effects still need a semantic successor.
26.3 In-Place Updates And Transactions
Some rewrites genuinely preserve operation identity and only update attributes or operands. In those cases use the rewriter’s in-place modification support so listeners and analyses see a coherent change. If a mutation can fail midway, construct the replacement form first rather than exposing temporarily malformed IR.
The rewriter does not prove your transformation legal. It maintains mutation mechanics; the pattern supplies semantic preconditions, and verification checks the resulting IR.