1 //===- RewriterGen.cpp - MLIR pattern rewriter generator ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // RewriterGen uses pattern rewrite definitions to generate rewriter matchers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Support/IndentedOstream.h"
14 #include "mlir/TableGen/Attribute.h"
15 #include "mlir/TableGen/CodeGenHelpers.h"
16 #include "mlir/TableGen/Format.h"
17 #include "mlir/TableGen/GenInfo.h"
18 #include "mlir/TableGen/Operator.h"
19 #include "mlir/TableGen/Pattern.h"
20 #include "mlir/TableGen/Predicate.h"
21 #include "mlir/TableGen/Type.h"
22 #include "llvm/ADT/FunctionExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/FormatAdapters.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/TableGen/Error.h"
31 #include "llvm/TableGen/Main.h"
32 #include "llvm/TableGen/Record.h"
33 #include "llvm/TableGen/TableGenBackend.h"
34 
35 using namespace mlir;
36 using namespace mlir::tblgen;
37 
38 using llvm::formatv;
39 using llvm::Record;
40 using llvm::RecordKeeper;
41 
42 #define DEBUG_TYPE "mlir-tblgen-rewritergen"
43 
44 namespace llvm {
45 template <>
46 struct format_provider<mlir::tblgen::Pattern::IdentifierLine> {
47   static void format(const mlir::tblgen::Pattern::IdentifierLine &v,
48                      raw_ostream &os, StringRef style) {
49     os << v.first << ":" << v.second;
50   }
51 };
52 } // end namespace llvm
53 
54 //===----------------------------------------------------------------------===//
55 // PatternEmitter
56 //===----------------------------------------------------------------------===//
57 
58 namespace {
59 
60 class StaticMatcherHelper;
61 
62 class PatternEmitter {
63 public:
64   PatternEmitter(Record *pat, RecordOperatorMap *mapper, raw_ostream &os,
65                  StaticMatcherHelper &helper);
66 
67   // Emits the mlir::RewritePattern struct named `rewriteName`.
68   void emit(StringRef rewriteName);
69 
70   // Emits the static function of DAG matcher.
71   void emitStaticMatcher(DagNode tree, std::string funcName);
72 
73 private:
74   // Emits the code for matching ops.
75   void emitMatchLogic(DagNode tree, StringRef opName);
76 
77   // Emits the code for rewriting ops.
78   void emitRewriteLogic();
79 
80   //===--------------------------------------------------------------------===//
81   // Match utilities
82   //===--------------------------------------------------------------------===//
83 
84   // Emits C++ statements for matching the DAG structure.
85   void emitMatch(DagNode tree, StringRef name, int depth);
86 
87   // Emit C++ function call to static DAG matcher.
88   void emitStaticMatchCall(DagNode tree, StringRef name);
89 
90   // Emits C++ statements for matching using a native code call.
91   void emitNativeCodeMatch(DagNode tree, StringRef name, int depth);
92 
93   // Emits C++ statements for matching the op constrained by the given DAG
94   // `tree` returning the op's variable name.
95   void emitOpMatch(DagNode tree, StringRef opName, int depth);
96 
97   // Emits C++ statements for matching the `argIndex`-th argument of the given
98   // DAG `tree` as an operand. operandIndex is the index in the DAG excluding
99   // the preceding attributes.
100   void emitOperandMatch(DagNode tree, StringRef opName, int argIndex,
101                         int operandIndex, int depth);
102 
103   // Emits C++ statements for matching the `argIndex`-th argument of the given
104   // DAG `tree` as an attribute.
105   void emitAttributeMatch(DagNode tree, StringRef opName, int argIndex,
106                           int depth);
107 
108   // Emits C++ for checking a match with a corresponding match failure
109   // diagnostic.
110   void emitMatchCheck(StringRef opName, const FmtObjectBase &matchFmt,
111                       const llvm::formatv_object_base &failureFmt);
112 
113   // Emits C++ for checking a match with a corresponding match failure
114   // diagnostics.
115   void emitMatchCheck(StringRef opName, const std::string &matchStr,
116                       const std::string &failureStr);
117 
118   //===--------------------------------------------------------------------===//
119   // Rewrite utilities
120   //===--------------------------------------------------------------------===//
121 
122   // The entry point for handling a result pattern rooted at `resultTree`. This
123   // method dispatches to concrete handlers according to `resultTree`'s kind and
124   // returns a symbol representing the whole value pack. Callers are expected to
125   // further resolve the symbol according to the specific use case.
126   //
127   // `depth` is the nesting level of `resultTree`; 0 means top-level result
128   // pattern. For top-level result pattern, `resultIndex` indicates which result
129   // of the matched root op this pattern is intended to replace, which can be
130   // used to deduce the result type of the op generated from this result
131   // pattern.
132   std::string handleResultPattern(DagNode resultTree, int resultIndex,
133                                   int depth);
134 
135   // Emits the C++ statement to replace the matched DAG with a value built via
136   // calling native C++ code.
137   std::string handleReplaceWithNativeCodeCall(DagNode resultTree, int depth);
138 
139   // Returns the symbol of the old value serving as the replacement.
140   StringRef handleReplaceWithValue(DagNode tree);
141 
142   // Trailing directives are used at the end of DAG node argument lists to
143   // specify additional behaviour for op matchers and creators, etc.
144   struct TrailingDirectives {
145     // DAG node containing the `location` directive. Null if there is none.
146     DagNode location;
147 
148     // DAG node containing the `returnType` directive. Null if there is none.
149     DagNode returnType;
150 
151     // Number of found trailing directives.
152     int numDirectives;
153   };
154 
155   // Collect any trailing directives.
156   TrailingDirectives getTrailingDirectives(DagNode tree);
157 
158   // Returns the location value to use.
159   std::string getLocation(TrailingDirectives &tail);
160 
161   // Returns the location value to use.
162   std::string handleLocationDirective(DagNode tree);
163 
164   // Emit return type argument.
165   std::string handleReturnTypeArg(DagNode returnType, int i, int depth);
166 
167   // Emits the C++ statement to build a new op out of the given DAG `tree` and
168   // returns the variable name that this op is assigned to. If the root op in
169   // DAG `tree` has a specified name, the created op will be assigned to a
170   // variable of the given name. Otherwise, a unique name will be used as the
171   // result value name.
172   std::string handleOpCreation(DagNode tree, int resultIndex, int depth);
173 
174   using ChildNodeIndexNameMap = DenseMap<unsigned, std::string>;
175 
176   // Emits a local variable for each value and attribute to be used for creating
177   // an op.
178   void createSeparateLocalVarsForOpArgs(DagNode node,
179                                         ChildNodeIndexNameMap &childNodeNames);
180 
181   // Emits the concrete arguments used to call an op's builder.
182   void supplyValuesForOpArgs(DagNode node,
183                              const ChildNodeIndexNameMap &childNodeNames,
184                              int depth);
185 
186   // Emits the local variables for holding all values as a whole and all named
187   // attributes as a whole to be used for creating an op.
188   void createAggregateLocalVarsForOpArgs(
189       DagNode node, const ChildNodeIndexNameMap &childNodeNames, int depth);
190 
191   // Returns the C++ expression to construct a constant attribute of the given
192   // `value` for the given attribute kind `attr`.
193   std::string handleConstantAttr(Attribute attr, const Twine &value);
194 
195   // Returns the C++ expression to build an argument from the given DAG `leaf`.
196   // `patArgName` is used to bound the argument to the source pattern.
197   std::string handleOpArgument(DagLeaf leaf, StringRef patArgName);
198 
199   //===--------------------------------------------------------------------===//
200   // General utilities
201   //===--------------------------------------------------------------------===//
202 
203   // Collects all of the operations within the given dag tree.
204   void collectOps(DagNode tree, llvm::SmallPtrSetImpl<const Operator *> &ops);
205 
206   // Returns a unique symbol for a local variable of the given `op`.
207   std::string getUniqueSymbol(const Operator *op);
208 
209   //===--------------------------------------------------------------------===//
210   // Symbol utilities
211   //===--------------------------------------------------------------------===//
212 
213   // Returns how many static values the given DAG `node` correspond to.
214   int getNodeValueCount(DagNode node);
215 
216 private:
217   // Pattern instantiation location followed by the location of multiclass
218   // prototypes used. This is intended to be used as a whole to
219   // PrintFatalError() on errors.
220   ArrayRef<llvm::SMLoc> loc;
221 
222   // Op's TableGen Record to wrapper object.
223   RecordOperatorMap *opMap;
224 
225   // Handy wrapper for pattern being emitted.
226   Pattern pattern;
227 
228   // Map for all bound symbols' info.
229   SymbolInfoMap symbolInfoMap;
230 
231   StaticMatcherHelper &staticMatcherHelper;
232 
233   // The next unused ID for newly created values.
234   unsigned nextValueId;
235 
236   raw_indented_ostream os;
237 
238   // Format contexts containing placeholder substitutions.
239   FmtContext fmtCtx;
240 };
241 
242 // Tracks DagNode's reference multiple times across patterns. Enables generating
243 // static matcher functions for DagNode's referenced multiple times rather than
244 // inlining them.
245 class StaticMatcherHelper {
246 public:
247   StaticMatcherHelper(RecordOperatorMap &mapper);
248 
249   // Determine if we should inline the match logic or delegate to a static
250   // function.
251   bool useStaticMatcher(DagNode node) {
252     return refStats[node] > kStaticMatcherThreshold;
253   }
254 
255   // Get the name of the static DAG matcher function corresponding to the node.
256   std::string getMatcherName(DagNode node) {
257     assert(useStaticMatcher(node));
258     return matcherNames[node];
259   }
260 
261   // Collect the `Record`s, i.e., the DRR, so that we can get the information of
262   // the duplicated DAGs.
263   void addPattern(Record *record);
264 
265   // Emit all static functions of DAG Matcher.
266   void populateStaticMatchers(raw_ostream &os);
267 
268 private:
269   static constexpr unsigned kStaticMatcherThreshold = 1;
270 
271   // Consider two patterns as down below,
272   //   DagNode_Root_A    DagNode_Root_B
273   //       \                 \
274   //     DagNode_C         DagNode_C
275   //         \                 \
276   //       DagNode_D         DagNode_D
277   //
278   // DagNode_Root_A and DagNode_Root_B share the same subtree which consists of
279   // DagNode_C and DagNode_D. Both DagNode_C and DagNode_D are referenced
280   // multiple times so we'll have static matchers for both of them. When we're
281   // emitting the match logic for DagNode_C, we will check if DagNode_D has the
282   // static matcher generated. If so, then we'll generate a call to the
283   // function, inline otherwise. In this case, inlining is not what we want. As
284   // a result, generate the static matcher in topological order to ensure all
285   // the dependent static matchers are generated and we can avoid accidentally
286   // inlining.
287   //
288   // The topological order of all the DagNodes among all patterns.
289   SmallVector<std::pair<DagNode, Record *>> topologicalOrder;
290 
291   RecordOperatorMap &opMap;
292 
293   // Records of the static function name of each DagNode
294   DenseMap<DagNode, std::string> matcherNames;
295 
296   // After collecting all the DagNode in each pattern, `refStats` records the
297   // number of users for each DagNode. We will generate the static matcher for a
298   // DagNode while the number of users exceeds a certain threshold.
299   DenseMap<DagNode, unsigned> refStats;
300 
301   // Number of static matcher generated. This is used to generate a unique name
302   // for each DagNode.
303   int staticMatcherCounter = 0;
304 };
305 
306 } // end anonymous namespace
307 
308 PatternEmitter::PatternEmitter(Record *pat, RecordOperatorMap *mapper,
309                                raw_ostream &os, StaticMatcherHelper &helper)
310     : loc(pat->getLoc()), opMap(mapper), pattern(pat, mapper),
311       symbolInfoMap(pat->getLoc()), staticMatcherHelper(helper), nextValueId(0),
312       os(os) {
313   fmtCtx.withBuilder("rewriter");
314 }
315 
316 std::string PatternEmitter::handleConstantAttr(Attribute attr,
317                                                const Twine &value) {
318   if (!attr.isConstBuildable())
319     PrintFatalError(loc, "Attribute " + attr.getAttrDefName() +
320                              " does not have the 'constBuilderCall' field");
321 
322   // TODO: Verify the constants here
323   return std::string(tgfmt(attr.getConstBuilderTemplate(), &fmtCtx, value));
324 }
325 
326 void PatternEmitter::emitStaticMatcher(DagNode tree, std::string funcName) {
327   os << formatv(
328       "static ::mlir::LogicalResult {0}(::mlir::PatternRewriter &rewriter, "
329       "::mlir::Operation *op0, ::llvm::SmallVector<::mlir::Operation "
330       "*, 4> &tblgen_ops",
331       funcName);
332 
333   // We pass the reference of the variables that need to be captured. Hence we
334   // need to collect all the symbols in the tree first.
335   pattern.collectBoundSymbols(tree, symbolInfoMap, /*isSrcPattern=*/true);
336   symbolInfoMap.assignUniqueAlternativeNames();
337   for (const auto &info : symbolInfoMap)
338     os << formatv(", {0}", info.second.getArgDecl(info.first));
339 
340   os << ") {\n";
341   os.indent();
342   os << "(void)tblgen_ops;\n";
343 
344   // Note that a static matcher is considered at least one step from the match
345   // entry.
346   emitMatch(tree, "op0", /*depth=*/1);
347 
348   os << "return ::mlir::success();\n";
349   os.unindent();
350   os << "}\n\n";
351 }
352 
353 // Helper function to match patterns.
354 void PatternEmitter::emitMatch(DagNode tree, StringRef name, int depth) {
355   if (tree.isNativeCodeCall()) {
356     emitNativeCodeMatch(tree, name, depth);
357     return;
358   }
359 
360   if (tree.isOperation()) {
361     emitOpMatch(tree, name, depth);
362     return;
363   }
364 
365   PrintFatalError(loc, "encountered non-op, non-NativeCodeCall match.");
366 }
367 
368 void PatternEmitter::emitStaticMatchCall(DagNode tree, StringRef opName) {
369   std::string funcName = staticMatcherHelper.getMatcherName(tree);
370   os << formatv("if(failed({0}(rewriter, {1}, tblgen_ops", funcName, opName);
371 
372   // TODO(chiahungduan): Add a lookupBoundSymbols() to do the subtree lookup in
373   // one pass.
374 
375   // In general, bound symbol should have the unique name in the pattern but
376   // for the operand, binding same symbol to multiple operands imply a
377   // constraint at the same time. In this case, we will rename those operands
378   // with different names. As a result, we need to collect all the symbolInfos
379   // from the DagNode then get the updated name of the local variables from the
380   // global symbolInfoMap.
381 
382   // Collect all the bound symbols in the Dag
383   SymbolInfoMap localSymbolMap(loc);
384   pattern.collectBoundSymbols(tree, localSymbolMap, /*isSrcPattern=*/true);
385 
386   for (const auto &info : localSymbolMap) {
387     auto name = info.first;
388     auto symboInfo = info.second;
389     auto ret = symbolInfoMap.findBoundSymbol(name, symboInfo);
390     os << formatv(", {0}", ret->second.getVarName(name));
391   }
392 
393   os << "))) {\n";
394   os.scope().os << "return ::mlir::failure();\n";
395   os << "}\n";
396 }
397 
398 // Helper function to match patterns.
399 void PatternEmitter::emitNativeCodeMatch(DagNode tree, StringRef opName,
400                                          int depth) {
401   LLVM_DEBUG(llvm::dbgs() << "handle NativeCodeCall matcher pattern: ");
402   LLVM_DEBUG(tree.print(llvm::dbgs()));
403   LLVM_DEBUG(llvm::dbgs() << '\n');
404 
405   // The order of generating static matcher follows the topological order so
406   // that for every dependent DagNode already have their static matcher
407   // generated if needed. The reason we check if `getMatcherName(tree).empty()`
408   // is when we are generating the static matcher for a DagNode itself. In this
409   // case, we need to emit the function body rather than a function call.
410   if (staticMatcherHelper.useStaticMatcher(tree) &&
411       !staticMatcherHelper.getMatcherName(tree).empty()) {
412     emitStaticMatchCall(tree, opName);
413 
414     // NativeCodeCall will never be at depth 0 so that we don't need to catch
415     // the root operation as emitOpMatch();
416 
417     return;
418   }
419 
420   // TODO(suderman): iterate through arguments, determine their types, output
421   // names.
422   SmallVector<std::string, 8> capture;
423 
424   raw_indented_ostream::DelimitedScope scope(os);
425 
426   for (int i = 0, e = tree.getNumArgs(); i != e; ++i) {
427     std::string argName = formatv("arg{0}_{1}", depth, i);
428     if (DagNode argTree = tree.getArgAsNestedDag(i)) {
429       os << "Value " << argName << ";\n";
430     } else {
431       auto leaf = tree.getArgAsLeaf(i);
432       if (leaf.isAttrMatcher() || leaf.isConstantAttr()) {
433         os << "Attribute " << argName << ";\n";
434       } else {
435         os << "Value " << argName << ";\n";
436       }
437     }
438 
439     capture.push_back(std::move(argName));
440   }
441 
442   auto tail = getTrailingDirectives(tree);
443   if (tail.returnType)
444     PrintFatalError(loc, "`NativeCodeCall` cannot have return type specifier");
445   auto locToUse = getLocation(tail);
446 
447   auto fmt = tree.getNativeCodeTemplate();
448   if (fmt.count("$_self") != 1)
449     PrintFatalError(loc, "NativeCodeCall must have $_self as argument for "
450                          "passing the defining Operation");
451 
452   auto nativeCodeCall = std::string(
453       tgfmt(fmt, &fmtCtx.addSubst("_loc", locToUse).withSelf(opName.str()),
454             static_cast<ArrayRef<std::string>>(capture)));
455 
456   emitMatchCheck(opName, formatv("!failed({0})", nativeCodeCall),
457                  formatv("\"{0} return failure\"", nativeCodeCall));
458 
459   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
460     auto name = tree.getArgName(i);
461     if (!name.empty() && name != "_") {
462       os << formatv("{0} = {1};\n", name, capture[i]);
463     }
464   }
465 
466   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
467     std::string argName = capture[i];
468 
469     // Handle nested DAG construct first
470     if (DagNode argTree = tree.getArgAsNestedDag(i)) {
471       PrintFatalError(
472           loc, formatv("Matching nested tree in NativeCodecall not support for "
473                        "{0} as arg {1}",
474                        argName, i));
475     }
476 
477     DagLeaf leaf = tree.getArgAsLeaf(i);
478 
479     // The parameter for native function doesn't bind any constraints.
480     if (leaf.isUnspecified())
481       continue;
482 
483     auto constraint = leaf.getAsConstraint();
484 
485     std::string self;
486     if (leaf.isAttrMatcher() || leaf.isConstantAttr())
487       self = argName;
488     else
489       self = formatv("{0}.getType()", argName);
490     emitMatchCheck(
491         opName,
492         tgfmt(constraint.getConditionTemplate(), &fmtCtx.withSelf(self)),
493         formatv("\"operand {0} of native code call '{1}' failed to satisfy "
494                 "constraint: "
495                 "'{2}'\"",
496                 i, tree.getNativeCodeTemplate(),
497                 escapeString(constraint.getSummary())));
498   }
499 
500   LLVM_DEBUG(llvm::dbgs() << "done emitting match for native code call\n");
501 }
502 
503 // Helper function to match patterns.
504 void PatternEmitter::emitOpMatch(DagNode tree, StringRef opName, int depth) {
505   Operator &op = tree.getDialectOp(opMap);
506   LLVM_DEBUG(llvm::dbgs() << "start emitting match for op '"
507                           << op.getOperationName() << "' at depth " << depth
508                           << '\n');
509 
510   auto getCastedName = [depth]() -> std::string {
511     return formatv("castedOp{0}", depth);
512   };
513 
514   // The order of generating static matcher follows the topological order so
515   // that for every dependent DagNode already have their static matcher
516   // generated if needed. The reason we check if `getMatcherName(tree).empty()`
517   // is when we are generating the static matcher for a DagNode itself. In this
518   // case, we need to emit the function body rather than a function call.
519   if (staticMatcherHelper.useStaticMatcher(tree) &&
520       !staticMatcherHelper.getMatcherName(tree).empty()) {
521     emitStaticMatchCall(tree, opName);
522     // In the codegen of rewriter, we suppose that castedOp0 will capture the
523     // root operation. Manually add it if the root DagNode is a static matcher.
524     if (depth == 0)
525       os << formatv("auto {2} = ::llvm::dyn_cast_or_null<{1}>({0}); "
526                     "(void){2};\n",
527                     opName, op.getQualCppClassName(), getCastedName());
528     return;
529   }
530 
531   std::string castedName = getCastedName();
532   os << formatv("auto {0} = ::llvm::dyn_cast<{2}>({1}); "
533                 "(void){0};\n",
534                 castedName, opName, op.getQualCppClassName());
535 
536   // Skip the operand matching at depth 0 as the pattern rewriter already does.
537   if (depth != 0)
538     emitMatchCheck(opName, /*matchStr=*/castedName,
539                    formatv("\"{0} is not {1} type\"", castedName,
540                            op.getQualCppClassName()));
541 
542   if (tree.getNumArgs() != op.getNumArgs())
543     PrintFatalError(loc, formatv("op '{0}' argument number mismatch: {1} in "
544                                  "pattern vs. {2} in definition",
545                                  op.getOperationName(), tree.getNumArgs(),
546                                  op.getNumArgs()));
547 
548   // If the operand's name is set, set to that variable.
549   auto name = tree.getSymbol();
550   if (!name.empty())
551     os << formatv("{0} = {1};\n", name, castedName);
552 
553   for (int i = 0, e = tree.getNumArgs(), nextOperand = 0; i != e; ++i) {
554     auto opArg = op.getArg(i);
555     std::string argName = formatv("op{0}", depth + 1);
556 
557     // Handle nested DAG construct first
558     if (DagNode argTree = tree.getArgAsNestedDag(i)) {
559       if (auto *operand = opArg.dyn_cast<NamedTypeConstraint *>()) {
560         if (operand->isVariableLength()) {
561           auto error = formatv("use nested DAG construct to match op {0}'s "
562                                "variadic operand #{1} unsupported now",
563                                op.getOperationName(), i);
564           PrintFatalError(loc, error);
565         }
566       }
567       os << "{\n";
568 
569       // Attributes don't count for getODSOperands.
570       // TODO: Operand is a Value, check if we should remove `getDefiningOp()`.
571       os.indent() << formatv(
572           "auto *{0} = "
573           "(*{1}.getODSOperands({2}).begin()).getDefiningOp();\n",
574           argName, castedName, nextOperand);
575       // Null check of operand's definingOp
576       emitMatchCheck(castedName, /*matchStr=*/argName,
577                      formatv("\"Operand {0} of {1} has null definingOp\"",
578                              nextOperand++, castedName));
579       emitMatch(argTree, argName, depth + 1);
580       os << formatv("tblgen_ops.push_back({0});\n", argName);
581       os.unindent() << "}\n";
582       continue;
583     }
584 
585     // Next handle DAG leaf: operand or attribute
586     if (opArg.is<NamedTypeConstraint *>()) {
587       // emitOperandMatch's argument indexing counts attributes.
588       emitOperandMatch(tree, castedName, i, nextOperand, depth);
589       ++nextOperand;
590     } else if (opArg.is<NamedAttribute *>()) {
591       emitAttributeMatch(tree, opName, i, depth);
592     } else {
593       PrintFatalError(loc, "unhandled case when matching op");
594     }
595   }
596   LLVM_DEBUG(llvm::dbgs() << "done emitting match for op '"
597                           << op.getOperationName() << "' at depth " << depth
598                           << '\n');
599 }
600 
601 void PatternEmitter::emitOperandMatch(DagNode tree, StringRef opName,
602                                       int argIndex, int operandIndex,
603                                       int depth) {
604   Operator &op = tree.getDialectOp(opMap);
605   auto *operand = op.getArg(argIndex).get<NamedTypeConstraint *>();
606   auto matcher = tree.getArgAsLeaf(argIndex);
607 
608   // If a constraint is specified, we need to generate C++ statements to
609   // check the constraint.
610   if (!matcher.isUnspecified()) {
611     if (!matcher.isOperandMatcher()) {
612       PrintFatalError(
613           loc, formatv("the {1}-th argument of op '{0}' should be an operand",
614                        op.getOperationName(), argIndex + 1));
615     }
616 
617     // Only need to verify if the matcher's type is different from the one
618     // of op definition.
619     Constraint constraint = matcher.getAsConstraint();
620     if (operand->constraint != constraint) {
621       if (operand->isVariableLength()) {
622         auto error = formatv(
623             "further constrain op {0}'s variadic operand #{1} unsupported now",
624             op.getOperationName(), argIndex);
625         PrintFatalError(loc, error);
626       }
627       auto self = formatv("(*{0}.getODSOperands({1}).begin()).getType()",
628                           opName, operandIndex);
629       emitMatchCheck(
630           opName,
631           tgfmt(constraint.getConditionTemplate(), &fmtCtx.withSelf(self)),
632           formatv("\"operand {0} of op '{1}' failed to satisfy constraint: "
633                   "'{2}'\"",
634                   operand - op.operand_begin(), op.getOperationName(),
635                   escapeString(constraint.getSummary())));
636     }
637   }
638 
639   // Capture the value
640   auto name = tree.getArgName(argIndex);
641   // `$_` is a special symbol to ignore op argument matching.
642   if (!name.empty() && name != "_") {
643     // We need to subtract the number of attributes before this operand to get
644     // the index in the operand list.
645     auto numPrevAttrs = std::count_if(
646         op.arg_begin(), op.arg_begin() + argIndex,
647         [](const Argument &arg) { return arg.is<NamedAttribute *>(); });
648 
649     auto res = symbolInfoMap.findBoundSymbol(name, tree, op, argIndex);
650     os << formatv("{0} = {1}.getODSOperands({2});\n",
651                   res->second.getVarName(name), opName,
652                   argIndex - numPrevAttrs);
653   }
654 }
655 
656 void PatternEmitter::emitAttributeMatch(DagNode tree, StringRef opName,
657                                         int argIndex, int depth) {
658   Operator &op = tree.getDialectOp(opMap);
659   auto *namedAttr = op.getArg(argIndex).get<NamedAttribute *>();
660   const auto &attr = namedAttr->attr;
661 
662   os << "{\n";
663   os.indent() << formatv("auto tblgen_attr = {0}->getAttrOfType<{1}>(\"{2}\");"
664                          "(void)tblgen_attr;\n",
665                          opName, attr.getStorageType(), namedAttr->name);
666 
667   // TODO: This should use getter method to avoid duplication.
668   if (attr.hasDefaultValue()) {
669     os << "if (!tblgen_attr) tblgen_attr = "
670        << std::string(tgfmt(attr.getConstBuilderTemplate(), &fmtCtx,
671                             attr.getDefaultValue()))
672        << ";\n";
673   } else if (attr.isOptional()) {
674     // For a missing attribute that is optional according to definition, we
675     // should just capture a mlir::Attribute() to signal the missing state.
676     // That is precisely what getAttr() returns on missing attributes.
677   } else {
678     emitMatchCheck(opName, tgfmt("tblgen_attr", &fmtCtx),
679                    formatv("\"expected op '{0}' to have attribute '{1}' "
680                            "of type '{2}'\"",
681                            op.getOperationName(), namedAttr->name,
682                            attr.getStorageType()));
683   }
684 
685   auto matcher = tree.getArgAsLeaf(argIndex);
686   if (!matcher.isUnspecified()) {
687     if (!matcher.isAttrMatcher()) {
688       PrintFatalError(
689           loc, formatv("the {1}-th argument of op '{0}' should be an attribute",
690                        op.getOperationName(), argIndex + 1));
691     }
692 
693     // If a constraint is specified, we need to generate C++ statements to
694     // check the constraint.
695     emitMatchCheck(
696         opName,
697         tgfmt(matcher.getConditionTemplate(), &fmtCtx.withSelf("tblgen_attr")),
698         formatv("\"op '{0}' attribute '{1}' failed to satisfy constraint: "
699                 "'{2}'\"",
700                 op.getOperationName(), namedAttr->name,
701                 escapeString(matcher.getAsConstraint().getSummary())));
702   }
703 
704   // Capture the value
705   auto name = tree.getArgName(argIndex);
706   // `$_` is a special symbol to ignore op argument matching.
707   if (!name.empty() && name != "_") {
708     os << formatv("{0} = tblgen_attr;\n", name);
709   }
710 
711   os.unindent() << "}\n";
712 }
713 
714 void PatternEmitter::emitMatchCheck(
715     StringRef opName, const FmtObjectBase &matchFmt,
716     const llvm::formatv_object_base &failureFmt) {
717   emitMatchCheck(opName, matchFmt.str(), failureFmt.str());
718 }
719 
720 void PatternEmitter::emitMatchCheck(StringRef opName,
721                                     const std::string &matchStr,
722                                     const std::string &failureStr) {
723 
724   os << "if (!(" << matchStr << "))";
725   os.scope("{\n", "\n}\n").os << "return rewriter.notifyMatchFailure(" << opName
726                               << ", [&](::mlir::Diagnostic &diag) {\n  diag << "
727                               << failureStr << ";\n});";
728 }
729 
730 void PatternEmitter::emitMatchLogic(DagNode tree, StringRef opName) {
731   LLVM_DEBUG(llvm::dbgs() << "--- start emitting match logic ---\n");
732   int depth = 0;
733   emitMatch(tree, opName, depth);
734 
735   for (auto &appliedConstraint : pattern.getConstraints()) {
736     auto &constraint = appliedConstraint.constraint;
737     auto &entities = appliedConstraint.entities;
738 
739     auto condition = constraint.getConditionTemplate();
740     if (isa<TypeConstraint>(constraint)) {
741       auto self = formatv("({0}.getType())",
742                           symbolInfoMap.getValueAndRangeUse(entities.front()));
743       emitMatchCheck(
744           opName, tgfmt(condition, &fmtCtx.withSelf(self.str())),
745           formatv("\"value entity '{0}' failed to satisfy constraint: '{1}'\"",
746                   entities.front(), escapeString(constraint.getSummary())));
747 
748     } else if (isa<AttrConstraint>(constraint)) {
749       PrintFatalError(
750           loc, "cannot use AttrConstraint in Pattern multi-entity constraints");
751     } else {
752       // TODO: replace formatv arguments with the exact specified
753       // args.
754       if (entities.size() > 4) {
755         PrintFatalError(loc, "only support up to 4-entity constraints now");
756       }
757       SmallVector<std::string, 4> names;
758       int i = 0;
759       for (int e = entities.size(); i < e; ++i)
760         names.push_back(symbolInfoMap.getValueAndRangeUse(entities[i]));
761       std::string self = appliedConstraint.self;
762       if (!self.empty())
763         self = symbolInfoMap.getValueAndRangeUse(self);
764       for (; i < 4; ++i)
765         names.push_back("<unused>");
766       emitMatchCheck(opName,
767                      tgfmt(condition, &fmtCtx.withSelf(self), names[0],
768                            names[1], names[2], names[3]),
769                      formatv("\"entities '{0}' failed to satisfy constraint: "
770                              "'{1}'\"",
771                              llvm::join(entities, ", "),
772                              escapeString(constraint.getSummary())));
773     }
774   }
775 
776   // Some of the operands could be bound to the same symbol name, we need
777   // to enforce equality constraint on those.
778   // TODO: we should be able to emit equality checks early
779   // and short circuit unnecessary work if vars are not equal.
780   for (auto symbolInfoIt = symbolInfoMap.begin();
781        symbolInfoIt != symbolInfoMap.end();) {
782     auto range = symbolInfoMap.getRangeOfEqualElements(symbolInfoIt->first);
783     auto startRange = range.first;
784     auto endRange = range.second;
785 
786     auto firstOperand = symbolInfoIt->second.getVarName(symbolInfoIt->first);
787     for (++startRange; startRange != endRange; ++startRange) {
788       auto secondOperand = startRange->second.getVarName(symbolInfoIt->first);
789       emitMatchCheck(
790           opName,
791           formatv("*{0}.begin() == *{1}.begin()", firstOperand, secondOperand),
792           formatv("\"Operands '{0}' and '{1}' must be equal\"", firstOperand,
793                   secondOperand));
794     }
795 
796     symbolInfoIt = endRange;
797   }
798 
799   LLVM_DEBUG(llvm::dbgs() << "--- done emitting match logic ---\n");
800 }
801 
802 void PatternEmitter::collectOps(DagNode tree,
803                                 llvm::SmallPtrSetImpl<const Operator *> &ops) {
804   // Check if this tree is an operation.
805   if (tree.isOperation()) {
806     const Operator &op = tree.getDialectOp(opMap);
807     LLVM_DEBUG(llvm::dbgs()
808                << "found operation " << op.getOperationName() << '\n');
809     ops.insert(&op);
810   }
811 
812   // Recurse the arguments of the tree.
813   for (unsigned i = 0, e = tree.getNumArgs(); i != e; ++i)
814     if (auto child = tree.getArgAsNestedDag(i))
815       collectOps(child, ops);
816 }
817 
818 void PatternEmitter::emit(StringRef rewriteName) {
819   // Get the DAG tree for the source pattern.
820   DagNode sourceTree = pattern.getSourcePattern();
821 
822   const Operator &rootOp = pattern.getSourceRootOp();
823   auto rootName = rootOp.getOperationName();
824 
825   // Collect the set of result operations.
826   llvm::SmallPtrSet<const Operator *, 4> resultOps;
827   LLVM_DEBUG(llvm::dbgs() << "start collecting ops used in result patterns\n");
828   for (unsigned i = 0, e = pattern.getNumResultPatterns(); i != e; ++i) {
829     collectOps(pattern.getResultPattern(i), resultOps);
830   }
831   LLVM_DEBUG(llvm::dbgs() << "done collecting ops used in result patterns\n");
832 
833   // Emit RewritePattern for Pattern.
834   auto locs = pattern.getLocation();
835   os << formatv("/* Generated from:\n    {0:$[ instantiating\n    ]}\n*/\n",
836                 make_range(locs.rbegin(), locs.rend()));
837   os << formatv(R"(struct {0} : public ::mlir::RewritePattern {
838   {0}(::mlir::MLIRContext *context)
839       : ::mlir::RewritePattern("{1}", {2}, context, {{)",
840                 rewriteName, rootName, pattern.getBenefit());
841   // Sort result operators by name.
842   llvm::SmallVector<const Operator *, 4> sortedResultOps(resultOps.begin(),
843                                                          resultOps.end());
844   llvm::sort(sortedResultOps, [&](const Operator *lhs, const Operator *rhs) {
845     return lhs->getOperationName() < rhs->getOperationName();
846   });
847   llvm::interleaveComma(sortedResultOps, os, [&](const Operator *op) {
848     os << '"' << op->getOperationName() << '"';
849   });
850   os << "}) {}\n";
851 
852   // Emit matchAndRewrite() function.
853   {
854     auto classScope = os.scope();
855     os.reindent(R"(
856     ::mlir::LogicalResult matchAndRewrite(::mlir::Operation *op0,
857         ::mlir::PatternRewriter &rewriter) const override {)")
858         << '\n';
859     {
860       auto functionScope = os.scope();
861 
862       // Register all symbols bound in the source pattern.
863       pattern.collectSourcePatternBoundSymbols(symbolInfoMap);
864 
865       LLVM_DEBUG(llvm::dbgs()
866                  << "start creating local variables for capturing matches\n");
867       os << "// Variables for capturing values and attributes used while "
868             "creating ops\n";
869       // Create local variables for storing the arguments and results bound
870       // to symbols.
871       for (const auto &symbolInfoPair : symbolInfoMap) {
872         const auto &symbol = symbolInfoPair.first;
873         const auto &info = symbolInfoPair.second;
874 
875         os << info.getVarDecl(symbol);
876       }
877       // TODO: capture ops with consistent numbering so that it can be
878       // reused for fused loc.
879       os << "::llvm::SmallVector<::mlir::Operation *, 4> tblgen_ops;\n\n";
880       LLVM_DEBUG(llvm::dbgs()
881                  << "done creating local variables for capturing matches\n");
882 
883       os << "// Match\n";
884       os << "tblgen_ops.push_back(op0);\n";
885       emitMatchLogic(sourceTree, "op0");
886 
887       os << "\n// Rewrite\n";
888       emitRewriteLogic();
889 
890       os << "return ::mlir::success();\n";
891     }
892     os << "};\n";
893   }
894   os << "};\n\n";
895 }
896 
897 void PatternEmitter::emitRewriteLogic() {
898   LLVM_DEBUG(llvm::dbgs() << "--- start emitting rewrite logic ---\n");
899   const Operator &rootOp = pattern.getSourceRootOp();
900   int numExpectedResults = rootOp.getNumResults();
901   int numResultPatterns = pattern.getNumResultPatterns();
902 
903   // First register all symbols bound to ops generated in result patterns.
904   pattern.collectResultPatternBoundSymbols(symbolInfoMap);
905 
906   // Only the last N static values generated are used to replace the matched
907   // root N-result op. We need to calculate the starting index (of the results
908   // of the matched op) each result pattern is to replace.
909   SmallVector<int, 4> offsets(numResultPatterns + 1, numExpectedResults);
910   // If we don't need to replace any value at all, set the replacement starting
911   // index as the number of result patterns so we skip all of them when trying
912   // to replace the matched op's results.
913   int replStartIndex = numExpectedResults == 0 ? numResultPatterns : -1;
914   for (int i = numResultPatterns - 1; i >= 0; --i) {
915     auto numValues = getNodeValueCount(pattern.getResultPattern(i));
916     offsets[i] = offsets[i + 1] - numValues;
917     if (offsets[i] == 0) {
918       if (replStartIndex == -1)
919         replStartIndex = i;
920     } else if (offsets[i] < 0 && offsets[i + 1] > 0) {
921       auto error = formatv(
922           "cannot use the same multi-result op '{0}' to generate both "
923           "auxiliary values and values to be used for replacing the matched op",
924           pattern.getResultPattern(i).getSymbol());
925       PrintFatalError(loc, error);
926     }
927   }
928 
929   if (offsets.front() > 0) {
930     const char error[] = "no enough values generated to replace the matched op";
931     PrintFatalError(loc, error);
932   }
933 
934   os << "auto odsLoc = rewriter.getFusedLoc({";
935   for (int i = 0, e = pattern.getSourcePattern().getNumOps(); i != e; ++i) {
936     os << (i ? ", " : "") << "tblgen_ops[" << i << "]->getLoc()";
937   }
938   os << "}); (void)odsLoc;\n";
939 
940   // Process auxiliary result patterns.
941   for (int i = 0; i < replStartIndex; ++i) {
942     DagNode resultTree = pattern.getResultPattern(i);
943     auto val = handleResultPattern(resultTree, offsets[i], 0);
944     // Normal op creation will be streamed to `os` by the above call; but
945     // NativeCodeCall will only be materialized to `os` if it is used. Here
946     // we are handling auxiliary patterns so we want the side effect even if
947     // NativeCodeCall is not replacing matched root op's results.
948     if (resultTree.isNativeCodeCall() &&
949         resultTree.getNumReturnsOfNativeCode() == 0)
950       os << val << ";\n";
951   }
952 
953   if (numExpectedResults == 0) {
954     assert(replStartIndex >= numResultPatterns &&
955            "invalid auxiliary vs. replacement pattern division!");
956     // No result to replace. Just erase the op.
957     os << "rewriter.eraseOp(op0);\n";
958   } else {
959     // Process replacement result patterns.
960     os << "::llvm::SmallVector<::mlir::Value, 4> tblgen_repl_values;\n";
961     for (int i = replStartIndex; i < numResultPatterns; ++i) {
962       DagNode resultTree = pattern.getResultPattern(i);
963       auto val = handleResultPattern(resultTree, offsets[i], 0);
964       os << "\n";
965       // Resolve each symbol for all range use so that we can loop over them.
966       // We need an explicit cast to `SmallVector` to capture the cases where
967       // `{0}` resolves to an `Operation::result_range` as well as cases that
968       // are not iterable (e.g. vector that gets wrapped in additional braces by
969       // RewriterGen).
970       // TODO: Revisit the need for materializing a vector.
971       os << symbolInfoMap.getAllRangeUse(
972           val,
973           "for (auto v: ::llvm::SmallVector<::mlir::Value, 4>{ {0} }) {{\n"
974           "  tblgen_repl_values.push_back(v);\n}\n",
975           "\n");
976     }
977     os << "\nrewriter.replaceOp(op0, tblgen_repl_values);\n";
978   }
979 
980   LLVM_DEBUG(llvm::dbgs() << "--- done emitting rewrite logic ---\n");
981 }
982 
983 std::string PatternEmitter::getUniqueSymbol(const Operator *op) {
984   return std::string(
985       formatv("tblgen_{0}_{1}", op->getCppClassName(), nextValueId++));
986 }
987 
988 std::string PatternEmitter::handleResultPattern(DagNode resultTree,
989                                                 int resultIndex, int depth) {
990   LLVM_DEBUG(llvm::dbgs() << "handle result pattern: ");
991   LLVM_DEBUG(resultTree.print(llvm::dbgs()));
992   LLVM_DEBUG(llvm::dbgs() << '\n');
993 
994   if (resultTree.isLocationDirective()) {
995     PrintFatalError(loc,
996                     "location directive can only be used with op creation");
997   }
998 
999   if (resultTree.isNativeCodeCall())
1000     return handleReplaceWithNativeCodeCall(resultTree, depth);
1001 
1002   if (resultTree.isReplaceWithValue())
1003     return handleReplaceWithValue(resultTree).str();
1004 
1005   // Normal op creation.
1006   auto symbol = handleOpCreation(resultTree, resultIndex, depth);
1007   if (resultTree.getSymbol().empty()) {
1008     // This is an op not explicitly bound to a symbol in the rewrite rule.
1009     // Register the auto-generated symbol for it.
1010     symbolInfoMap.bindOpResult(symbol, pattern.getDialectOp(resultTree));
1011   }
1012   return symbol;
1013 }
1014 
1015 StringRef PatternEmitter::handleReplaceWithValue(DagNode tree) {
1016   assert(tree.isReplaceWithValue());
1017 
1018   if (tree.getNumArgs() != 1) {
1019     PrintFatalError(
1020         loc, "replaceWithValue directive must take exactly one argument");
1021   }
1022 
1023   if (!tree.getSymbol().empty()) {
1024     PrintFatalError(loc, "cannot bind symbol to replaceWithValue");
1025   }
1026 
1027   return tree.getArgName(0);
1028 }
1029 
1030 std::string PatternEmitter::handleLocationDirective(DagNode tree) {
1031   assert(tree.isLocationDirective());
1032   auto lookUpArgLoc = [this, &tree](int idx) {
1033     const auto *const lookupFmt = "(*{0}.begin()).getLoc()";
1034     return symbolInfoMap.getAllRangeUse(tree.getArgName(idx), lookupFmt);
1035   };
1036 
1037   if (tree.getNumArgs() == 0)
1038     llvm::PrintFatalError(
1039         "At least one argument to location directive required");
1040 
1041   if (!tree.getSymbol().empty())
1042     PrintFatalError(loc, "cannot bind symbol to location");
1043 
1044   if (tree.getNumArgs() == 1) {
1045     DagLeaf leaf = tree.getArgAsLeaf(0);
1046     if (leaf.isStringAttr())
1047       return formatv("::mlir::NameLoc::get(rewriter.getIdentifier(\"{0}\"))",
1048                      leaf.getStringAttr())
1049           .str();
1050     return lookUpArgLoc(0);
1051   }
1052 
1053   std::string ret;
1054   llvm::raw_string_ostream os(ret);
1055   std::string strAttr;
1056   os << "rewriter.getFusedLoc({";
1057   bool first = true;
1058   for (int i = 0, e = tree.getNumArgs(); i != e; ++i) {
1059     DagLeaf leaf = tree.getArgAsLeaf(i);
1060     // Handle the optional string value.
1061     if (leaf.isStringAttr()) {
1062       if (!strAttr.empty())
1063         llvm::PrintFatalError("Only one string attribute may be specified");
1064       strAttr = leaf.getStringAttr();
1065       continue;
1066     }
1067     os << (first ? "" : ", ") << lookUpArgLoc(i);
1068     first = false;
1069   }
1070   os << "}";
1071   if (!strAttr.empty()) {
1072     os << ", rewriter.getStringAttr(\"" << strAttr << "\")";
1073   }
1074   os << ")";
1075   return os.str();
1076 }
1077 
1078 std::string PatternEmitter::handleReturnTypeArg(DagNode returnType, int i,
1079                                                 int depth) {
1080   // Nested NativeCodeCall.
1081   if (auto dagNode = returnType.getArgAsNestedDag(i)) {
1082     if (!dagNode.isNativeCodeCall())
1083       PrintFatalError(loc, "nested DAG in `returnType` must be a native code "
1084                            "call");
1085     return handleReplaceWithNativeCodeCall(dagNode, depth);
1086   }
1087   // String literal.
1088   auto dagLeaf = returnType.getArgAsLeaf(i);
1089   if (dagLeaf.isStringAttr())
1090     return tgfmt(dagLeaf.getStringAttr(), &fmtCtx);
1091   return tgfmt(
1092       "$0.getType()", &fmtCtx,
1093       handleOpArgument(returnType.getArgAsLeaf(i), returnType.getArgName(i)));
1094 }
1095 
1096 std::string PatternEmitter::handleOpArgument(DagLeaf leaf,
1097                                              StringRef patArgName) {
1098   if (leaf.isStringAttr())
1099     PrintFatalError(loc, "raw string not supported as argument");
1100   if (leaf.isConstantAttr()) {
1101     auto constAttr = leaf.getAsConstantAttr();
1102     return handleConstantAttr(constAttr.getAttribute(),
1103                               constAttr.getConstantValue());
1104   }
1105   if (leaf.isEnumAttrCase()) {
1106     auto enumCase = leaf.getAsEnumAttrCase();
1107     if (enumCase.isStrCase())
1108       return handleConstantAttr(enumCase, "\"" + enumCase.getSymbol() + "\"");
1109     // This is an enum case backed by an IntegerAttr. We need to get its value
1110     // to build the constant.
1111     std::string val = std::to_string(enumCase.getValue());
1112     return handleConstantAttr(enumCase, val);
1113   }
1114 
1115   LLVM_DEBUG(llvm::dbgs() << "handle argument '" << patArgName << "'\n");
1116   auto argName = symbolInfoMap.getValueAndRangeUse(patArgName);
1117   if (leaf.isUnspecified() || leaf.isOperandMatcher()) {
1118     LLVM_DEBUG(llvm::dbgs() << "replace " << patArgName << " with '" << argName
1119                             << "' (via symbol ref)\n");
1120     return argName;
1121   }
1122   if (leaf.isNativeCodeCall()) {
1123     auto repl = tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(argName));
1124     LLVM_DEBUG(llvm::dbgs() << "replace " << patArgName << " with '" << repl
1125                             << "' (via NativeCodeCall)\n");
1126     return std::string(repl);
1127   }
1128   PrintFatalError(loc, "unhandled case when rewriting op");
1129 }
1130 
1131 std::string PatternEmitter::handleReplaceWithNativeCodeCall(DagNode tree,
1132                                                             int depth) {
1133   LLVM_DEBUG(llvm::dbgs() << "handle NativeCodeCall pattern: ");
1134   LLVM_DEBUG(tree.print(llvm::dbgs()));
1135   LLVM_DEBUG(llvm::dbgs() << '\n');
1136 
1137   auto fmt = tree.getNativeCodeTemplate();
1138 
1139   SmallVector<std::string, 16> attrs;
1140 
1141   auto tail = getTrailingDirectives(tree);
1142   if (tail.returnType)
1143     PrintFatalError(loc, "`NativeCodeCall` cannot have return type specifier");
1144   auto locToUse = getLocation(tail);
1145 
1146   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
1147     if (tree.isNestedDagArg(i)) {
1148       attrs.push_back(
1149           handleResultPattern(tree.getArgAsNestedDag(i), i, depth + 1));
1150     } else {
1151       attrs.push_back(
1152           handleOpArgument(tree.getArgAsLeaf(i), tree.getArgName(i)));
1153     }
1154     LLVM_DEBUG(llvm::dbgs() << "NativeCodeCall argument #" << i
1155                             << " replacement: " << attrs[i] << "\n");
1156   }
1157 
1158   std::string symbol = tgfmt(fmt, &fmtCtx.addSubst("_loc", locToUse),
1159                              static_cast<ArrayRef<std::string>>(attrs));
1160 
1161   // In general, NativeCodeCall without naming binding don't need this. To
1162   // ensure void helper function has been correctly labeled, i.e., use
1163   // NativeCodeCallVoid, we cache the result to a local variable so that we will
1164   // get a compilation error in the auto-generated file.
1165   // Example.
1166   //   // In the td file
1167   //   Pat<(...), (NativeCodeCall<Foo> ...)>
1168   //
1169   //   ---
1170   //
1171   //   // In the auto-generated .cpp
1172   //   ...
1173   //   // Causes compilation error if Foo() returns void.
1174   //   auto nativeVar = Foo();
1175   //   ...
1176   if (tree.getNumReturnsOfNativeCode() != 0) {
1177     // Determine the local variable name for return value.
1178     std::string varName =
1179         SymbolInfoMap::getValuePackName(tree.getSymbol()).str();
1180     if (varName.empty()) {
1181       varName = formatv("nativeVar_{0}", nextValueId++);
1182       // Register the local variable for later uses.
1183       symbolInfoMap.bindValues(varName, tree.getNumReturnsOfNativeCode());
1184     }
1185 
1186     // Catch the return value of helper function.
1187     os << formatv("auto {0} = {1}; (void){0};\n", varName, symbol);
1188 
1189     if (!tree.getSymbol().empty())
1190       symbol = tree.getSymbol().str();
1191     else
1192       symbol = varName;
1193   }
1194 
1195   return symbol;
1196 }
1197 
1198 int PatternEmitter::getNodeValueCount(DagNode node) {
1199   if (node.isOperation()) {
1200     // If the op is bound to a symbol in the rewrite rule, query its result
1201     // count from the symbol info map.
1202     auto symbol = node.getSymbol();
1203     if (!symbol.empty()) {
1204       return symbolInfoMap.getStaticValueCount(symbol);
1205     }
1206     // Otherwise this is an unbound op; we will use all its results.
1207     return pattern.getDialectOp(node).getNumResults();
1208   }
1209 
1210   if (node.isNativeCodeCall())
1211     return node.getNumReturnsOfNativeCode();
1212 
1213   return 1;
1214 }
1215 
1216 PatternEmitter::TrailingDirectives
1217 PatternEmitter::getTrailingDirectives(DagNode tree) {
1218   TrailingDirectives tail = {DagNode(nullptr), DagNode(nullptr), 0};
1219 
1220   // Look backwards through the arguments.
1221   auto numPatArgs = tree.getNumArgs();
1222   for (int i = numPatArgs - 1; i >= 0; --i) {
1223     auto dagArg = tree.getArgAsNestedDag(i);
1224     // A leaf is not a directive. Stop looking.
1225     if (!dagArg)
1226       break;
1227 
1228     auto isLocation = dagArg.isLocationDirective();
1229     auto isReturnType = dagArg.isReturnTypeDirective();
1230     // If encountered a DAG node that isn't a trailing directive, stop looking.
1231     if (!(isLocation || isReturnType))
1232       break;
1233     // Save the directive, but error if one of the same type was already
1234     // found.
1235     ++tail.numDirectives;
1236     if (isLocation) {
1237       if (tail.location)
1238         PrintFatalError(loc, "`location` directive can only be specified "
1239                              "once");
1240       tail.location = dagArg;
1241     } else if (isReturnType) {
1242       if (tail.returnType)
1243         PrintFatalError(loc, "`returnType` directive can only be specified "
1244                              "once");
1245       tail.returnType = dagArg;
1246     }
1247   }
1248 
1249   return tail;
1250 }
1251 
1252 std::string
1253 PatternEmitter::getLocation(PatternEmitter::TrailingDirectives &tail) {
1254   if (tail.location)
1255     return handleLocationDirective(tail.location);
1256 
1257   // If no explicit location is given, use the default, all fused, location.
1258   return "odsLoc";
1259 }
1260 
1261 std::string PatternEmitter::handleOpCreation(DagNode tree, int resultIndex,
1262                                              int depth) {
1263   LLVM_DEBUG(llvm::dbgs() << "create op for pattern: ");
1264   LLVM_DEBUG(tree.print(llvm::dbgs()));
1265   LLVM_DEBUG(llvm::dbgs() << '\n');
1266 
1267   Operator &resultOp = tree.getDialectOp(opMap);
1268   auto numOpArgs = resultOp.getNumArgs();
1269   auto numPatArgs = tree.getNumArgs();
1270 
1271   auto tail = getTrailingDirectives(tree);
1272   auto locToUse = getLocation(tail);
1273 
1274   auto inPattern = numPatArgs - tail.numDirectives;
1275   if (numOpArgs != inPattern) {
1276     PrintFatalError(loc,
1277                     formatv("resultant op '{0}' argument number mismatch: "
1278                             "{1} in pattern vs. {2} in definition",
1279                             resultOp.getOperationName(), inPattern, numOpArgs));
1280   }
1281 
1282   // A map to collect all nested DAG child nodes' names, with operand index as
1283   // the key. This includes both bound and unbound child nodes.
1284   ChildNodeIndexNameMap childNodeNames;
1285 
1286   // First go through all the child nodes who are nested DAG constructs to
1287   // create ops for them and remember the symbol names for them, so that we can
1288   // use the results in the current node. This happens in a recursive manner.
1289   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
1290     if (auto child = tree.getArgAsNestedDag(i))
1291       childNodeNames[i] = handleResultPattern(child, i, depth + 1);
1292   }
1293 
1294   // The name of the local variable holding this op.
1295   std::string valuePackName;
1296   // The symbol for holding the result of this pattern. Note that the result of
1297   // this pattern is not necessarily the same as the variable created by this
1298   // pattern because we can use `__N` suffix to refer only a specific result if
1299   // the generated op is a multi-result op.
1300   std::string resultValue;
1301   if (tree.getSymbol().empty()) {
1302     // No symbol is explicitly bound to this op in the pattern. Generate a
1303     // unique name.
1304     valuePackName = resultValue = getUniqueSymbol(&resultOp);
1305   } else {
1306     resultValue = std::string(tree.getSymbol());
1307     // Strip the index to get the name for the value pack and use it to name the
1308     // local variable for the op.
1309     valuePackName = std::string(SymbolInfoMap::getValuePackName(resultValue));
1310   }
1311 
1312   // Create the local variable for this op.
1313   os << formatv("{0} {1};\n{{\n", resultOp.getQualCppClassName(),
1314                 valuePackName);
1315 
1316   // Right now ODS don't have general type inference support. Except a few
1317   // special cases listed below, DRR needs to supply types for all results
1318   // when building an op.
1319   bool isSameOperandsAndResultType =
1320       resultOp.getTrait("::mlir::OpTrait::SameOperandsAndResultType");
1321   bool useFirstAttr =
1322       resultOp.getTrait("::mlir::OpTrait::FirstAttrDerivedResultType");
1323 
1324   if (!tail.returnType && (isSameOperandsAndResultType || useFirstAttr)) {
1325     // We know how to deduce the result type for ops with these traits and we've
1326     // generated builders taking aggregate parameters. Use those builders to
1327     // create the ops.
1328 
1329     // First prepare local variables for op arguments used in builder call.
1330     createAggregateLocalVarsForOpArgs(tree, childNodeNames, depth);
1331 
1332     // Then create the op.
1333     os.scope("", "\n}\n").os << formatv(
1334         "{0} = rewriter.create<{1}>({2}, tblgen_values, tblgen_attrs);",
1335         valuePackName, resultOp.getQualCppClassName(), locToUse);
1336     return resultValue;
1337   }
1338 
1339   bool usePartialResults = valuePackName != resultValue;
1340 
1341   if (!tail.returnType && (usePartialResults || depth > 0 || resultIndex < 0)) {
1342     // For these cases (broadcastable ops, op results used both as auxiliary
1343     // values and replacement values, ops in nested patterns, auxiliary ops), we
1344     // still need to supply the result types when building the op. But because
1345     // we don't generate a builder automatically with ODS for them, it's the
1346     // developer's responsibility to make sure such a builder (with result type
1347     // deduction ability) exists. We go through the separate-parameter builder
1348     // here given that it's easier for developers to write compared to
1349     // aggregate-parameter builders.
1350     createSeparateLocalVarsForOpArgs(tree, childNodeNames);
1351 
1352     os.scope().os << formatv("{0} = rewriter.create<{1}>({2}", valuePackName,
1353                              resultOp.getQualCppClassName(), locToUse);
1354     supplyValuesForOpArgs(tree, childNodeNames, depth);
1355     os << "\n  );\n}\n";
1356     return resultValue;
1357   }
1358 
1359   // If we are provided explicit return types, use them to build the op.
1360   // However, if depth == 0 and resultIndex >= 0, it means we are replacing
1361   // the values generated from the source pattern root op. Then we must use the
1362   // source pattern's value types to determine the value type of the generated
1363   // op here.
1364   if (depth == 0 && resultIndex >= 0 && tail.returnType)
1365     PrintFatalError(loc, "Cannot specify explicit return types in an op whose "
1366                          "return values replace the source pattern's root op");
1367 
1368   // First prepare local variables for op arguments used in builder call.
1369   createAggregateLocalVarsForOpArgs(tree, childNodeNames, depth);
1370 
1371   // Then prepare the result types. We need to specify the types for all
1372   // results.
1373   os.indent() << formatv("::mlir::SmallVector<::mlir::Type, 4> tblgen_types; "
1374                          "(void)tblgen_types;\n");
1375   int numResults = resultOp.getNumResults();
1376   if (tail.returnType) {
1377     auto numRetTys = tail.returnType.getNumArgs();
1378     for (int i = 0; i < numRetTys; ++i) {
1379       auto varName = handleReturnTypeArg(tail.returnType, i, depth + 1);
1380       os << "tblgen_types.push_back(" << varName << ");\n";
1381     }
1382   } else {
1383     if (numResults != 0) {
1384       // Copy the result types from the source pattern.
1385       for (int i = 0; i < numResults; ++i)
1386         os << formatv("for (auto v: castedOp0.getODSResults({0})) {{\n"
1387                       "  tblgen_types.push_back(v.getType());\n}\n",
1388                       resultIndex + i);
1389     }
1390   }
1391   os << formatv("{0} = rewriter.create<{1}>({2}, tblgen_types, "
1392                 "tblgen_values, tblgen_attrs);\n",
1393                 valuePackName, resultOp.getQualCppClassName(), locToUse);
1394   os.unindent() << "}\n";
1395   return resultValue;
1396 }
1397 
1398 void PatternEmitter::createSeparateLocalVarsForOpArgs(
1399     DagNode node, ChildNodeIndexNameMap &childNodeNames) {
1400   Operator &resultOp = node.getDialectOp(opMap);
1401 
1402   // Now prepare operands used for building this op:
1403   // * If the operand is non-variadic, we create a `Value` local variable.
1404   // * If the operand is variadic, we create a `SmallVector<Value>` local
1405   //   variable.
1406 
1407   int valueIndex = 0; // An index for uniquing local variable names.
1408   for (int argIndex = 0, e = resultOp.getNumArgs(); argIndex < e; ++argIndex) {
1409     const auto *operand =
1410         resultOp.getArg(argIndex).dyn_cast<NamedTypeConstraint *>();
1411     // We do not need special handling for attributes.
1412     if (!operand)
1413       continue;
1414 
1415     raw_indented_ostream::DelimitedScope scope(os);
1416     std::string varName;
1417     if (operand->isVariadic()) {
1418       varName = std::string(formatv("tblgen_values_{0}", valueIndex++));
1419       os << formatv("::mlir::SmallVector<::mlir::Value, 4> {0};\n", varName);
1420       std::string range;
1421       if (node.isNestedDagArg(argIndex)) {
1422         range = childNodeNames[argIndex];
1423       } else {
1424         range = std::string(node.getArgName(argIndex));
1425       }
1426       // Resolve the symbol for all range use so that we have a uniform way of
1427       // capturing the values.
1428       range = symbolInfoMap.getValueAndRangeUse(range);
1429       os << formatv("for (auto v: {0}) {{\n  {1}.push_back(v);\n}\n", range,
1430                     varName);
1431     } else {
1432       varName = std::string(formatv("tblgen_value_{0}", valueIndex++));
1433       os << formatv("::mlir::Value {0} = ", varName);
1434       if (node.isNestedDagArg(argIndex)) {
1435         os << symbolInfoMap.getValueAndRangeUse(childNodeNames[argIndex]);
1436       } else {
1437         DagLeaf leaf = node.getArgAsLeaf(argIndex);
1438         auto symbol =
1439             symbolInfoMap.getValueAndRangeUse(node.getArgName(argIndex));
1440         if (leaf.isNativeCodeCall()) {
1441           os << std::string(
1442               tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(symbol)));
1443         } else {
1444           os << symbol;
1445         }
1446       }
1447       os << ";\n";
1448     }
1449 
1450     // Update to use the newly created local variable for building the op later.
1451     childNodeNames[argIndex] = varName;
1452   }
1453 }
1454 
1455 void PatternEmitter::supplyValuesForOpArgs(
1456     DagNode node, const ChildNodeIndexNameMap &childNodeNames, int depth) {
1457   Operator &resultOp = node.getDialectOp(opMap);
1458   for (int argIndex = 0, numOpArgs = resultOp.getNumArgs();
1459        argIndex != numOpArgs; ++argIndex) {
1460     // Start each argument on its own line.
1461     os << ",\n    ";
1462 
1463     Argument opArg = resultOp.getArg(argIndex);
1464     // Handle the case of operand first.
1465     if (auto *operand = opArg.dyn_cast<NamedTypeConstraint *>()) {
1466       if (!operand->name.empty())
1467         os << "/*" << operand->name << "=*/";
1468       os << childNodeNames.lookup(argIndex);
1469       continue;
1470     }
1471 
1472     // The argument in the op definition.
1473     auto opArgName = resultOp.getArgName(argIndex);
1474     if (auto subTree = node.getArgAsNestedDag(argIndex)) {
1475       if (!subTree.isNativeCodeCall())
1476         PrintFatalError(loc, "only NativeCodeCall allowed in nested dag node "
1477                              "for creating attribute");
1478       os << formatv("/*{0}=*/{1}", opArgName, childNodeNames.lookup(argIndex));
1479     } else {
1480       auto leaf = node.getArgAsLeaf(argIndex);
1481       // The argument in the result DAG pattern.
1482       auto patArgName = node.getArgName(argIndex);
1483       if (leaf.isConstantAttr() || leaf.isEnumAttrCase()) {
1484         // TODO: Refactor out into map to avoid recomputing these.
1485         if (!opArg.is<NamedAttribute *>())
1486           PrintFatalError(loc, Twine("expected attribute ") + Twine(argIndex));
1487         if (!patArgName.empty())
1488           os << "/*" << patArgName << "=*/";
1489       } else {
1490         os << "/*" << opArgName << "=*/";
1491       }
1492       os << handleOpArgument(leaf, patArgName);
1493     }
1494   }
1495 }
1496 
1497 void PatternEmitter::createAggregateLocalVarsForOpArgs(
1498     DagNode node, const ChildNodeIndexNameMap &childNodeNames, int depth) {
1499   Operator &resultOp = node.getDialectOp(opMap);
1500 
1501   auto scope = os.scope();
1502   os << formatv("::mlir::SmallVector<::mlir::Value, 4> "
1503                 "tblgen_values; (void)tblgen_values;\n");
1504   os << formatv("::mlir::SmallVector<::mlir::NamedAttribute, 4> "
1505                 "tblgen_attrs; (void)tblgen_attrs;\n");
1506 
1507   const char *addAttrCmd =
1508       "if (auto tmpAttr = {1}) {\n"
1509       "  tblgen_attrs.emplace_back(rewriter.getIdentifier(\"{0}\"), "
1510       "tmpAttr);\n}\n";
1511   for (int argIndex = 0, e = resultOp.getNumArgs(); argIndex < e; ++argIndex) {
1512     if (resultOp.getArg(argIndex).is<NamedAttribute *>()) {
1513       // The argument in the op definition.
1514       auto opArgName = resultOp.getArgName(argIndex);
1515       if (auto subTree = node.getArgAsNestedDag(argIndex)) {
1516         if (!subTree.isNativeCodeCall())
1517           PrintFatalError(loc, "only NativeCodeCall allowed in nested dag node "
1518                                "for creating attribute");
1519         os << formatv(addAttrCmd, opArgName, childNodeNames.lookup(argIndex));
1520       } else {
1521         auto leaf = node.getArgAsLeaf(argIndex);
1522         // The argument in the result DAG pattern.
1523         auto patArgName = node.getArgName(argIndex);
1524         os << formatv(addAttrCmd, opArgName,
1525                       handleOpArgument(leaf, patArgName));
1526       }
1527       continue;
1528     }
1529 
1530     const auto *operand =
1531         resultOp.getArg(argIndex).get<NamedTypeConstraint *>();
1532     std::string varName;
1533     if (operand->isVariadic()) {
1534       std::string range;
1535       if (node.isNestedDagArg(argIndex)) {
1536         range = childNodeNames.lookup(argIndex);
1537       } else {
1538         range = std::string(node.getArgName(argIndex));
1539       }
1540       // Resolve the symbol for all range use so that we have a uniform way of
1541       // capturing the values.
1542       range = symbolInfoMap.getValueAndRangeUse(range);
1543       os << formatv("for (auto v: {0}) {{\n  tblgen_values.push_back(v);\n}\n",
1544                     range);
1545     } else {
1546       os << formatv("tblgen_values.push_back(");
1547       if (node.isNestedDagArg(argIndex)) {
1548         os << symbolInfoMap.getValueAndRangeUse(
1549             childNodeNames.lookup(argIndex));
1550       } else {
1551         DagLeaf leaf = node.getArgAsLeaf(argIndex);
1552         if (leaf.isConstantAttr())
1553           // TODO: Use better location
1554           PrintFatalError(
1555               loc,
1556               "attribute found where value was expected, if attempting to use "
1557               "constant value, construct a constant op with given attribute "
1558               "instead");
1559 
1560         auto symbol =
1561             symbolInfoMap.getValueAndRangeUse(node.getArgName(argIndex));
1562         if (leaf.isNativeCodeCall()) {
1563           os << std::string(
1564               tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(symbol)));
1565         } else {
1566           os << symbol;
1567         }
1568       }
1569       os << ");\n";
1570     }
1571   }
1572 }
1573 
1574 StaticMatcherHelper::StaticMatcherHelper(RecordOperatorMap &mapper)
1575     : opMap(mapper) {}
1576 
1577 void StaticMatcherHelper::populateStaticMatchers(raw_ostream &os) {
1578   // PatternEmitter will use the static matcher if there's one generated. To
1579   // ensure that all the dependent static matchers are generated before emitting
1580   // the matching logic of the DagNode, we use topological order to achieve it.
1581   for (auto &dagInfo : topologicalOrder) {
1582     DagNode node = dagInfo.first;
1583     if (!useStaticMatcher(node))
1584       continue;
1585 
1586     std::string funcName =
1587         formatv("static_dag_matcher_{0}", staticMatcherCounter++);
1588     assert(matcherNames.find(node) == matcherNames.end());
1589     PatternEmitter(dagInfo.second, &opMap, os, *this)
1590         .emitStaticMatcher(node, funcName);
1591     matcherNames[node] = funcName;
1592   }
1593 }
1594 
1595 void StaticMatcherHelper::addPattern(Record *record) {
1596   Pattern pat(record, &opMap);
1597 
1598   // While generating the function body of the DAG matcher, it may depends on
1599   // other DAG matchers. To ensure the dependent matchers are ready, we compute
1600   // the topological order for all the DAGs and emit the DAG matchers in this
1601   // order.
1602   llvm::unique_function<void(DagNode)> dfs = [&](DagNode node) {
1603     ++refStats[node];
1604 
1605     if (refStats[node] != 1)
1606       return;
1607 
1608     for (unsigned i = 0, e = node.getNumArgs(); i < e; ++i)
1609       if (DagNode sibling = node.getArgAsNestedDag(i))
1610         dfs(sibling);
1611 
1612     topologicalOrder.push_back(std::make_pair(node, record));
1613   };
1614 
1615   dfs(pat.getSourcePattern());
1616 }
1617 
1618 static void emitRewriters(const RecordKeeper &recordKeeper, raw_ostream &os) {
1619   emitSourceFileHeader("Rewriters", os);
1620 
1621   const auto &patterns = recordKeeper.getAllDerivedDefinitions("Pattern");
1622 
1623   // We put the map here because it can be shared among multiple patterns.
1624   RecordOperatorMap recordOpMap;
1625 
1626   // Exam all the patterns and generate static matcher for the duplicated
1627   // DagNode.
1628   StaticMatcherHelper staticMatcher(recordOpMap);
1629   for (Record *p : patterns)
1630     staticMatcher.addPattern(p);
1631   staticMatcher.populateStaticMatchers(os);
1632 
1633   std::vector<std::string> rewriterNames;
1634   rewriterNames.reserve(patterns.size());
1635 
1636   std::string baseRewriterName = "GeneratedConvert";
1637   int rewriterIndex = 0;
1638 
1639   for (Record *p : patterns) {
1640     std::string name;
1641     if (p->isAnonymous()) {
1642       // If no name is provided, ensure unique rewriter names simply by
1643       // appending unique suffix.
1644       name = baseRewriterName + llvm::utostr(rewriterIndex++);
1645     } else {
1646       name = std::string(p->getName());
1647     }
1648     LLVM_DEBUG(llvm::dbgs()
1649                << "=== start generating pattern '" << name << "' ===\n");
1650     PatternEmitter(p, &recordOpMap, os, staticMatcher).emit(name);
1651     LLVM_DEBUG(llvm::dbgs()
1652                << "=== done generating pattern '" << name << "' ===\n");
1653     rewriterNames.push_back(std::move(name));
1654   }
1655 
1656   // Emit function to add the generated matchers to the pattern list.
1657   os << "void LLVM_ATTRIBUTE_UNUSED populateWithGenerated("
1658         "::mlir::RewritePatternSet &patterns) {\n";
1659   for (const auto &name : rewriterNames) {
1660     os << "  patterns.add<" << name << ">(patterns.getContext());\n";
1661   }
1662   os << "}\n";
1663 }
1664 
1665 static mlir::GenRegistration
1666     genRewriters("gen-rewriters", "Generate pattern rewriters",
1667                  [](const RecordKeeper &records, raw_ostream &os) {
1668                    emitRewriters(records, os);
1669                    return false;
1670                  });
1671