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/SmallPtrSet.h"
18 #include "llvm/Support/FormatVariadic.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 
22 #define DEBUG_TYPE "mlir-tblgen-operator"
23 
24 using namespace mlir;
25 
26 using llvm::DagInit;
27 using llvm::DefInit;
28 using llvm::Record;
29 
30 tblgen::Operator::Operator(const llvm::Record &def)
31     : dialect(def.getValueAsDef("opDialect")), def(def) {
32   // The first `_` in the op's TableGen def name is treated as separating the
33   // dialect prefix and the op class name. The dialect prefix will be ignored if
34   // not empty. Otherwise, if def name starts with a `_`, the `_` is considered
35   // as part of the class name.
36   StringRef prefix;
37   std::tie(prefix, cppClassName) = def.getName().split('_');
38   if (prefix.empty()) {
39     // Class name with a leading underscore and without dialect prefix
40     cppClassName = def.getName();
41   } else if (cppClassName.empty()) {
42     // Class name without dialect prefix
43     cppClassName = prefix;
44   }
45 
46   populateOpStructure();
47 }
48 
49 std::string tblgen::Operator::getOperationName() const {
50   auto prefix = dialect.getName();
51   auto opName = def.getValueAsString("opName");
52   if (prefix.empty())
53     return std::string(opName);
54   return std::string(llvm::formatv("{0}.{1}", prefix, opName));
55 }
56 
57 StringRef tblgen::Operator::getDialectName() const { return dialect.getName(); }
58 
59 StringRef tblgen::Operator::getCppClassName() const { return cppClassName; }
60 
61 std::string tblgen::Operator::getQualCppClassName() const {
62   auto prefix = dialect.getCppNamespace();
63   if (prefix.empty())
64     return std::string(cppClassName);
65   return std::string(llvm::formatv("{0}::{1}", prefix, cppClassName));
66 }
67 
68 int tblgen::Operator::getNumResults() const {
69   DagInit *results = def.getValueAsDag("results");
70   return results->getNumArgs();
71 }
72 
73 StringRef tblgen::Operator::getExtraClassDeclaration() const {
74   constexpr auto attr = "extraClassDeclaration";
75   if (def.isValueUnset(attr))
76     return {};
77   return def.getValueAsString(attr);
78 }
79 
80 const llvm::Record &tblgen::Operator::getDef() const { return def; }
81 
82 bool tblgen::Operator::isVariadic() const {
83   return getNumVariadicOperands() != 0 || getNumVariadicResults() != 0;
84 }
85 
86 bool tblgen::Operator::skipDefaultBuilders() const {
87   return def.getValueAsBit("skipDefaultBuilders");
88 }
89 
90 auto tblgen::Operator::result_begin() -> value_iterator {
91   return results.begin();
92 }
93 
94 auto tblgen::Operator::result_end() -> value_iterator { return results.end(); }
95 
96 auto tblgen::Operator::getResults() -> value_range {
97   return {result_begin(), result_end()};
98 }
99 
100 tblgen::TypeConstraint
101 tblgen::Operator::getResultTypeConstraint(int index) const {
102   DagInit *results = def.getValueAsDag("results");
103   return TypeConstraint(cast<DefInit>(results->getArg(index)));
104 }
105 
106 StringRef tblgen::Operator::getResultName(int index) const {
107   DagInit *results = def.getValueAsDag("results");
108   return results->getArgNameStr(index);
109 }
110 
111 unsigned tblgen::Operator::getNumVariadicResults() const {
112   return std::count_if(
113       results.begin(), results.end(),
114       [](const NamedTypeConstraint &c) { return c.constraint.isVariadic(); });
115 }
116 
117 unsigned tblgen::Operator::getNumVariadicOperands() const {
118   return std::count_if(
119       operands.begin(), operands.end(),
120       [](const NamedTypeConstraint &c) { return c.constraint.isVariadic(); });
121 }
122 
123 tblgen::Operator::arg_iterator tblgen::Operator::arg_begin() const {
124   return arguments.begin();
125 }
126 
127 tblgen::Operator::arg_iterator tblgen::Operator::arg_end() const {
128   return arguments.end();
129 }
130 
131 tblgen::Operator::arg_range tblgen::Operator::getArgs() const {
132   return {arg_begin(), arg_end()};
133 }
134 
135 StringRef tblgen::Operator::getArgName(int index) const {
136   DagInit *argumentValues = def.getValueAsDag("arguments");
137   return argumentValues->getArgName(index)->getValue();
138 }
139 
140 const tblgen::OpTrait *tblgen::Operator::getTrait(StringRef trait) const {
141   for (const auto &t : traits) {
142     if (auto opTrait = dyn_cast<tblgen::NativeOpTrait>(&t)) {
143       if (opTrait->getTrait() == trait)
144         return opTrait;
145     } else if (auto opTrait = dyn_cast<tblgen::InternalOpTrait>(&t)) {
146       if (opTrait->getTrait() == trait)
147         return opTrait;
148     } else if (auto opTrait = dyn_cast<tblgen::InterfaceOpTrait>(&t)) {
149       if (opTrait->getTrait() == trait)
150         return opTrait;
151     }
152   }
153   return nullptr;
154 }
155 
156 unsigned tblgen::Operator::getNumRegions() const { return regions.size(); }
157 
158 const tblgen::NamedRegion &tblgen::Operator::getRegion(unsigned index) const {
159   return regions[index];
160 }
161 
162 auto tblgen::Operator::trait_begin() const -> const_trait_iterator {
163   return traits.begin();
164 }
165 auto tblgen::Operator::trait_end() const -> const_trait_iterator {
166   return traits.end();
167 }
168 auto tblgen::Operator::getTraits() const
169     -> llvm::iterator_range<const_trait_iterator> {
170   return {trait_begin(), trait_end()};
171 }
172 
173 auto tblgen::Operator::attribute_begin() const -> attribute_iterator {
174   return attributes.begin();
175 }
176 auto tblgen::Operator::attribute_end() const -> attribute_iterator {
177   return attributes.end();
178 }
179 auto tblgen::Operator::getAttributes() const
180     -> llvm::iterator_range<attribute_iterator> {
181   return {attribute_begin(), attribute_end()};
182 }
183 
184 auto tblgen::Operator::operand_begin() -> value_iterator {
185   return operands.begin();
186 }
187 auto tblgen::Operator::operand_end() -> value_iterator {
188   return operands.end();
189 }
190 auto tblgen::Operator::getOperands() -> value_range {
191   return {operand_begin(), operand_end()};
192 }
193 
194 auto tblgen::Operator::getArg(int index) const -> Argument {
195   return arguments[index];
196 }
197 
198 void tblgen::Operator::populateOpStructure() {
199   auto &recordKeeper = def.getRecords();
200   auto typeConstraintClass = recordKeeper.getClass("TypeConstraint");
201   auto attrClass = recordKeeper.getClass("Attr");
202   auto derivedAttrClass = recordKeeper.getClass("DerivedAttr");
203   numNativeAttributes = 0;
204 
205   DagInit *argumentValues = def.getValueAsDag("arguments");
206   unsigned numArgs = argumentValues->getNumArgs();
207 
208   // Handle operands and native attributes.
209   for (unsigned i = 0; i != numArgs; ++i) {
210     auto arg = argumentValues->getArg(i);
211     auto givenName = argumentValues->getArgNameStr(i);
212     auto argDefInit = dyn_cast<DefInit>(arg);
213     if (!argDefInit)
214       PrintFatalError(def.getLoc(),
215                       Twine("undefined type for argument #") + Twine(i));
216     Record *argDef = argDefInit->getDef();
217 
218     if (argDef->isSubClassOf(typeConstraintClass)) {
219       operands.push_back(
220           NamedTypeConstraint{givenName, TypeConstraint(argDefInit)});
221     } else if (argDef->isSubClassOf(attrClass)) {
222       if (givenName.empty())
223         PrintFatalError(argDef->getLoc(), "attributes must be named");
224       if (argDef->isSubClassOf(derivedAttrClass))
225         PrintFatalError(argDef->getLoc(),
226                         "derived attributes not allowed in argument list");
227       attributes.push_back({givenName, Attribute(argDef)});
228       ++numNativeAttributes;
229     } else {
230       PrintFatalError(def.getLoc(), "unexpected def type; only defs deriving "
231                                     "from TypeConstraint or Attr are allowed");
232     }
233   }
234 
235   // Handle derived attributes.
236   for (const auto &val : def.getValues()) {
237     if (auto *record = dyn_cast<llvm::RecordRecTy>(val.getType())) {
238       if (!record->isSubClassOf(attrClass))
239         continue;
240       if (!record->isSubClassOf(derivedAttrClass))
241         PrintFatalError(def.getLoc(),
242                         "unexpected Attr where only DerivedAttr is allowed");
243 
244       if (record->getClasses().size() != 1) {
245         PrintFatalError(
246             def.getLoc(),
247             "unsupported attribute modelling, only single class expected");
248       }
249       attributes.push_back(
250           {cast<llvm::StringInit>(val.getNameInit())->getValue(),
251            Attribute(cast<DefInit>(val.getValue()))});
252     }
253   }
254 
255   // Populate `arguments`. This must happen after we've finalized `operands` and
256   // `attributes` because we will put their elements' pointers in `arguments`.
257   // SmallVector may perform re-allocation under the hood when adding new
258   // elements.
259   int operandIndex = 0, attrIndex = 0;
260   for (unsigned i = 0; i != numArgs; ++i) {
261     Record *argDef = dyn_cast<DefInit>(argumentValues->getArg(i))->getDef();
262 
263     if (argDef->isSubClassOf(typeConstraintClass)) {
264       arguments.emplace_back(&operands[operandIndex++]);
265     } else {
266       assert(argDef->isSubClassOf(attrClass));
267       arguments.emplace_back(&attributes[attrIndex++]);
268     }
269   }
270 
271   auto *resultsDag = def.getValueAsDag("results");
272   auto *outsOp = dyn_cast<DefInit>(resultsDag->getOperator());
273   if (!outsOp || outsOp->getDef()->getName() != "outs") {
274     PrintFatalError(def.getLoc(), "'results' must have 'outs' directive");
275   }
276 
277   // Handle results.
278   for (unsigned i = 0, e = resultsDag->getNumArgs(); i < e; ++i) {
279     auto name = resultsDag->getArgNameStr(i);
280     auto *resultDef = dyn_cast<DefInit>(resultsDag->getArg(i));
281     if (!resultDef) {
282       PrintFatalError(def.getLoc(),
283                       Twine("undefined type for result #") + Twine(i));
284     }
285     results.push_back({name, TypeConstraint(resultDef)});
286   }
287 
288   // Create list of traits, skipping over duplicates: appending to lists in
289   // tablegen is easy, making them unique less so, so dedupe here.
290   if (auto traitList = def.getValueAsListInit("traits")) {
291     // This is uniquing based on pointers of the trait.
292     SmallPtrSet<const llvm::Init *, 32> traitSet;
293     traits.reserve(traitSet.size());
294     for (auto traitInit : *traitList) {
295       // Keep traits in the same order while skipping over duplicates.
296       if (traitSet.insert(traitInit).second)
297         traits.push_back(OpTrait::create(traitInit));
298     }
299   }
300 
301   // Handle regions
302   auto *regionsDag = def.getValueAsDag("regions");
303   auto *regionsOp = dyn_cast<DefInit>(regionsDag->getOperator());
304   if (!regionsOp || regionsOp->getDef()->getName() != "region") {
305     PrintFatalError(def.getLoc(), "'regions' must have 'region' directive");
306   }
307 
308   for (unsigned i = 0, e = regionsDag->getNumArgs(); i < e; ++i) {
309     auto name = regionsDag->getArgNameStr(i);
310     auto *regionInit = dyn_cast<DefInit>(regionsDag->getArg(i));
311     if (!regionInit) {
312       PrintFatalError(def.getLoc(),
313                       Twine("undefined kind for region #") + Twine(i));
314     }
315     regions.push_back({name, Region(regionInit->getDef())});
316   }
317 
318   LLVM_DEBUG(print(llvm::dbgs()));
319 }
320 
321 ArrayRef<llvm::SMLoc> tblgen::Operator::getLoc() const { return def.getLoc(); }
322 
323 bool tblgen::Operator::hasDescription() const {
324   return def.getValue("description") != nullptr;
325 }
326 
327 StringRef tblgen::Operator::getDescription() const {
328   return def.getValueAsString("description");
329 }
330 
331 bool tblgen::Operator::hasSummary() const {
332   return def.getValue("summary") != nullptr;
333 }
334 
335 StringRef tblgen::Operator::getSummary() const {
336   return def.getValueAsString("summary");
337 }
338 
339 void tblgen::Operator::print(llvm::raw_ostream &os) const {
340   os << "op '" << getOperationName() << "'\n";
341   for (Argument arg : arguments) {
342     if (auto *attr = arg.dyn_cast<NamedAttribute *>())
343       os << "[attribute] " << attr->name << '\n';
344     else
345       os << "[operand] " << arg.get<NamedTypeConstraint *>()->name << '\n';
346   }
347 }
348