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