1 //===- LLVMIRConversionGen.cpp - MLIR LLVM IR builder 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 // This file uses tablegen definitions of the LLVM IR Dialect operations to
10 // generate the code building the LLVM IR from it.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Support/LogicalResult.h"
15 #include "mlir/TableGen/Attribute.h"
16 #include "mlir/TableGen/GenInfo.h"
17 #include "mlir/TableGen/Operator.h"
18 
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/FormatVariadic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/TableGen/Record.h"
24 #include "llvm/TableGen/TableGenBackend.h"
25 
26 using namespace llvm;
27 using namespace mlir;
28 
29 static bool emitError(const Twine &message) {
30   llvm::errs() << message << "\n";
31   return false;
32 }
33 
34 namespace {
35 // Helper structure to return a position of the substring in a string.
36 struct StringLoc {
37   size_t pos;
38   size_t length;
39 
40   // Take a substring identified by this location in the given string.
41   StringRef in(StringRef str) const { return str.substr(pos, length); }
42 
43   // A location is invalid if its position is outside the string.
44   explicit operator bool() { return pos != std::string::npos; }
45 };
46 } // namespace
47 
48 // Find the next TableGen variable in the given pattern.  These variables start
49 // with a `$` character and can contain alphanumeric characters or underscores.
50 // Return the position of the variable in the pattern and its length, including
51 // the `$` character.  The escape syntax `$$` is also detected and returned.
52 static StringLoc findNextVariable(StringRef str) {
53   size_t startPos = str.find('$');
54   if (startPos == std::string::npos)
55     return {startPos, 0};
56 
57   // If we see "$$", return immediately.
58   if (startPos != str.size() - 1 && str[startPos + 1] == '$')
59     return {startPos, 2};
60 
61   // Otherwise, the symbol spans until the first character that is not
62   // alphanumeric or '_'.
63   size_t endPos = str.find_if_not([](char c) { return isAlnum(c) || c == '_'; },
64                                   startPos + 1);
65   if (endPos == std::string::npos)
66     endPos = str.size();
67 
68   return {startPos, endPos - startPos};
69 }
70 
71 // Check if `name` is the name of the variadic operand of `op`.  The variadic
72 // operand can only appear at the last position in the list of operands.
73 static bool isVariadicOperandName(const tblgen::Operator &op, StringRef name) {
74   unsigned numOperands = op.getNumOperands();
75   if (numOperands == 0)
76     return false;
77   const auto &operand = op.getOperand(numOperands - 1);
78   return operand.isVariableLength() && operand.name == name;
79 }
80 
81 // Check if `result` is a known name of a result of `op`.
82 static bool isResultName(const tblgen::Operator &op, StringRef name) {
83   for (int i = 0, e = op.getNumResults(); i < e; ++i)
84     if (op.getResultName(i) == name)
85       return true;
86   return false;
87 }
88 
89 // Check if `name` is a known name of an attribute of `op`.
90 static bool isAttributeName(const tblgen::Operator &op, StringRef name) {
91   return llvm::any_of(
92       op.getAttributes(),
93       [name](const tblgen::NamedAttribute &attr) { return attr.name == name; });
94 }
95 
96 // Check if `name` is a known name of an operand of `op`.
97 static bool isOperandName(const tblgen::Operator &op, StringRef name) {
98   for (int i = 0, e = op.getNumOperands(); i < e; ++i)
99     if (op.getOperand(i).name == name)
100       return true;
101   return false;
102 }
103 
104 // Emit to `os` the operator-name driven check and the call to LLVM IRBuilder
105 // for one definition of an LLVM IR Dialect operation.  Return true on success.
106 static bool emitOneBuilder(const Record &record, raw_ostream &os) {
107   auto op = tblgen::Operator(record);
108 
109   if (!record.getValue("llvmBuilder"))
110     return emitError("no 'llvmBuilder' field for op " + op.getOperationName());
111 
112   // Return early if there is no builder specified.
113   auto builderStrRef = record.getValueAsString("llvmBuilder");
114   if (builderStrRef.empty())
115     return true;
116 
117   // Progressively create the builder string by replacing $-variables with
118   // value lookups.  Keep only the not-yet-traversed part of the builder pattern
119   // to avoid re-traversing the string multiple times.
120   std::string builder;
121   llvm::raw_string_ostream bs(builder);
122   while (auto loc = findNextVariable(builderStrRef)) {
123     auto name = loc.in(builderStrRef).drop_front();
124     // First, insert the non-matched part as is.
125     bs << builderStrRef.substr(0, loc.pos);
126     // Then, rewrite the name based on its kind.
127     bool isVariadicOperand = isVariadicOperandName(op, name);
128     if (isOperandName(op, name)) {
129       auto result =
130           isVariadicOperand
131               ? formatv("moduleTranslation.lookupValues(op.{0}())", name)
132               : formatv("moduleTranslation.lookupValue(op.{0}())", name);
133       bs << result;
134     } else if (isAttributeName(op, name)) {
135       bs << formatv("op.{0}()", name);
136     } else if (isResultName(op, name)) {
137       bs << formatv("moduleTranslation.mapValue(op.{0}())", name);
138     } else if (name == "_resultType") {
139       bs << "moduleTranslation.convertType(op.getResult().getType())";
140     } else if (name == "_hasResult") {
141       bs << "opInst.getNumResults() == 1";
142     } else if (name == "_location") {
143       bs << "opInst.getLoc()";
144     } else if (name == "_numOperands") {
145       bs << "opInst.getNumOperands()";
146     } else if (name == "$") {
147       bs << '$';
148     } else {
149       return emitError(name + " is neither an argument nor a result of " +
150                        op.getOperationName());
151     }
152     // Finally, only keep the untraversed part of the string.
153     builderStrRef = builderStrRef.substr(loc.pos + loc.length);
154   }
155 
156   // Output the check and the rewritten builder string.
157   os << "if (auto op = dyn_cast<" << op.getQualCppClassName()
158      << ">(opInst)) {\n";
159   os << bs.str() << builderStrRef << "\n";
160   os << "  return success();\n";
161   os << "}\n";
162 
163   return true;
164 }
165 
166 // Emit all builders.  Returns false on success because of the generator
167 // registration requirements.
168 static bool emitBuilders(const RecordKeeper &recordKeeper, raw_ostream &os) {
169   for (const auto *def : recordKeeper.getAllDerivedDefinitions("LLVM_OpBase")) {
170     if (!emitOneBuilder(*def, os))
171       return true;
172   }
173   return false;
174 }
175 
176 namespace {
177 // Wrapper class around a Tablegen definition of an LLVM enum attribute case.
178 class LLVMEnumAttrCase : public tblgen::EnumAttrCase {
179 public:
180   using tblgen::EnumAttrCase::EnumAttrCase;
181 
182   // Constructs a case from a non LLVM-specific enum attribute case.
183   explicit LLVMEnumAttrCase(const tblgen::EnumAttrCase &other)
184       : tblgen::EnumAttrCase(&other.getDef()) {}
185 
186   // Returns the C++ enumerant for the LLVM API.
187   StringRef getLLVMEnumerant() const {
188     return def->getValueAsString("llvmEnumerant");
189   }
190 };
191 
192 // Wraper class around a Tablegen definition of an LLVM enum attribute.
193 class LLVMEnumAttr : public tblgen::EnumAttr {
194 public:
195   using tblgen::EnumAttr::EnumAttr;
196 
197   // Returns the C++ enum name for the LLVM API.
198   StringRef getLLVMClassName() const {
199     return def->getValueAsString("llvmClassName");
200   }
201 
202   // Returns all associated cases viewed as LLVM-specific enum cases.
203   std::vector<LLVMEnumAttrCase> getAllCases() const {
204     std::vector<LLVMEnumAttrCase> cases;
205 
206     for (auto &c : tblgen::EnumAttr::getAllCases())
207       cases.push_back(LLVMEnumAttrCase(c));
208 
209     return cases;
210   }
211 };
212 } // namespace
213 
214 // Emits conversion function "LLVMClass convertEnumToLLVM(Enum)" and containing
215 // switch-based logic to convert from the MLIR LLVM dialect enum attribute case
216 // (Enum) to the corresponding LLVM API enumerant
217 static void emitOneEnumToConversion(const llvm::Record *record,
218                                     raw_ostream &os) {
219   LLVMEnumAttr enumAttr(record);
220   StringRef llvmClass = enumAttr.getLLVMClassName();
221   StringRef cppClassName = enumAttr.getEnumClassName();
222   StringRef cppNamespace = enumAttr.getCppNamespace();
223 
224   // Emit the function converting the enum attribute to its LLVM counterpart.
225   os << formatv("static {0} convert{1}ToLLVM({2}::{1} value) {{\n", llvmClass,
226                 cppClassName, cppNamespace);
227   os << "  switch (value) {\n";
228 
229   for (const auto &enumerant : enumAttr.getAllCases()) {
230     StringRef llvmEnumerant = enumerant.getLLVMEnumerant();
231     StringRef cppEnumerant = enumerant.getSymbol();
232     os << formatv("  case {0}::{1}::{2}:\n", cppNamespace, cppClassName,
233                   cppEnumerant);
234     os << formatv("    return {0}::{1};\n", llvmClass, llvmEnumerant);
235   }
236 
237   os << "  }\n";
238   os << formatv("  llvm_unreachable(\"unknown {0} type\");\n",
239                 enumAttr.getEnumClassName());
240   os << "}\n\n";
241 }
242 
243 // Emits conversion function "Enum convertEnumFromLLVM(LLVMClass)" and
244 // containing switch-based logic to convert from the LLVM API enumerant to MLIR
245 // LLVM dialect enum attribute (Enum).
246 static void emitOneEnumFromConversion(const llvm::Record *record,
247                                       raw_ostream &os) {
248   LLVMEnumAttr enumAttr(record);
249   StringRef llvmClass = enumAttr.getLLVMClassName();
250   StringRef cppClassName = enumAttr.getEnumClassName();
251   StringRef cppNamespace = enumAttr.getCppNamespace();
252 
253   // Emit the function converting the enum attribute from its LLVM counterpart.
254   os << formatv("inline {0}::{1} convert{1}FromLLVM({2} value) {{\n",
255                 cppNamespace, cppClassName, llvmClass);
256   os << "  switch (value) {\n";
257 
258   for (const auto &enumerant : enumAttr.getAllCases()) {
259     StringRef llvmEnumerant = enumerant.getLLVMEnumerant();
260     StringRef cppEnumerant = enumerant.getSymbol();
261     os << formatv("  case {0}::{1}:\n", llvmClass, llvmEnumerant);
262     os << formatv("    return {0}::{1}::{2};\n", cppNamespace, cppClassName,
263                   cppEnumerant);
264   }
265 
266   os << "  }\n";
267   os << formatv("  llvm_unreachable(\"unknown {0} type\");",
268                 enumAttr.getLLVMClassName());
269   os << "}\n\n";
270 }
271 
272 // Emits conversion functions between MLIR enum attribute case and corresponding
273 // LLVM API enumerants for all registered LLVM dialect enum attributes.
274 template <bool ConvertTo>
275 static bool emitEnumConversionDefs(const RecordKeeper &recordKeeper,
276                                    raw_ostream &os) {
277   for (const auto *def : recordKeeper.getAllDerivedDefinitions("LLVM_EnumAttr"))
278     if (ConvertTo)
279       emitOneEnumToConversion(def, os);
280     else
281       emitOneEnumFromConversion(def, os);
282 
283   return false;
284 }
285 
286 static mlir::GenRegistration
287     genLLVMIRConversions("gen-llvmir-conversions",
288                          "Generate LLVM IR conversions", emitBuilders);
289 
290 static mlir::GenRegistration
291     genEnumToLLVMConversion("gen-enum-to-llvmir-conversions",
292                             "Generate conversions of EnumAttrs to LLVM IR",
293                             emitEnumConversionDefs</*ConvertTo=*/true>);
294 
295 static mlir::GenRegistration
296     genEnumFromLLVMConversion("gen-enum-from-llvmir-conversions",
297                               "Generate conversions of EnumAttrs from LLVM IR",
298                               emitEnumConversionDefs</*ConvertTo=*/false>);
299