1 //===- Operator.cpp - Operator class --------------------------------------===//
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 // Operator wrapper to simplify using TableGen Record defining a MLIR Op.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/TableGen/Operator.h"
14 #include "mlir/TableGen/OpTrait.h"
15 #include "mlir/TableGen/Predicate.h"
16 #include "mlir/TableGen/Type.h"
17 #include "llvm/ADT/EquivalenceClasses.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Sequence.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/TypeSwitch.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/FormatVariadic.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 
27 #define DEBUG_TYPE "mlir-tblgen-operator"
28 
29 using namespace mlir;
30 
31 using llvm::DagInit;
32 using llvm::DefInit;
33 using llvm::Record;
34 
35 tblgen::Operator::Operator(const llvm::Record &def)
36     : dialect(def.getValueAsDef("opDialect")), def(def) {
37   // The first `_` in the op's TableGen def name is treated as separating the
38   // dialect prefix and the op class name. The dialect prefix will be ignored if
39   // not empty. Otherwise, if def name starts with a `_`, the `_` is considered
40   // as part of the class name.
41   StringRef prefix;
42   std::tie(prefix, cppClassName) = def.getName().split('_');
43   if (prefix.empty()) {
44     // Class name with a leading underscore and without dialect prefix
45     cppClassName = def.getName();
46   } else if (cppClassName.empty()) {
47     // Class name without dialect prefix
48     cppClassName = prefix;
49   }
50 
51   populateOpStructure();
52 }
53 
54 std::string tblgen::Operator::getOperationName() const {
55   auto prefix = dialect.getName();
56   auto opName = def.getValueAsString("opName");
57   if (prefix.empty())
58     return std::string(opName);
59   return std::string(llvm::formatv("{0}.{1}", prefix, opName));
60 }
61 
62 std::string tblgen::Operator::getAdaptorName() const {
63   return std::string(llvm::formatv("{0}Adaptor", getCppClassName()));
64 }
65 
66 StringRef tblgen::Operator::getDialectName() const { return dialect.getName(); }
67 
68 StringRef tblgen::Operator::getCppClassName() const { return cppClassName; }
69 
70 std::string tblgen::Operator::getQualCppClassName() const {
71   auto prefix = dialect.getCppNamespace();
72   if (prefix.empty())
73     return std::string(cppClassName);
74   return std::string(llvm::formatv("{0}::{1}", prefix, cppClassName));
75 }
76 
77 int tblgen::Operator::getNumResults() const {
78   DagInit *results = def.getValueAsDag("results");
79   return results->getNumArgs();
80 }
81 
82 StringRef tblgen::Operator::getExtraClassDeclaration() const {
83   constexpr auto attr = "extraClassDeclaration";
84   if (def.isValueUnset(attr))
85     return {};
86   return def.getValueAsString(attr);
87 }
88 
89 const llvm::Record &tblgen::Operator::getDef() const { return def; }
90 
91 bool tblgen::Operator::skipDefaultBuilders() const {
92   return def.getValueAsBit("skipDefaultBuilders");
93 }
94 
95 auto tblgen::Operator::result_begin() -> value_iterator {
96   return results.begin();
97 }
98 
99 auto tblgen::Operator::result_end() -> value_iterator { return results.end(); }
100 
101 auto tblgen::Operator::getResults() -> value_range {
102   return {result_begin(), result_end()};
103 }
104 
105 tblgen::TypeConstraint
106 tblgen::Operator::getResultTypeConstraint(int index) const {
107   DagInit *results = def.getValueAsDag("results");
108   return TypeConstraint(cast<DefInit>(results->getArg(index)));
109 }
110 
111 StringRef tblgen::Operator::getResultName(int index) const {
112   DagInit *results = def.getValueAsDag("results");
113   return results->getArgNameStr(index);
114 }
115 
116 auto tblgen::Operator::getResultDecorators(int index) const
117     -> var_decorator_range {
118   Record *result =
119       cast<DefInit>(def.getValueAsDag("results")->getArg(index))->getDef();
120   if (!result->isSubClassOf("OpVariable"))
121     return var_decorator_range(nullptr, nullptr);
122   return *result->getValueAsListInit("decorators");
123 }
124 
125 unsigned tblgen::Operator::getNumVariableLengthResults() const {
126   return llvm::count_if(results, [](const NamedTypeConstraint &c) {
127     return c.constraint.isVariableLength();
128   });
129 }
130 
131 unsigned tblgen::Operator::getNumVariableLengthOperands() const {
132   return llvm::count_if(operands, [](const NamedTypeConstraint &c) {
133     return c.constraint.isVariableLength();
134   });
135 }
136 
137 bool tblgen::Operator::hasSingleVariadicArg() const {
138   return getNumArgs() == 1 && getArg(0).is<tblgen::NamedTypeConstraint *>() &&
139          getOperand(0).isVariadic();
140 }
141 
142 tblgen::Operator::arg_iterator tblgen::Operator::arg_begin() const {
143   return arguments.begin();
144 }
145 
146 tblgen::Operator::arg_iterator tblgen::Operator::arg_end() const {
147   return arguments.end();
148 }
149 
150 tblgen::Operator::arg_range tblgen::Operator::getArgs() const {
151   return {arg_begin(), arg_end()};
152 }
153 
154 StringRef tblgen::Operator::getArgName(int index) const {
155   DagInit *argumentValues = def.getValueAsDag("arguments");
156   return argumentValues->getArgName(index)->getValue();
157 }
158 
159 auto tblgen::Operator::getArgDecorators(int index) const
160     -> var_decorator_range {
161   Record *arg =
162       cast<DefInit>(def.getValueAsDag("arguments")->getArg(index))->getDef();
163   if (!arg->isSubClassOf("OpVariable"))
164     return var_decorator_range(nullptr, nullptr);
165   return *arg->getValueAsListInit("decorators");
166 }
167 
168 const tblgen::OpTrait *tblgen::Operator::getTrait(StringRef trait) const {
169   for (const auto &t : traits) {
170     if (const auto *opTrait = dyn_cast<tblgen::NativeOpTrait>(&t)) {
171       if (opTrait->getTrait() == trait)
172         return opTrait;
173     } else if (const auto *opTrait = dyn_cast<tblgen::InternalOpTrait>(&t)) {
174       if (opTrait->getTrait() == trait)
175         return opTrait;
176     } else if (const auto *opTrait = dyn_cast<tblgen::InterfaceOpTrait>(&t)) {
177       if (opTrait->getTrait() == trait)
178         return opTrait;
179     }
180   }
181   return nullptr;
182 }
183 
184 auto tblgen::Operator::region_begin() const -> const_region_iterator {
185   return regions.begin();
186 }
187 auto tblgen::Operator::region_end() const -> const_region_iterator {
188   return regions.end();
189 }
190 auto tblgen::Operator::getRegions() const
191     -> llvm::iterator_range<const_region_iterator> {
192   return {region_begin(), region_end()};
193 }
194 
195 unsigned tblgen::Operator::getNumRegions() const { return regions.size(); }
196 
197 const tblgen::NamedRegion &tblgen::Operator::getRegion(unsigned index) const {
198   return regions[index];
199 }
200 
201 unsigned tblgen::Operator::getNumVariadicRegions() const {
202   return llvm::count_if(regions,
203                         [](const NamedRegion &c) { return c.isVariadic(); });
204 }
205 
206 auto tblgen::Operator::successor_begin() const -> const_successor_iterator {
207   return successors.begin();
208 }
209 auto tblgen::Operator::successor_end() const -> const_successor_iterator {
210   return successors.end();
211 }
212 auto tblgen::Operator::getSuccessors() const
213     -> llvm::iterator_range<const_successor_iterator> {
214   return {successor_begin(), successor_end()};
215 }
216 
217 unsigned tblgen::Operator::getNumSuccessors() const {
218   return successors.size();
219 }
220 
221 const tblgen::NamedSuccessor &
222 tblgen::Operator::getSuccessor(unsigned index) const {
223   return successors[index];
224 }
225 
226 unsigned tblgen::Operator::getNumVariadicSuccessors() const {
227   return llvm::count_if(successors,
228                         [](const NamedSuccessor &c) { return c.isVariadic(); });
229 }
230 
231 auto tblgen::Operator::trait_begin() const -> const_trait_iterator {
232   return traits.begin();
233 }
234 auto tblgen::Operator::trait_end() const -> const_trait_iterator {
235   return traits.end();
236 }
237 auto tblgen::Operator::getTraits() const
238     -> llvm::iterator_range<const_trait_iterator> {
239   return {trait_begin(), trait_end()};
240 }
241 
242 auto tblgen::Operator::attribute_begin() const -> attribute_iterator {
243   return attributes.begin();
244 }
245 auto tblgen::Operator::attribute_end() const -> attribute_iterator {
246   return attributes.end();
247 }
248 auto tblgen::Operator::getAttributes() const
249     -> llvm::iterator_range<attribute_iterator> {
250   return {attribute_begin(), attribute_end()};
251 }
252 
253 auto tblgen::Operator::operand_begin() -> value_iterator {
254   return operands.begin();
255 }
256 auto tblgen::Operator::operand_end() -> value_iterator {
257   return operands.end();
258 }
259 auto tblgen::Operator::getOperands() -> value_range {
260   return {operand_begin(), operand_end()};
261 }
262 
263 auto tblgen::Operator::getArg(int index) const -> Argument {
264   return arguments[index];
265 }
266 
267 // Mapping from result index to combined argument and result index. Arguments
268 // are indexed to match getArg index, while the result indexes are mapped to
269 // avoid overlap.
270 static int resultIndex(int i) { return -1 - i; }
271 
272 bool tblgen::Operator::isVariadic() const {
273   return any_of(llvm::concat<const NamedTypeConstraint>(operands, results),
274                 [](const NamedTypeConstraint &op) { return op.isVariadic(); });
275 }
276 
277 void tblgen::Operator::populateTypeInferenceInfo(
278     const llvm::StringMap<int> &argumentsAndResultsIndex) {
279   // If the type inference op interface is not registered, then do not attempt
280   // to determine if the result types an be inferred.
281   auto &recordKeeper = def.getRecords();
282   auto *inferTrait = recordKeeper.getDef(inferTypeOpInterface);
283   allResultsHaveKnownTypes = false;
284   if (!inferTrait)
285     return;
286 
287   // If there are no results, the skip this else the build method generated
288   // overlaps with another autogenerated builder.
289   if (getNumResults() == 0)
290     return;
291 
292   // Skip for ops with variadic operands/results.
293   // TODO: This can be relaxed.
294   if (isVariadic())
295     return;
296 
297   // Skip cases currently being custom generated.
298   // TODO: Remove special cases.
299   if (getTrait("OpTrait::SameOperandsAndResultType"))
300     return;
301 
302   // We create equivalence classes of argument/result types where arguments
303   // and results are mapped into the same index space and indices corresponding
304   // to the same type are in the same equivalence class.
305   llvm::EquivalenceClasses<int> ecs;
306   resultTypeMapping.resize(getNumResults());
307   // Captures the argument whose type matches a given result type. Preference
308   // towards capturing operands first before attributes.
309   auto captureMapping = [&](int i) {
310     bool found = false;
311     ecs.insert(resultIndex(i));
312     auto mi = ecs.findLeader(resultIndex(i));
313     for (auto me = ecs.member_end(); mi != me; ++mi) {
314       if (*mi < 0) {
315         auto tc = getResultTypeConstraint(i);
316         if (tc.getBuilderCall().hasValue()) {
317           resultTypeMapping[i].emplace_back(tc);
318           found = true;
319         }
320         continue;
321       }
322 
323       if (getArg(*mi).is<NamedAttribute *>()) {
324         // TODO: Handle attributes.
325         continue;
326       } else {
327         resultTypeMapping[i].emplace_back(*mi);
328         found = true;
329       }
330     }
331     return found;
332   };
333 
334   for (const OpTrait &trait : traits) {
335     const llvm::Record &def = trait.getDef();
336     // If the infer type op interface was manually added, then treat it as
337     // intention that the op needs special handling.
338     // TODO: Reconsider whether to always generate, this is more conservative
339     // and keeps existing behavior so starting that way for now.
340     if (def.isSubClassOf(
341             llvm::formatv("{0}::Trait", inferTypeOpInterface).str()))
342       return;
343     if (const auto *opTrait = dyn_cast<tblgen::InterfaceOpTrait>(&trait))
344       if (&opTrait->getDef() == inferTrait)
345         return;
346 
347     if (!def.isSubClassOf("AllTypesMatch"))
348       continue;
349 
350     auto values = def.getValueAsListOfStrings("values");
351     auto root = argumentsAndResultsIndex.lookup(values.front());
352     for (StringRef str : values)
353       ecs.unionSets(argumentsAndResultsIndex.lookup(str), root);
354   }
355 
356   // Verifies that all output types have a corresponding known input type
357   // and chooses matching operand or attribute (in that order) that
358   // matches it.
359   allResultsHaveKnownTypes =
360       all_of(llvm::seq<int>(0, getNumResults()), captureMapping);
361 
362   // If the types could be computed, then add type inference trait.
363   if (allResultsHaveKnownTypes)
364     traits.push_back(OpTrait::create(inferTrait->getDefInit()));
365 }
366 
367 void tblgen::Operator::populateOpStructure() {
368   auto &recordKeeper = def.getRecords();
369   auto *typeConstraintClass = recordKeeper.getClass("TypeConstraint");
370   auto *attrClass = recordKeeper.getClass("Attr");
371   auto *derivedAttrClass = recordKeeper.getClass("DerivedAttr");
372   auto *opVarClass = recordKeeper.getClass("OpVariable");
373   numNativeAttributes = 0;
374 
375   DagInit *argumentValues = def.getValueAsDag("arguments");
376   unsigned numArgs = argumentValues->getNumArgs();
377 
378   // Mapping from name of to argument or result index. Arguments are indexed
379   // to match getArg index, while the results are negatively indexed.
380   llvm::StringMap<int> argumentsAndResultsIndex;
381 
382   // Handle operands and native attributes.
383   for (unsigned i = 0; i != numArgs; ++i) {
384     auto *arg = argumentValues->getArg(i);
385     auto givenName = argumentValues->getArgNameStr(i);
386     auto *argDefInit = dyn_cast<DefInit>(arg);
387     if (!argDefInit)
388       PrintFatalError(def.getLoc(),
389                       Twine("undefined type for argument #") + Twine(i));
390     Record *argDef = argDefInit->getDef();
391     if (argDef->isSubClassOf(opVarClass))
392       argDef = argDef->getValueAsDef("constraint");
393 
394     if (argDef->isSubClassOf(typeConstraintClass)) {
395       operands.push_back(
396           NamedTypeConstraint{givenName, TypeConstraint(argDef)});
397     } else if (argDef->isSubClassOf(attrClass)) {
398       if (givenName.empty())
399         PrintFatalError(argDef->getLoc(), "attributes must be named");
400       if (argDef->isSubClassOf(derivedAttrClass))
401         PrintFatalError(argDef->getLoc(),
402                         "derived attributes not allowed in argument list");
403       attributes.push_back({givenName, Attribute(argDef)});
404       ++numNativeAttributes;
405     } else {
406       PrintFatalError(def.getLoc(), "unexpected def type; only defs deriving "
407                                     "from TypeConstraint or Attr are allowed");
408     }
409     if (!givenName.empty())
410       argumentsAndResultsIndex[givenName] = i;
411   }
412 
413   // Handle derived attributes.
414   for (const auto &val : def.getValues()) {
415     if (auto *record = dyn_cast<llvm::RecordRecTy>(val.getType())) {
416       if (!record->isSubClassOf(attrClass))
417         continue;
418       if (!record->isSubClassOf(derivedAttrClass))
419         PrintFatalError(def.getLoc(),
420                         "unexpected Attr where only DerivedAttr is allowed");
421 
422       if (record->getClasses().size() != 1) {
423         PrintFatalError(
424             def.getLoc(),
425             "unsupported attribute modelling, only single class expected");
426       }
427       attributes.push_back(
428           {cast<llvm::StringInit>(val.getNameInit())->getValue(),
429            Attribute(cast<DefInit>(val.getValue()))});
430     }
431   }
432 
433   // Populate `arguments`. This must happen after we've finalized `operands` and
434   // `attributes` because we will put their elements' pointers in `arguments`.
435   // SmallVector may perform re-allocation under the hood when adding new
436   // elements.
437   int operandIndex = 0, attrIndex = 0;
438   for (unsigned i = 0; i != numArgs; ++i) {
439     Record *argDef = dyn_cast<DefInit>(argumentValues->getArg(i))->getDef();
440     if (argDef->isSubClassOf(opVarClass))
441       argDef = argDef->getValueAsDef("constraint");
442 
443     if (argDef->isSubClassOf(typeConstraintClass)) {
444       attrOrOperandMapping.push_back(
445           {OperandOrAttribute::Kind::Operand, operandIndex});
446       arguments.emplace_back(&operands[operandIndex++]);
447     } else {
448       assert(argDef->isSubClassOf(attrClass));
449       attrOrOperandMapping.push_back(
450           {OperandOrAttribute::Kind::Attribute, attrIndex});
451       arguments.emplace_back(&attributes[attrIndex++]);
452     }
453   }
454 
455   auto *resultsDag = def.getValueAsDag("results");
456   auto *outsOp = dyn_cast<DefInit>(resultsDag->getOperator());
457   if (!outsOp || outsOp->getDef()->getName() != "outs") {
458     PrintFatalError(def.getLoc(), "'results' must have 'outs' directive");
459   }
460 
461   // Handle results.
462   for (unsigned i = 0, e = resultsDag->getNumArgs(); i < e; ++i) {
463     auto name = resultsDag->getArgNameStr(i);
464     auto *resultInit = dyn_cast<DefInit>(resultsDag->getArg(i));
465     if (!resultInit) {
466       PrintFatalError(def.getLoc(),
467                       Twine("undefined type for result #") + Twine(i));
468     }
469     auto *resultDef = resultInit->getDef();
470     if (resultDef->isSubClassOf(opVarClass))
471       resultDef = resultDef->getValueAsDef("constraint");
472     results.push_back({name, TypeConstraint(resultDef)});
473     if (!name.empty())
474       argumentsAndResultsIndex[name] = resultIndex(i);
475   }
476 
477   // Handle successors
478   auto *successorsDag = def.getValueAsDag("successors");
479   auto *successorsOp = dyn_cast<DefInit>(successorsDag->getOperator());
480   if (!successorsOp || successorsOp->getDef()->getName() != "successor") {
481     PrintFatalError(def.getLoc(),
482                     "'successors' must have 'successor' directive");
483   }
484 
485   for (unsigned i = 0, e = successorsDag->getNumArgs(); i < e; ++i) {
486     auto name = successorsDag->getArgNameStr(i);
487     auto *successorInit = dyn_cast<DefInit>(successorsDag->getArg(i));
488     if (!successorInit) {
489       PrintFatalError(def.getLoc(),
490                       Twine("undefined kind for successor #") + Twine(i));
491     }
492     Successor successor(successorInit->getDef());
493 
494     // Only support variadic successors if it is the last one for now.
495     if (i != e - 1 && successor.isVariadic())
496       PrintFatalError(def.getLoc(), "only the last successor can be variadic");
497     successors.push_back({name, successor});
498   }
499 
500   // Create list of traits, skipping over duplicates: appending to lists in
501   // tablegen is easy, making them unique less so, so dedupe here.
502   if (auto *traitList = def.getValueAsListInit("traits")) {
503     // This is uniquing based on pointers of the trait.
504     SmallPtrSet<const llvm::Init *, 32> traitSet;
505     traits.reserve(traitSet.size());
506     for (auto *traitInit : *traitList) {
507       // Keep traits in the same order while skipping over duplicates.
508       if (traitSet.insert(traitInit).second)
509         traits.push_back(OpTrait::create(traitInit));
510     }
511   }
512 
513   populateTypeInferenceInfo(argumentsAndResultsIndex);
514 
515   // Handle regions
516   auto *regionsDag = def.getValueAsDag("regions");
517   auto *regionsOp = dyn_cast<DefInit>(regionsDag->getOperator());
518   if (!regionsOp || regionsOp->getDef()->getName() != "region") {
519     PrintFatalError(def.getLoc(), "'regions' must have 'region' directive");
520   }
521 
522   for (unsigned i = 0, e = regionsDag->getNumArgs(); i < e; ++i) {
523     auto name = regionsDag->getArgNameStr(i);
524     auto *regionInit = dyn_cast<DefInit>(regionsDag->getArg(i));
525     if (!regionInit) {
526       PrintFatalError(def.getLoc(),
527                       Twine("undefined kind for region #") + Twine(i));
528     }
529     Region region(regionInit->getDef());
530     if (region.isVariadic()) {
531       // Only support variadic regions if it is the last one for now.
532       if (i != e - 1)
533         PrintFatalError(def.getLoc(), "only the last region can be variadic");
534       if (name.empty())
535         PrintFatalError(def.getLoc(), "variadic regions must be named");
536     }
537 
538     regions.push_back({name, region});
539   }
540 
541   LLVM_DEBUG(print(llvm::dbgs()));
542 }
543 
544 auto tblgen::Operator::getSameTypeAsResult(int index) const
545     -> ArrayRef<ArgOrType> {
546   assert(allResultTypesKnown());
547   return resultTypeMapping[index];
548 }
549 
550 ArrayRef<llvm::SMLoc> tblgen::Operator::getLoc() const { return def.getLoc(); }
551 
552 bool tblgen::Operator::hasDescription() const {
553   return def.getValue("description") != nullptr;
554 }
555 
556 StringRef tblgen::Operator::getDescription() const {
557   return def.getValueAsString("description");
558 }
559 
560 bool tblgen::Operator::hasSummary() const {
561   return def.getValue("summary") != nullptr;
562 }
563 
564 StringRef tblgen::Operator::getSummary() const {
565   return def.getValueAsString("summary");
566 }
567 
568 bool tblgen::Operator::hasAssemblyFormat() const {
569   auto *valueInit = def.getValueInit("assemblyFormat");
570   return isa<llvm::CodeInit, llvm::StringInit>(valueInit);
571 }
572 
573 StringRef tblgen::Operator::getAssemblyFormat() const {
574   return TypeSwitch<llvm::Init *, StringRef>(def.getValueInit("assemblyFormat"))
575       .Case<llvm::StringInit, llvm::CodeInit>(
576           [&](auto *init) { return init->getValue(); });
577 }
578 
579 void tblgen::Operator::print(llvm::raw_ostream &os) const {
580   os << "op '" << getOperationName() << "'\n";
581   for (Argument arg : arguments) {
582     if (auto *attr = arg.dyn_cast<NamedAttribute *>())
583       os << "[attribute] " << attr->name << '\n';
584     else
585       os << "[operand] " << arg.get<NamedTypeConstraint *>()->name << '\n';
586   }
587 }
588 
589 auto tblgen::Operator::VariableDecoratorIterator::unwrap(llvm::Init *init)
590     -> VariableDecorator {
591   return VariableDecorator(cast<llvm::DefInit>(init)->getDef());
592 }
593 
594 auto tblgen::Operator::getArgToOperandOrAttribute(int index) const
595     -> OperandOrAttribute {
596   return attrOrOperandMapping[index];
597 }
598