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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
|
//===- IRDLToCpp.cpp - Converts IRDL definitions to C++ -------------------===//
//
// Part of the LLVM Project, under the A0ache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/IRDLToCpp/IRDLToCpp.h"
#include "mlir/Dialect/IRDL/IR/IRDL.h"
#include "mlir/Support/LLVM.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include "TemplatingUtils.h"
using namespace mlir;
constexpr char headerTemplateText[] =
#include "Templates/Header.txt"
;
constexpr char declarationMacroFlag[] = "GEN_DIALECT_DECL_HEADER";
constexpr char definitionMacroFlag[] = "GEN_DIALECT_DEF";
namespace {
/// The set of strings that can be generated from a Dialect declaraiton
struct DialectStrings {
std::string dialectName;
std::string dialectCppName;
std::string dialectCppShortName;
std::string dialectBaseTypeName;
std::string namespaceOpen;
std::string namespaceClose;
std::string namespacePath;
};
/// The set of strings that can be generated from a Type declaraiton
struct TypeStrings {
StringRef typeName;
std::string typeCppName;
};
/// The set of strings that can be generated from an Operation declaraiton
struct OpStrings {
StringRef opName;
std::string opCppName;
SmallVector<std::string> opResultNames;
SmallVector<std::string> opOperandNames;
SmallVector<std::string> opRegionNames;
};
static std::string joinNameList(llvm::ArrayRef<std::string> names) {
std::string nameArray;
llvm::raw_string_ostream nameArrayStream(nameArray);
nameArrayStream << "{\"" << llvm::join(names, "\", \"") << "\"}";
return nameArray;
}
/// Generates the C++ type name for a TypeOp
static std::string typeToCppName(irdl::TypeOp type) {
return llvm::formatv("{0}Type",
convertToCamelFromSnakeCase(type.getSymName(), true));
}
/// Generates the C++ class name for an OperationOp
static std::string opToCppName(irdl::OperationOp op) {
return llvm::formatv("{0}Op",
convertToCamelFromSnakeCase(op.getSymName(), true));
}
/// Generates TypeStrings from a TypeOp
static TypeStrings getStrings(irdl::TypeOp type) {
TypeStrings strings;
strings.typeName = type.getSymName();
strings.typeCppName = typeToCppName(type);
return strings;
}
/// Generates OpStrings from an OperatioOp
static OpStrings getStrings(irdl::OperationOp op) {
auto operandOp = op.getOp<irdl::OperandsOp>();
auto resultOp = op.getOp<irdl::ResultsOp>();
auto regionsOp = op.getOp<irdl::RegionsOp>();
OpStrings strings;
strings.opName = op.getSymName();
strings.opCppName = opToCppName(op);
if (operandOp) {
strings.opOperandNames = SmallVector<std::string>(
llvm::map_range(operandOp->getNames(), [](Attribute attr) {
return llvm::formatv("{0}", cast<StringAttr>(attr));
}));
}
if (resultOp) {
strings.opResultNames = SmallVector<std::string>(
llvm::map_range(resultOp->getNames(), [](Attribute attr) {
return llvm::formatv("{0}", cast<StringAttr>(attr));
}));
}
if (regionsOp) {
strings.opRegionNames = SmallVector<std::string>(
llvm::map_range(regionsOp->getNames(), [](Attribute attr) {
return llvm::formatv("{0}", cast<StringAttr>(attr));
}));
}
return strings;
}
/// Fills a dictionary with values from TypeStrings
static void fillDict(irdl::detail::dictionary &dict,
const TypeStrings &strings) {
dict["TYPE_NAME"] = strings.typeName;
dict["TYPE_CPP_NAME"] = strings.typeCppName;
}
/// Fills a dictionary with values from OpStrings
static void fillDict(irdl::detail::dictionary &dict, const OpStrings &strings) {
const auto operandCount = strings.opOperandNames.size();
const auto resultCount = strings.opResultNames.size();
const auto regionCount = strings.opRegionNames.size();
dict["OP_NAME"] = strings.opName;
dict["OP_CPP_NAME"] = strings.opCppName;
dict["OP_OPERAND_COUNT"] = std::to_string(strings.opOperandNames.size());
dict["OP_RESULT_COUNT"] = std::to_string(strings.opResultNames.size());
dict["OP_OPERAND_INITIALIZER_LIST"] =
operandCount ? joinNameList(strings.opOperandNames) : "{\"\"}";
dict["OP_RESULT_INITIALIZER_LIST"] =
resultCount ? joinNameList(strings.opResultNames) : "{\"\"}";
dict["OP_REGION_COUNT"] = std::to_string(regionCount);
}
/// Fills a dictionary with values from DialectStrings
static void fillDict(irdl::detail::dictionary &dict,
const DialectStrings &strings) {
dict["DIALECT_NAME"] = strings.dialectName;
dict["DIALECT_BASE_TYPE_NAME"] = strings.dialectBaseTypeName;
dict["DIALECT_CPP_NAME"] = strings.dialectCppName;
dict["DIALECT_CPP_SHORT_NAME"] = strings.dialectCppShortName;
dict["NAMESPACE_OPEN"] = strings.namespaceOpen;
dict["NAMESPACE_CLOSE"] = strings.namespaceClose;
dict["NAMESPACE_PATH"] = strings.namespacePath;
}
static LogicalResult generateTypedefList(irdl::DialectOp &dialect,
SmallVector<std::string> &typeNames) {
auto typeOps = dialect.getOps<irdl::TypeOp>();
auto range = llvm::map_range(typeOps, typeToCppName);
typeNames = SmallVector<std::string>(range);
return success();
}
static LogicalResult generateOpList(irdl::DialectOp &dialect,
SmallVector<std::string> &opNames) {
auto operationOps = dialect.getOps<irdl::OperationOp>();
auto range = llvm::map_range(operationOps, opToCppName);
opNames = SmallVector<std::string>(range);
return success();
}
} // namespace
static LogicalResult generateTypeInclude(irdl::TypeOp type, raw_ostream &output,
irdl::detail::dictionary &dict) {
static const auto typeDeclTemplate = irdl::detail::Template(
#include "Templates/TypeDecl.txt"
);
fillDict(dict, getStrings(type));
typeDeclTemplate.render(output, dict);
return success();
}
static void generateOpGetterDeclarations(irdl::detail::dictionary &dict,
const OpStrings &opStrings) {
auto opGetters = std::string{};
auto resGetters = std::string{};
auto regionGetters = std::string{};
auto regionAdaptorGetters = std::string{};
for (size_t i = 0, end = opStrings.opOperandNames.size(); i < end; ++i) {
const auto op =
llvm::convertToCamelFromSnakeCase(opStrings.opOperandNames[i], true);
opGetters += llvm::formatv("::mlir::Value get{0}() { return "
"getStructuredOperands({1}).front(); }\n ",
op, i);
}
for (size_t i = 0, end = opStrings.opResultNames.size(); i < end; ++i) {
const auto op =
llvm::convertToCamelFromSnakeCase(opStrings.opResultNames[i], true);
resGetters += llvm::formatv(
R"(::mlir::Value get{0}() { return ::llvm::cast<::mlir::Value>(getStructuredResults({1}).front()); }
)",
op, i);
}
for (size_t i = 0, end = opStrings.opRegionNames.size(); i < end; ++i) {
const auto op =
llvm::convertToCamelFromSnakeCase(opStrings.opRegionNames[i], true);
regionAdaptorGetters += llvm::formatv(
R"(::mlir::Region &get{0}() { return *getRegions()[{1}]; }
)",
op, i);
regionGetters += llvm::formatv(
R"(::mlir::Region &get{0}() { return (*this)->getRegion({1}); }
)",
op, i);
}
dict["OP_OPERAND_GETTER_DECLS"] = opGetters;
dict["OP_RESULT_GETTER_DECLS"] = resGetters;
dict["OP_REGION_ADAPTER_GETTER_DECLS"] = regionAdaptorGetters;
dict["OP_REGION_GETTER_DECLS"] = regionGetters;
}
static void generateOpBuilderDeclarations(irdl::detail::dictionary &dict,
const OpStrings &opStrings) {
std::string buildDecls;
llvm::raw_string_ostream stream{buildDecls};
auto resultParams =
llvm::join(llvm::map_range(opStrings.opResultNames,
[](StringRef name) -> std::string {
return llvm::formatv(
"::mlir::Type {0}, ",
llvm::convertToCamelFromSnakeCase(name));
}),
"");
auto operandParams =
llvm::join(llvm::map_range(opStrings.opOperandNames,
[](StringRef name) -> std::string {
return llvm::formatv(
"::mlir::Value {0}, ",
llvm::convertToCamelFromSnakeCase(name));
}),
"");
stream << llvm::formatv(
R"(static void build(::mlir::OpBuilder &opBuilder, ::mlir::OperationState &opState, {0} {1} ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {{});)",
resultParams, operandParams);
stream << "\n";
stream << llvm::formatv(
R"(static {0} create(::mlir::OpBuilder &opBuilder, ::mlir::Location location, {1} {2} ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {{});)",
opStrings.opCppName, resultParams, operandParams);
stream << "\n";
stream << llvm::formatv(
R"(static {0} create(::mlir::ImplicitLocOpBuilder &opBuilder, {1} {2} ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {{});)",
opStrings.opCppName, resultParams, operandParams);
stream << "\n";
dict["OP_BUILD_DECLS"] = buildDecls;
}
// add traits to the dictionary, return true if any were added
static SmallVector<std::string> generateTraits(irdl::OperationOp op,
const OpStrings &strings) {
SmallVector<std::string> cppTraitNames;
if (!strings.opRegionNames.empty()) {
cppTraitNames.push_back(
llvm::formatv("::mlir::OpTrait::NRegions<{0}>::Impl",
strings.opRegionNames.size())
.str());
// Requires verifyInvariantsImpl is implemented on the op
cppTraitNames.emplace_back("::mlir::OpTrait::OpInvariants");
}
return cppTraitNames;
}
static LogicalResult generateOperationInclude(irdl::OperationOp op,
raw_ostream &output,
irdl::detail::dictionary &dict) {
static const auto perOpDeclTemplate = irdl::detail::Template(
#include "Templates/PerOperationDecl.txt"
);
const auto opStrings = getStrings(op);
fillDict(dict, opStrings);
SmallVector<std::string> traitNames = generateTraits(op, opStrings);
if (traitNames.empty())
dict["OP_TEMPLATE_ARGS"] = opStrings.opCppName;
else
dict["OP_TEMPLATE_ARGS"] = llvm::formatv("{0}, {1}", opStrings.opCppName,
llvm::join(traitNames, ", "));
generateOpGetterDeclarations(dict, opStrings);
generateOpBuilderDeclarations(dict, opStrings);
perOpDeclTemplate.render(output, dict);
return success();
}
static LogicalResult generateInclude(irdl::DialectOp dialect,
raw_ostream &output,
DialectStrings &dialectStrings) {
static const auto dialectDeclTemplate = irdl::detail::Template(
#include "Templates/DialectDecl.txt"
);
static const auto typeHeaderDeclTemplate = irdl::detail::Template(
#include "Templates/TypeHeaderDecl.txt"
);
irdl::detail::dictionary dict;
fillDict(dict, dialectStrings);
dialectDeclTemplate.render(output, dict);
typeHeaderDeclTemplate.render(output, dict);
auto typeOps = dialect.getOps<irdl::TypeOp>();
auto operationOps = dialect.getOps<irdl::OperationOp>();
for (auto &&typeOp : typeOps) {
if (failed(generateTypeInclude(typeOp, output, dict)))
return failure();
}
SmallVector<std::string> opNames;
if (failed(generateOpList(dialect, opNames)))
return failure();
auto classDeclarations =
llvm::join(llvm::map_range(opNames,
[](llvm::StringRef name) -> std::string {
return llvm::formatv("class {0};", name);
}),
"\n");
const auto forwardDeclarations = llvm::formatv(
"{1}\n{0}\n{2}", std::move(classDeclarations),
dialectStrings.namespaceOpen, dialectStrings.namespaceClose);
output << forwardDeclarations;
for (auto &&operationOp : operationOps) {
if (failed(generateOperationInclude(operationOp, output, dict)))
return failure();
}
return success();
}
static void generateRegionConstraintVerifiers(
irdl::detail::dictionary &dict, irdl::OperationOp op,
const OpStrings &strings, SmallVectorImpl<std::string> &verifierHelpers,
SmallVectorImpl<std::string> &verifierCalls) {
auto regionsOp = op.getOp<irdl::RegionsOp>();
if (strings.opRegionNames.empty() || !regionsOp)
return;
for (size_t i = 0; i < strings.opRegionNames.size(); ++i) {
std::string regionName = strings.opRegionNames[i];
std::string helperFnName =
llvm::formatv("__mlir_irdl_local_region_constraint_{0}_{1}",
strings.opCppName, regionName)
.str();
// Extract the actual region constraint from the IRDL RegionOp
std::string condition = "true";
std::string textualConditionName = "any region";
if (auto regionDefOp =
dyn_cast<irdl::RegionOp>(regionsOp->getArgs()[i].getDefiningOp())) {
// Generate constraint condition based on RegionOp attributes
SmallVector<std::string> conditionParts;
SmallVector<std::string> descriptionParts;
// Check number of blocks constraint
if (auto blockCount = regionDefOp.getNumberOfBlocks()) {
conditionParts.push_back(
llvm::formatv("region.getBlocks().size() == {0}",
blockCount.value())
.str());
descriptionParts.push_back(
llvm::formatv("exactly {0} block(s)", blockCount.value()).str());
}
// Check entry block arguments constraint
if (regionDefOp.getConstrainedArguments()) {
size_t expectedArgCount = regionDefOp.getEntryBlockArgs().size();
conditionParts.push_back(
llvm::formatv("region.getNumArguments() == {0}", expectedArgCount)
.str());
descriptionParts.push_back(
llvm::formatv("{0} entry block argument(s)", expectedArgCount)
.str());
}
// Combine conditions
if (!conditionParts.empty()) {
condition = llvm::join(conditionParts, " && ");
}
// Generate descriptive error message
if (!descriptionParts.empty()) {
textualConditionName =
llvm::formatv("region with {0}",
llvm::join(descriptionParts, " and "))
.str();
}
}
verifierHelpers.push_back(llvm::formatv(
R"(static ::llvm::LogicalResult {0}(::mlir::Operation *op, ::mlir::Region ®ion, ::llvm::StringRef regionName, unsigned regionIndex) {{
if (!({1})) {{
return op->emitOpError("region #") << regionIndex
<< (regionName.empty() ? " " : " ('" + regionName + "') ")
<< "failed to verify constraint: {2}";
}
return ::mlir::success();
})",
helperFnName, condition, textualConditionName));
verifierCalls.push_back(llvm::formatv(R"(
if (::mlir::failed({0}(*this, (*this)->getRegion({1}), "{2}", {1})))
return ::mlir::failure();)",
helperFnName, i, regionName)
.str());
}
}
static void generateVerifiers(irdl::detail::dictionary &dict,
irdl::OperationOp op, const OpStrings &strings) {
SmallVector<std::string> verifierHelpers;
SmallVector<std::string> verifierCalls;
generateRegionConstraintVerifiers(dict, op, strings, verifierHelpers,
verifierCalls);
// Add an overall verifier that sequences the helper calls
std::string verifierDef =
llvm::formatv(R"(
::llvm::LogicalResult {0}::verifyInvariantsImpl() {{
if(::mlir::failed(verify()))
return ::mlir::failure();
{1}
return ::mlir::success();
})",
strings.opCppName, llvm::join(verifierCalls, "\n"));
dict["OP_VERIFIER_HELPERS"] = llvm::join(verifierHelpers, "\n");
dict["OP_VERIFIER"] = verifierDef;
}
static std::string generateOpDefinition(irdl::detail::dictionary &dict,
irdl::OperationOp op) {
static const auto perOpDefTemplate = mlir::irdl::detail::Template{
#include "Templates/PerOperationDef.txt"
};
auto opStrings = getStrings(op);
fillDict(dict, opStrings);
const auto operandCount = opStrings.opOperandNames.size();
const auto operandNames =
operandCount ? joinNameList(opStrings.opOperandNames) : "{\"\"}";
const auto resultNames = joinNameList(opStrings.opResultNames);
auto resultTypes = llvm::join(
llvm::map_range(opStrings.opResultNames,
[](StringRef attr) -> std::string {
return llvm::formatv("::mlir::Type {0}, ", attr);
}),
"");
auto operandTypes = llvm::join(
llvm::map_range(opStrings.opOperandNames,
[](StringRef attr) -> std::string {
return llvm::formatv("::mlir::Value {0}, ", attr);
}),
"");
auto operandAdder =
llvm::join(llvm::map_range(opStrings.opOperandNames,
[](StringRef attr) -> std::string {
return llvm::formatv(
" opState.addOperands({0});", attr);
}),
"\n");
auto resultAdder = llvm::join(
llvm::map_range(opStrings.opResultNames,
[](StringRef attr) -> std::string {
return llvm::formatv(" opState.addTypes({0});", attr);
}),
"\n");
const auto buildDefinition = llvm::formatv(
R"(
void {0}::build(::mlir::OpBuilder &opBuilder, ::mlir::OperationState &opState, {1} {2} ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) {{
{3}
{4}
}
{0} {0}::create(::mlir::OpBuilder &opBuilder, ::mlir::Location location, {1} {2} ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) {{
::mlir::OperationState __state__(location, getOperationName());
build(opBuilder, __state__, {5} {6} attributes);
auto __res__ = ::llvm::dyn_cast<{0}>(opBuilder.create(__state__));
assert(__res__ && "builder didn't return the right type");
return __res__;
}
{0} {0}::create(::mlir::ImplicitLocOpBuilder &opBuilder, {1} {2} ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) {{
return create(opBuilder, opBuilder.getLoc(), {5} {6} attributes);
}
)",
opStrings.opCppName, std::move(resultTypes), std::move(operandTypes),
std::move(operandAdder), std::move(resultAdder),
llvm::join(opStrings.opResultNames, ",") +
(!opStrings.opResultNames.empty() ? "," : ""),
llvm::join(opStrings.opOperandNames, ",") +
(!opStrings.opOperandNames.empty() ? "," : ""));
dict["OP_BUILD_DEFS"] = buildDefinition;
generateVerifiers(dict, op, opStrings);
std::string str;
llvm::raw_string_ostream stream{str};
perOpDefTemplate.render(stream, dict);
return str;
}
static std::string
generateTypeVerifierCase(StringRef name, const DialectStrings &dialectStrings) {
return llvm::formatv(
R"(.Case({1}::{0}::getMnemonic(), [&](llvm::StringRef, llvm::SMLoc) {
value = {1}::{0}::get(parser.getContext());
return ::mlir::success(!!value);
}))",
name, dialectStrings.namespacePath);
}
static LogicalResult generateLib(irdl::DialectOp dialect, raw_ostream &output,
DialectStrings &dialectStrings) {
static const auto typeHeaderDefTemplate = mlir::irdl::detail::Template{
#include "Templates/TypeHeaderDef.txt"
};
static const auto typeDefTemplate = mlir::irdl::detail::Template{
#include "Templates/TypeDef.txt"
};
static const auto dialectDefTemplate = mlir::irdl::detail::Template{
#include "Templates/DialectDef.txt"
};
irdl::detail::dictionary dict;
fillDict(dict, dialectStrings);
typeHeaderDefTemplate.render(output, dict);
SmallVector<std::string> typeNames;
if (failed(generateTypedefList(dialect, typeNames)))
return failure();
dict["TYPE_LIST"] = llvm::join(
llvm::map_range(typeNames,
[&dialectStrings](llvm::StringRef name) -> std::string {
return llvm::formatv(
"{0}::{1}", dialectStrings.namespacePath, name);
}),
",\n");
auto typeVerifierGenerator =
[&dialectStrings](llvm::StringRef name) -> std::string {
return generateTypeVerifierCase(name, dialectStrings);
};
auto typeCase =
llvm::join(llvm::map_range(typeNames, typeVerifierGenerator), "\n");
dict["TYPE_PARSER"] = llvm::formatv(
R"(static ::mlir::OptionalParseResult generatedTypeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type &value) {
return ::mlir::AsmParser::KeywordSwitch<::mlir::OptionalParseResult>(parser)
{0}
.Default([&](llvm::StringRef keyword, llvm::SMLoc) {{
*mnemonic = keyword;
return std::nullopt;
});
})",
std::move(typeCase));
auto typePrintCase =
llvm::join(llvm::map_range(typeNames,
[&](llvm::StringRef name) -> std::string {
return llvm::formatv(
R"(.Case<{1}::{0}>([&](auto t) {
printer << {1}::{0}::getMnemonic();
return ::mlir::success();
}))",
name, dialectStrings.namespacePath);
}),
"\n");
dict["TYPE_PRINTER"] = llvm::formatv(
R"(static ::llvm::LogicalResult generatedTypePrinter(::mlir::Type def, ::mlir::AsmPrinter &printer) {
return ::llvm::TypeSwitch<::mlir::Type, ::llvm::LogicalResult>(def)
{0}
.Default([](auto) {{ return ::mlir::failure(); });
})",
std::move(typePrintCase));
dict["TYPE_DEFINES"] =
join(map_range(typeNames,
[&](StringRef name) -> std::string {
return formatv("MLIR_DEFINE_EXPLICIT_TYPE_ID({1}::{0})",
name, dialectStrings.namespacePath);
}),
"\n");
typeDefTemplate.render(output, dict);
auto operations = dialect.getOps<irdl::OperationOp>();
SmallVector<std::string> opNames;
if (failed(generateOpList(dialect, opNames)))
return failure();
const auto commaSeparatedOpList = llvm::join(
map_range(opNames,
[&dialectStrings](llvm::StringRef name) -> std::string {
return llvm::formatv("{0}::{1}", dialectStrings.namespacePath,
name);
}),
",\n");
const auto opDefinitionGenerator = [&dict](irdl::OperationOp op) {
return generateOpDefinition(dict, op);
};
const auto perOpDefinitions =
llvm::join(llvm::map_range(operations, opDefinitionGenerator), "\n");
dict["OP_LIST"] = commaSeparatedOpList;
dict["OP_CLASSES"] = perOpDefinitions;
output << perOpDefinitions;
dialectDefTemplate.render(output, dict);
return success();
}
static LogicalResult verifySupported(irdl::DialectOp dialect) {
LogicalResult res = success();
dialect.walk([&](mlir::Operation *op) {
res =
llvm::TypeSwitch<Operation *, LogicalResult>(op)
.Case<irdl::DialectOp>(([](irdl::DialectOp) { return success(); }))
.Case<irdl::OperationOp>(
([](irdl::OperationOp) { return success(); }))
.Case<irdl::TypeOp>(([](irdl::TypeOp) { return success(); }))
.Case<irdl::OperandsOp>(([](irdl::OperandsOp op) -> LogicalResult {
if (llvm::all_of(
op.getVariadicity(), [](irdl::VariadicityAttr attr) {
return attr.getValue() == irdl::Variadicity::single;
}))
return success();
return op.emitError("IRDL C++ translation does not yet support "
"variadic operations");
}))
.Case<irdl::ResultsOp>(([](irdl::ResultsOp op) -> LogicalResult {
if (llvm::all_of(
op.getVariadicity(), [](irdl::VariadicityAttr attr) {
return attr.getValue() == irdl::Variadicity::single;
}))
return success();
return op.emitError(
"IRDL C++ translation does not yet support variadic results");
}))
.Case<irdl::AnyOp>(([](irdl::AnyOp) { return success(); }))
.Case<irdl::RegionOp>(([](irdl::RegionOp) { return success(); }))
.Case<irdl::RegionsOp>(([](irdl::RegionsOp) { return success(); }))
.Default([](mlir::Operation *op) -> LogicalResult {
return op->emitError("IRDL C++ translation does not yet support "
"translation of ")
<< op->getName() << " operation";
});
if (failed(res))
return WalkResult::interrupt();
return WalkResult::advance();
});
return res;
}
LogicalResult
irdl::translateIRDLDialectToCpp(llvm::ArrayRef<irdl::DialectOp> dialects,
raw_ostream &output) {
static const auto typeDefTempl = detail::Template(
#include "Templates/TypeDef.txt"
);
llvm::SmallMapVector<DialectOp, DialectStrings, 2> dialectStringTable;
for (auto dialect : dialects) {
if (failed(verifySupported(dialect)))
return failure();
StringRef dialectName = dialect.getSymName();
SmallVector<SmallString<8>> namespaceAbsolutePath{{"mlir"}, dialectName};
std::string namespaceOpen;
std::string namespaceClose;
std::string namespacePath;
llvm::raw_string_ostream namespaceOpenStream(namespaceOpen);
llvm::raw_string_ostream namespaceCloseStream(namespaceClose);
llvm::raw_string_ostream namespacePathStream(namespacePath);
for (auto &pathElement : namespaceAbsolutePath) {
namespaceOpenStream << "namespace " << pathElement << " {\n";
namespaceCloseStream << "} // namespace " << pathElement << "\n";
namespacePathStream << "::" << pathElement;
}
std::string cppShortName =
llvm::convertToCamelFromSnakeCase(dialectName, true);
std::string dialectBaseTypeName = llvm::formatv("{0}Type", cppShortName);
std::string cppName = llvm::formatv("{0}Dialect", cppShortName);
DialectStrings dialectStrings;
dialectStrings.dialectName = dialectName;
dialectStrings.dialectBaseTypeName = dialectBaseTypeName;
dialectStrings.dialectCppName = cppName;
dialectStrings.dialectCppShortName = cppShortName;
dialectStrings.namespaceOpen = namespaceOpen;
dialectStrings.namespaceClose = namespaceClose;
dialectStrings.namespacePath = namespacePath;
dialectStringTable[dialect] = std::move(dialectStrings);
}
// generate the actual header
output << headerTemplateText;
output << llvm::formatv("#ifdef {0}\n#undef {0}\n", declarationMacroFlag);
for (auto dialect : dialects) {
auto &dialectStrings = dialectStringTable[dialect];
auto &dialectName = dialectStrings.dialectName;
if (failed(generateInclude(dialect, output, dialectStrings)))
return dialect->emitError("Error in Dialect " + dialectName +
" while generating headers");
}
output << llvm::formatv("#endif // #ifdef {}\n", declarationMacroFlag);
output << llvm::formatv("#ifdef {0}\n#undef {0}\n ", definitionMacroFlag);
for (auto &dialect : dialects) {
auto &dialectStrings = dialectStringTable[dialect];
auto &dialectName = dialectStrings.dialectName;
if (failed(generateLib(dialect, output, dialectStrings)))
return dialect->emitError("Error in Dialect " + dialectName +
" while generating library");
}
output << llvm::formatv("#endif // #ifdef {}\n", definitionMacroFlag);
return success();
}
|