forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOmpOpGen.cpp
368 lines (315 loc) · 14.3 KB
/
OmpOpGen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
//===- OmpOpGen.cpp - OpenMP dialect op specific generators ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// OmpOpGen defines OpenMP dialect operation specific generators.
//
//===----------------------------------------------------------------------===//
#include "mlir/TableGen/GenInfo.h"
#include "mlir/TableGen/CodeGenHelpers.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
using namespace llvm;
/// The code block defining the base mixin class for combining clause operand
/// structures.
static const char *const baseMixinClass = R"(
namespace detail {
template <typename... Mixins>
struct Clauses : public Mixins... {};
} // namespace detail
)";
/// The code block defining operation argument structures.
static const char *const operationArgStruct = R"(
using {0}Operands = detail::Clauses<{1}>;
)";
/// Remove multiple optional prefixes and suffixes from \c str.
///
/// Prefixes and suffixes are attempted to be removed once in the order they
/// appear in the \c prefixes and \c suffixes arguments. All prefixes are
/// processed before suffixes are. This means it will behave as shown in the
/// following example:
/// - str: "PrePreNameSuf1Suf2"
/// - prefixes: ["Pre"]
/// - suffixes: ["Suf1", "Suf2"]
/// - return: "PreNameSuf1"
static StringRef stripPrefixAndSuffix(StringRef str,
llvm::ArrayRef<StringRef> prefixes,
llvm::ArrayRef<StringRef> suffixes) {
for (StringRef prefix : prefixes)
if (str.starts_with(prefix))
str = str.drop_front(prefix.size());
for (StringRef suffix : suffixes)
if (str.ends_with(suffix))
str = str.drop_back(suffix.size());
return str;
}
/// Obtain the name of the OpenMP clause a given record inheriting
/// `OpenMP_Clause` refers to.
///
/// It supports direct and indirect `OpenMP_Clause` superclasses. Once the
/// `OpenMP_Clause` class the record is based on is found, the optional
/// "OpenMP_" prefix and "Skip" and "Clause" suffixes are removed to return only
/// the clause name, i.e. "OpenMP_CollapseClauseSkip" is returned as "Collapse".
static StringRef extractOmpClauseName(const Record *clause) {
const Record *ompClause = clause->getRecords().getClass("OpenMP_Clause");
assert(ompClause && "base OpenMP records expected to be defined");
StringRef clauseClassName;
SmallVector<const Record *, 1> clauseSuperClasses;
clause->getDirectSuperClasses(clauseSuperClasses);
// Check if OpenMP_Clause is a direct superclass.
for (const Record *superClass : clauseSuperClasses) {
if (superClass == ompClause) {
clauseClassName = clause->getName();
break;
}
}
// Support indirectly-inherited OpenMP_Clauses.
if (clauseClassName.empty()) {
for (auto [superClass, _] : clause->getSuperClasses()) {
if (superClass->isSubClassOf(ompClause)) {
clauseClassName = superClass->getName();
break;
}
}
}
assert(!clauseClassName.empty() && "clause name must be found");
// Keep only the OpenMP clause name itself for reporting purposes.
return stripPrefixAndSuffix(clauseClassName, /*prefixes=*/{"OpenMP_"},
/*suffixes=*/{"Skip", "Clause"});
}
/// Check that the given argument, identified by its name and initialization
/// value, is present in the \c arguments `dag`.
static bool verifyArgument(const DagInit *arguments, StringRef argName,
const Init *argInit) {
auto range = zip_equal(arguments->getArgNames(), arguments->getArgs());
return llvm::any_of(
range, [&](std::tuple<const llvm::StringInit *, const llvm::Init *> v) {
return std::get<0>(v)->getAsUnquotedString() == argName &&
std::get<1>(v) == argInit;
});
}
/// Check that the given string record value, identified by its \c opValueName,
/// is either undefined or empty in both the given operation and clause record
/// or its contents for the clause record are contained in the operation record.
/// Passing a non-empty \c clauseValueName enables checking values named
/// differently in the operation and clause records.
static bool verifyStringValue(const Record *op, const Record *clause,
StringRef opValueName,
StringRef clauseValueName = {}) {
auto opValue = op->getValueAsOptionalString(opValueName);
auto clauseValue = clause->getValueAsOptionalString(
clauseValueName.empty() ? opValueName : clauseValueName);
bool opHasValue = opValue && !opValue->trim().empty();
bool clauseHasValue = clauseValue && !clauseValue->trim().empty();
if (!opHasValue)
return !clauseHasValue;
return !clauseHasValue || opValue->contains(clauseValue->trim());
}
/// Verify that all fields of the given clause not explicitly ignored are
/// present in the corresponding operation field.
///
/// Print warnings or errors where this is not the case.
static void verifyClause(const Record *op, const Record *clause) {
StringRef clauseClassName = extractOmpClauseName(clause);
if (!clause->getValueAsBit("ignoreArgs")) {
const DagInit *opArguments = op->getValueAsDag("arguments");
const DagInit *arguments = clause->getValueAsDag("arguments");
for (auto [name, arg] :
zip(arguments->getArgNames(), arguments->getArgs())) {
if (!verifyArgument(opArguments, name->getAsUnquotedString(), arg))
PrintWarning(
op->getLoc(),
"'" + clauseClassName + "' clause-defined argument '" +
arg->getAsUnquotedString() + ":$" +
name->getAsUnquotedString() +
"' not present in operation. Consider `dag arguments = "
"!con(clausesArgs, ...)` or explicitly skipping this field.");
}
}
if (!clause->getValueAsBit("ignoreAsmFormat") &&
!verifyStringValue(op, clause, "assemblyFormat", "reqAssemblyFormat"))
PrintWarning(
op->getLoc(),
"'" + clauseClassName +
"' clause-defined `reqAssemblyFormat` not present in operation. "
"Consider concatenating `clauses[{Req,Opt}]AssemblyFormat` or "
"explicitly skipping this field.");
if (!clause->getValueAsBit("ignoreAsmFormat") &&
!verifyStringValue(op, clause, "assemblyFormat", "optAssemblyFormat"))
PrintWarning(
op->getLoc(),
"'" + clauseClassName +
"' clause-defined `optAssemblyFormat` not present in operation. "
"Consider concatenating `clauses[{Req,Opt}]AssemblyFormat` or "
"explicitly skipping this field.");
if (!clause->getValueAsBit("ignoreDesc") &&
!verifyStringValue(op, clause, "description"))
PrintError(op->getLoc(),
"'" + clauseClassName +
"' clause-defined `description` not present in operation. "
"Consider concatenating `clausesDescription` or explicitly "
"skipping this field.");
if (!clause->getValueAsBit("ignoreExtraDecl") &&
!verifyStringValue(op, clause, "extraClassDeclaration"))
PrintWarning(
op->getLoc(),
"'" + clauseClassName +
"' clause-defined `extraClassDeclaration` not present in "
"operation. Consider concatenating `clausesExtraClassDeclaration` "
"or explicitly skipping this field.");
}
/// Translate the type of an OpenMP clause's argument to its corresponding
/// representation for clause operand structures.
///
/// All kinds of values are represented as `mlir::Value` fields, whereas
/// attributes are represented based on their `storageType`.
///
/// \param[in] name The name of the argument.
/// \param[in] init The `DefInit` object representing the argument.
/// \param[out] nest Number of levels of array nesting associated with the
/// type. Must be initially set to 0.
/// \param[out] rank Rank (number of dimensions, if an array type) of the base
/// type. Must be initially set to 1.
///
/// \return the name of the base type to represent elements of the argument
/// type.
static StringRef translateArgumentType(ArrayRef<SMLoc> loc,
const StringInit *name, const Init *init,
int &nest, int &rank) {
const Record *def = cast<DefInit>(init)->getDef();
llvm::StringSet<> superClasses;
for (auto [sc, _] : def->getSuperClasses())
superClasses.insert(sc->getNameInitAsString());
// Handle wrapper-style superclasses.
if (superClasses.contains("OptionalAttr"))
return translateArgumentType(
loc, name, def->getValue("baseAttr")->getValue(), nest, rank);
if (superClasses.contains("TypedArrayAttrBase"))
return translateArgumentType(
loc, name, def->getValue("elementAttr")->getValue(), ++nest, rank);
// Handle ElementsAttrBase superclasses.
if (superClasses.contains("ElementsAttrBase")) {
// TODO: Obtain the rank from ranked types.
++nest;
if (superClasses.contains("IntElementsAttrBase"))
return "::llvm::APInt";
if (superClasses.contains("FloatElementsAttr") ||
superClasses.contains("RankedFloatElementsAttr"))
return "::llvm::APFloat";
if (superClasses.contains("DenseArrayAttrBase"))
return stripPrefixAndSuffix(def->getValueAsString("returnType"),
{"::llvm::ArrayRef<"}, {">"});
// Decrease the nesting depth in the case where the base type cannot be
// inferred, so that the bare storageType is used instead of a vector.
--nest;
PrintWarning(
loc,
"could not infer array-like attribute element type for argument '" +
name->getAsUnquotedString() + "', will use bare `storageType`");
}
// Handle simple attribute and value types.
[[maybe_unused]] bool isAttr = superClasses.contains("Attr");
bool isValue = superClasses.contains("TypeConstraint");
if (superClasses.contains("Variadic"))
++nest;
if (isValue) {
assert(!isAttr &&
"argument can't be simultaneously a value and an attribute");
return "::mlir::Value";
}
assert(isAttr && "argument must be an attribute if it's not a value");
return nest > 0 ? "::mlir::Attribute"
: def->getValueAsString("storageType").trim();
}
/// Generate the structure that represents the arguments of the given \c clause
/// record of type \c OpenMP_Clause.
///
/// It will contain a field for each argument, using the same name translated to
/// camel case and the corresponding base type as returned by
/// translateArgumentType() optionally wrapped in one or more llvm::SmallVector.
///
/// An additional field containing a tuple of integers to hold the size of each
/// dimension will also be created for multi-rank types. This is not yet
/// supported.
static void genClauseOpsStruct(const Record *clause, raw_ostream &os) {
if (clause->isAnonymous())
return;
StringRef clauseName = extractOmpClauseName(clause);
os << "struct " << clauseName << "ClauseOps {\n";
const DagInit *arguments = clause->getValueAsDag("arguments");
for (auto [name, arg] :
zip_equal(arguments->getArgNames(), arguments->getArgs())) {
int nest = 0, rank = 1;
StringRef baseType =
translateArgumentType(clause->getLoc(), name, arg, nest, rank);
std::string fieldName =
convertToCamelFromSnakeCase(name->getAsUnquotedString(),
/*capitalizeFirst=*/false);
os << formatv(" {0}{1}{2} {3};\n",
fmt_repeat("::llvm::SmallVector<", nest), baseType,
fmt_repeat(">", nest), fieldName);
if (rank > 1) {
assert(nest >= 1 && "must be nested if it's a ranked type");
os << formatv(" {0}::std::tuple<{1}int>{2} {3}Dims;\n",
fmt_repeat("::llvm::SmallVector<", nest - 1),
fmt_repeat("int, ", rank - 1), fmt_repeat(">", nest - 1),
fieldName);
}
}
os << "};\n";
}
/// Generate the structure that represents the clause-related arguments of the
/// given \c op record of type \c OpenMP_Op.
///
/// This structure will be defined in terms of the clause operand structures
/// associated to the clauses of the operation.
static void genOperandsDef(const Record *op, raw_ostream &os) {
if (op->isAnonymous())
return;
SmallVector<std::string> clauseNames;
for (const Record *clause : op->getValueAsListOfDefs("clauseList"))
clauseNames.push_back((extractOmpClauseName(clause) + "ClauseOps").str());
StringRef opName = stripPrefixAndSuffix(
op->getName(), /*prefixes=*/{"OpenMP_"}, /*suffixes=*/{"Op"});
os << formatv(operationArgStruct, opName, join(clauseNames, ", "));
}
/// Verify that all properties of `OpenMP_Clause`s of records deriving from
/// `OpenMP_Op`s have been inherited by the latter.
static bool verifyDecls(const RecordKeeper &records, raw_ostream &) {
for (const Record *op : records.getAllDerivedDefinitions("OpenMP_Op")) {
for (const Record *clause : op->getValueAsListOfDefs("clauseList"))
verifyClause(op, clause);
}
return false;
}
/// Generate structures to represent clause-related operands, based on existing
/// `OpenMP_Clause` definitions and aggregate them into operation-specific
/// structures according to the `clauses` argument of each definition deriving
/// from `OpenMP_Op`.
static bool genClauseOps(const RecordKeeper &records, raw_ostream &os) {
mlir::tblgen::NamespaceEmitter ns(os, "mlir::omp");
for (const Record *clause : records.getAllDerivedDefinitions("OpenMP_Clause"))
genClauseOpsStruct(clause, os);
// Produce base mixin class.
os << baseMixinClass;
for (const Record *op : records.getAllDerivedDefinitions("OpenMP_Op"))
genOperandsDef(op, os);
return false;
}
// Registers the generator to mlir-tblgen.
static mlir::GenRegistration
verifyOpenmpOps("verify-openmp-ops",
"Verify OpenMP operations (produce no output file)",
verifyDecls);
static mlir::GenRegistration
genOpenmpClauseOps("gen-openmp-clause-ops",
"Generate OpenMP clause operand structures",
genClauseOps);