forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpFormatGen.cpp
3828 lines (3464 loc) · 150 KB
/
OpFormatGen.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
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- OpFormatGen.cpp - MLIR operation asm format generator --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "OpFormatGen.h"
#include "FormatGen.h"
#include "OpClass.h"
#include "mlir/Support/LLVM.h"
#include "mlir/TableGen/Class.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/Operator.h"
#include "mlir/TableGen/Trait.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/TableGen/Record.h"
#define DEBUG_TYPE "mlir-tblgen-opformatgen"
using namespace mlir;
using namespace mlir::tblgen;
using llvm::formatv;
using llvm::Record;
using llvm::StringMap;
//===----------------------------------------------------------------------===//
// VariableElement
namespace {
/// This class represents an instance of an op variable element. A variable
/// refers to something registered on the operation itself, e.g. an operand,
/// result, attribute, region, or successor.
template <typename VarT, VariableElement::Kind VariableKind>
class OpVariableElement : public VariableElementBase<VariableKind> {
public:
using Base = OpVariableElement<VarT, VariableKind>;
/// Create an op variable element with the variable value.
OpVariableElement(const VarT *var) : var(var) {}
/// Get the variable.
const VarT *getVar() const { return var; }
protected:
/// The op variable, e.g. a type or attribute constraint.
const VarT *var;
};
/// This class represents a variable that refers to an attribute argument.
struct AttributeVariable
: public OpVariableElement<NamedAttribute, VariableElement::Attribute> {
using Base::Base;
/// Return the constant builder call for the type of this attribute, or
/// std::nullopt if it doesn't have one.
std::optional<StringRef> getTypeBuilder() const {
std::optional<Type> attrType = var->attr.getValueType();
return attrType ? attrType->getBuilderCall() : std::nullopt;
}
/// Indicate if this attribute is printed "qualified" (that is it is
/// prefixed with the `#dialect.mnemonic`).
bool shouldBeQualified() { return shouldBeQualifiedFlag; }
void setShouldBeQualified(bool qualified = true) {
shouldBeQualifiedFlag = qualified;
}
private:
bool shouldBeQualifiedFlag = false;
};
/// This class represents a variable that refers to an operand argument.
using OperandVariable =
OpVariableElement<NamedTypeConstraint, VariableElement::Operand>;
/// This class represents a variable that refers to a result.
using ResultVariable =
OpVariableElement<NamedTypeConstraint, VariableElement::Result>;
/// This class represents a variable that refers to a region.
using RegionVariable = OpVariableElement<NamedRegion, VariableElement::Region>;
/// This class represents a variable that refers to a successor.
using SuccessorVariable =
OpVariableElement<NamedSuccessor, VariableElement::Successor>;
/// This class represents a variable that refers to a property argument.
using PropertyVariable =
OpVariableElement<NamedProperty, VariableElement::Property>;
/// LLVM RTTI helper for attribute-like variables, that is, attributes or
/// properties. This allows for common handling of attributes and properties in
/// parts of the code that are oblivious to whether something is stored as an
/// attribute or a property.
struct AttributeLikeVariable : public VariableElement {
enum { AttributeLike = 1 << 0 };
static bool classof(const VariableElement *ve) {
return ve->getKind() == VariableElement::Attribute ||
ve->getKind() == VariableElement::Property;
}
static bool classof(const FormatElement *fe) {
return isa<VariableElement>(fe) && classof(cast<VariableElement>(fe));
}
/// Returns true if the variable is a UnitAttr or a UnitProp.
bool isUnit() const {
if (const auto *attr = dyn_cast<AttributeVariable>(this))
return attr->getVar()->attr.getBaseAttr().getAttrDefName() == "UnitAttr";
if (const auto *prop = dyn_cast<PropertyVariable>(this)) {
StringRef baseDefName =
prop->getVar()->prop.getBaseProperty().getPropertyDefName();
// Note: remove the `UnitProperty` case once the deprecation period is
// over.
return baseDefName == "UnitProp" || baseDefName == "UnitProperty";
}
llvm_unreachable("Type that wasn't listed in classof()");
}
StringRef getName() const {
if (const auto *attr = dyn_cast<AttributeVariable>(this))
return attr->getVar()->name;
if (const auto *prop = dyn_cast<PropertyVariable>(this))
return prop->getVar()->name;
llvm_unreachable("Type that wasn't listed in classof()");
}
};
} // namespace
//===----------------------------------------------------------------------===//
// DirectiveElement
namespace {
/// This class represents the `operands` directive. This directive represents
/// all of the operands of an operation.
using OperandsDirective = DirectiveElementBase<DirectiveElement::Operands>;
/// This class represents the `results` directive. This directive represents
/// all of the results of an operation.
using ResultsDirective = DirectiveElementBase<DirectiveElement::Results>;
/// This class represents the `regions` directive. This directive represents
/// all of the regions of an operation.
using RegionsDirective = DirectiveElementBase<DirectiveElement::Regions>;
/// This class represents the `successors` directive. This directive represents
/// all of the successors of an operation.
using SuccessorsDirective = DirectiveElementBase<DirectiveElement::Successors>;
/// This class represents the `attr-dict` directive. This directive represents
/// the attribute dictionary of the operation.
class AttrDictDirective
: public DirectiveElementBase<DirectiveElement::AttrDict> {
public:
explicit AttrDictDirective(bool withKeyword) : withKeyword(withKeyword) {}
/// Return whether the dictionary should be printed with the 'attributes'
/// keyword.
bool isWithKeyword() const { return withKeyword; }
private:
/// If the dictionary should be printed with the 'attributes' keyword.
bool withKeyword;
};
/// This class represents the `prop-dict` directive. This directive represents
/// the properties of the operation, expressed as a directionary.
class PropDictDirective
: public DirectiveElementBase<DirectiveElement::PropDict> {
public:
explicit PropDictDirective() = default;
};
/// This class represents the `functional-type` directive. This directive takes
/// two arguments and formats them, respectively, as the inputs and results of a
/// FunctionType.
class FunctionalTypeDirective
: public DirectiveElementBase<DirectiveElement::FunctionalType> {
public:
FunctionalTypeDirective(FormatElement *inputs, FormatElement *results)
: inputs(inputs), results(results) {}
FormatElement *getInputs() const { return inputs; }
FormatElement *getResults() const { return results; }
private:
/// The input and result arguments.
FormatElement *inputs, *results;
};
/// This class represents the `type` directive.
class TypeDirective : public DirectiveElementBase<DirectiveElement::Type> {
public:
TypeDirective(FormatElement *arg) : arg(arg) {}
FormatElement *getArg() const { return arg; }
/// Indicate if this type is printed "qualified" (that is it is
/// prefixed with the `!dialect.mnemonic`).
bool shouldBeQualified() { return shouldBeQualifiedFlag; }
void setShouldBeQualified(bool qualified = true) {
shouldBeQualifiedFlag = qualified;
}
private:
/// The argument that is used to format the directive.
FormatElement *arg;
bool shouldBeQualifiedFlag = false;
};
/// This class represents a group of order-independent optional clauses. Each
/// clause starts with a literal element and has a coressponding parsing
/// element. A parsing element is a continous sequence of format elements.
/// Each clause can appear 0 or 1 time.
class OIListElement : public DirectiveElementBase<DirectiveElement::OIList> {
public:
OIListElement(std::vector<FormatElement *> &&literalElements,
std::vector<std::vector<FormatElement *>> &&parsingElements)
: literalElements(std::move(literalElements)),
parsingElements(std::move(parsingElements)) {}
/// Returns a range to iterate over the LiteralElements.
auto getLiteralElements() const {
return llvm::map_range(literalElements, [](FormatElement *el) {
return cast<LiteralElement>(el);
});
}
/// Returns a range to iterate over the parsing elements corresponding to the
/// clauses.
ArrayRef<std::vector<FormatElement *>> getParsingElements() const {
return parsingElements;
}
/// Returns a range to iterate over tuples of parsing and literal elements.
auto getClauses() const {
return llvm::zip(getLiteralElements(), getParsingElements());
}
/// If the parsing element is a single UnitAttr element, then it returns the
/// attribute variable. Otherwise, returns nullptr.
AttributeLikeVariable *
getUnitVariableParsingElement(ArrayRef<FormatElement *> pelement) {
if (pelement.size() == 1) {
auto *attrElem = dyn_cast<AttributeLikeVariable>(pelement[0]);
if (attrElem && attrElem->isUnit())
return attrElem;
}
return nullptr;
}
private:
/// A vector of `LiteralElement` objects. Each element stores the keyword
/// for one case of oilist element. For example, an oilist element along with
/// the `literalElements` vector:
/// ```
/// oilist [ `keyword` `=` `(` $arg0 `)` | `otherKeyword` `<` $arg1 `>`]
/// literalElements = { `keyword`, `otherKeyword` }
/// ```
std::vector<FormatElement *> literalElements;
/// A vector of valid declarative assembly format vectors. Each object in
/// parsing elements is a vector of elements in assembly format syntax.
/// For example, an oilist element along with the parsingElements vector:
/// ```
/// oilist [ `keyword` `=` `(` $arg0 `)` | `otherKeyword` `<` $arg1 `>`]
/// parsingElements = {
/// { `=`, `(`, $arg0, `)` },
/// { `<`, $arg1, `>` }
/// }
/// ```
std::vector<std::vector<FormatElement *>> parsingElements;
};
} // namespace
//===----------------------------------------------------------------------===//
// OperationFormat
//===----------------------------------------------------------------------===//
namespace {
using ConstArgument =
llvm::PointerUnion<const NamedAttribute *, const NamedTypeConstraint *>;
struct OperationFormat {
/// This class represents a specific resolver for an operand or result type.
class TypeResolution {
public:
TypeResolution() = default;
/// Get the index into the buildable types for this type, or std::nullopt.
std::optional<int> getBuilderIdx() const { return builderIdx; }
void setBuilderIdx(int idx) { builderIdx = idx; }
/// Get the variable this type is resolved to, or nullptr.
const NamedTypeConstraint *getVariable() const {
return llvm::dyn_cast_if_present<const NamedTypeConstraint *>(resolver);
}
/// Get the attribute this type is resolved to, or nullptr.
const NamedAttribute *getAttribute() const {
return llvm::dyn_cast_if_present<const NamedAttribute *>(resolver);
}
/// Get the transformer for the type of the variable, or std::nullopt.
std::optional<StringRef> getVarTransformer() const {
return variableTransformer;
}
void setResolver(ConstArgument arg, std::optional<StringRef> transformer) {
resolver = arg;
variableTransformer = transformer;
assert(getVariable() || getAttribute());
}
private:
/// If the type is resolved with a buildable type, this is the index into
/// 'buildableTypes' in the parent format.
std::optional<int> builderIdx;
/// If the type is resolved based upon another operand or result, this is
/// the variable or the attribute that this type is resolved to.
ConstArgument resolver;
/// If the type is resolved based upon another operand or result, this is
/// a transformer to apply to the variable when resolving.
std::optional<StringRef> variableTransformer;
};
/// The context in which an element is generated.
enum class GenContext {
/// The element is generated at the top-level or with the same behaviour.
Normal,
/// The element is generated inside an optional group.
Optional
};
OperationFormat(const Operator &op, bool hasProperties)
: useProperties(hasProperties), opCppClassName(op.getCppClassName()) {
operandTypes.resize(op.getNumOperands(), TypeResolution());
resultTypes.resize(op.getNumResults(), TypeResolution());
hasImplicitTermTrait = llvm::any_of(op.getTraits(), [](const Trait &trait) {
return trait.getDef().isSubClassOf("SingleBlockImplicitTerminatorImpl");
});
hasSingleBlockTrait = op.getTrait("::mlir::OpTrait::SingleBlock");
}
/// Generate the operation parser from this format.
void genParser(Operator &op, OpClass &opClass);
/// Generate the parser code for a specific format element.
void genElementParser(FormatElement *element, MethodBody &body,
FmtContext &attrTypeCtx,
GenContext genCtx = GenContext::Normal);
/// Generate the C++ to resolve the types of operands and results during
/// parsing.
void genParserTypeResolution(Operator &op, MethodBody &body);
/// Generate the C++ to resolve the types of the operands during parsing.
void genParserOperandTypeResolution(
Operator &op, MethodBody &body,
function_ref<void(TypeResolution &, StringRef)> emitTypeResolver);
/// Generate the C++ to resolve regions during parsing.
void genParserRegionResolution(Operator &op, MethodBody &body);
/// Generate the C++ to resolve successors during parsing.
void genParserSuccessorResolution(Operator &op, MethodBody &body);
/// Generate the C++ to handling variadic segment size traits.
void genParserVariadicSegmentResolution(Operator &op, MethodBody &body);
/// Generate the operation printer from this format.
void genPrinter(Operator &op, OpClass &opClass);
/// Generate the printer code for a specific format element.
void genElementPrinter(FormatElement *element, MethodBody &body, Operator &op,
bool &shouldEmitSpace, bool &lastWasPunctuation);
/// The various elements in this format.
std::vector<FormatElement *> elements;
/// A flag indicating if all operand/result types were seen. If the format
/// contains these, it can not contain individual type resolvers.
bool allOperands = false, allOperandTypes = false, allResultTypes = false;
/// A flag indicating if this operation infers its result types
bool infersResultTypes = false;
/// A flag indicating if this operation has the SingleBlockImplicitTerminator
/// trait.
bool hasImplicitTermTrait;
/// A flag indicating if this operation has the SingleBlock trait.
bool hasSingleBlockTrait;
/// Indicate whether we need to use properties for the current operator.
bool useProperties;
/// Indicate whether prop-dict is used in the format
bool hasPropDict;
/// The Operation class name
StringRef opCppClassName;
/// A map of buildable types to indices.
llvm::MapVector<StringRef, int, StringMap<int>> buildableTypes;
/// The index of the buildable type, if valid, for every operand and result.
std::vector<TypeResolution> operandTypes, resultTypes;
/// The set of attributes explicitly used within the format.
llvm::SmallSetVector<const NamedAttribute *, 8> usedAttributes;
llvm::StringSet<> inferredAttributes;
/// The set of properties explicitly used within the format.
llvm::SmallSetVector<const NamedProperty *, 8> usedProperties;
};
} // namespace
//===----------------------------------------------------------------------===//
// Parser Gen
/// Returns true if we can format the given attribute as an EnumAttr in the
/// parser format.
static bool canFormatEnumAttr(const NamedAttribute *attr) {
Attribute baseAttr = attr->attr.getBaseAttr();
const EnumAttr *enumAttr = dyn_cast<EnumAttr>(&baseAttr);
if (!enumAttr)
return false;
// The attribute must have a valid underlying type and a constant builder.
return !enumAttr->getUnderlyingType().empty() &&
!enumAttr->getConstBuilderTemplate().empty();
}
/// Returns if we should format the given attribute as an SymbolNameAttr.
static bool shouldFormatSymbolNameAttr(const NamedAttribute *attr) {
return attr->attr.getBaseAttr().getAttrDefName() == "SymbolNameAttr";
}
/// The code snippet used to generate a parser call for an attribute.
///
/// {0}: The name of the attribute.
/// {1}: The type for the attribute.
const char *const attrParserCode = R"(
if (parser.parseCustomAttributeWithFallback({0}Attr, {1})) {{
return ::mlir::failure();
}
)";
/// The code snippet used to generate a parser call for an attribute.
///
/// {0}: The name of the attribute.
/// {1}: The type for the attribute.
const char *const genericAttrParserCode = R"(
if (parser.parseAttribute({0}Attr, {1}))
return ::mlir::failure();
)";
const char *const optionalAttrParserCode = R"(
::mlir::OptionalParseResult parseResult{0}Attr =
parser.parseOptionalAttribute({0}Attr, {1});
if (parseResult{0}Attr.has_value() && failed(*parseResult{0}Attr))
return ::mlir::failure();
if (parseResult{0}Attr.has_value() && succeeded(*parseResult{0}Attr))
)";
/// The code snippet used to generate a parser call for a symbol name attribute.
///
/// {0}: The name of the attribute.
const char *const symbolNameAttrParserCode = R"(
if (parser.parseSymbolName({0}Attr))
return ::mlir::failure();
)";
const char *const optionalSymbolNameAttrParserCode = R"(
// Parsing an optional symbol name doesn't fail, so no need to check the
// result.
(void)parser.parseOptionalSymbolName({0}Attr);
)";
/// The code snippet used to generate a parser call for an enum attribute.
///
/// {0}: The name of the attribute.
/// {1}: The c++ namespace for the enum symbolize functions.
/// {2}: The function to symbolize a string of the enum.
/// {3}: The constant builder call to create an attribute of the enum type.
/// {4}: The set of allowed enum keywords.
/// {5}: The error message on failure when the enum isn't present.
/// {6}: The attribute assignment expression
const char *const enumAttrParserCode = R"(
{
::llvm::StringRef attrStr;
::mlir::NamedAttrList attrStorage;
auto loc = parser.getCurrentLocation();
if (parser.parseOptionalKeyword(&attrStr, {4})) {
::mlir::StringAttr attrVal;
::mlir::OptionalParseResult parseResult =
parser.parseOptionalAttribute(attrVal,
parser.getBuilder().getNoneType(),
"{0}", attrStorage);
if (parseResult.has_value()) {{
if (failed(*parseResult))
return ::mlir::failure();
attrStr = attrVal.getValue();
} else {
{5}
}
}
if (!attrStr.empty()) {
auto attrOptional = {1}::{2}(attrStr);
if (!attrOptional)
return parser.emitError(loc, "invalid ")
<< "{0} attribute specification: \"" << attrStr << '"';;
{0}Attr = {3};
{6}
}
}
)";
/// The code snippet used to generate a parser call for a property.
/// {0}: The name of the property
/// {1}: The C++ class name of the operation
/// {2}: The property's parser code with appropriate substitutions performed
/// {3}: The description of the expected property for the error message.
const char *const propertyParserCode = R"(
auto {0}PropLoc = parser.getCurrentLocation();
auto {0}PropParseResult = [&](auto& propStorage) -> ::mlir::ParseResult {{
{2}
return ::mlir::success();
}(result.getOrAddProperties<{1}::Properties>().{0});
if (failed({0}PropParseResult)) {{
return parser.emitError({0}PropLoc, "invalid value for property {0}, expected {3}");
}
)";
/// The code snippet used to generate a parser call for a property.
/// {0}: The name of the property
/// {1}: The C++ class name of the operation
/// {2}: The property's parser code with appropriate substitutions performed
const char *const optionalPropertyParserCode = R"(
auto {0}PropParseResult = [&](auto& propStorage) -> ::mlir::OptionalParseResult {{
{2}
return ::mlir::success();
}(result.getOrAddProperties<{1}::Properties>().{0});
if ({0}PropParseResult.has_value() && failed(*{0}PropParseResult)) {{
return ::mlir::failure();
}
)";
/// The code snippet used to generate a parser call for an operand.
///
/// {0}: The name of the operand.
const char *const variadicOperandParserCode = R"(
{0}OperandsLoc = parser.getCurrentLocation();
if (parser.parseOperandList({0}Operands))
return ::mlir::failure();
)";
const char *const optionalOperandParserCode = R"(
{
{0}OperandsLoc = parser.getCurrentLocation();
::mlir::OpAsmParser::UnresolvedOperand operand;
::mlir::OptionalParseResult parseResult =
parser.parseOptionalOperand(operand);
if (parseResult.has_value()) {
if (failed(*parseResult))
return ::mlir::failure();
{0}Operands.push_back(operand);
}
}
)";
const char *const operandParserCode = R"(
{0}OperandsLoc = parser.getCurrentLocation();
if (parser.parseOperand({0}RawOperand))
return ::mlir::failure();
)";
/// The code snippet used to generate a parser call for a VariadicOfVariadic
/// operand.
///
/// {0}: The name of the operand.
/// {1}: The name of segment size attribute.
const char *const variadicOfVariadicOperandParserCode = R"(
{
{0}OperandsLoc = parser.getCurrentLocation();
int32_t curSize = 0;
do {
if (parser.parseOptionalLParen())
break;
if (parser.parseOperandList({0}Operands) || parser.parseRParen())
return ::mlir::failure();
{0}OperandGroupSizes.push_back({0}Operands.size() - curSize);
curSize = {0}Operands.size();
} while (succeeded(parser.parseOptionalComma()));
}
)";
/// The code snippet used to generate a parser call for a type list.
///
/// {0}: The name for the type list.
const char *const variadicOfVariadicTypeParserCode = R"(
do {
if (parser.parseOptionalLParen())
break;
if (parser.parseOptionalRParen() &&
(parser.parseTypeList({0}Types) || parser.parseRParen()))
return ::mlir::failure();
} while (succeeded(parser.parseOptionalComma()));
)";
const char *const variadicTypeParserCode = R"(
if (parser.parseTypeList({0}Types))
return ::mlir::failure();
)";
const char *const optionalTypeParserCode = R"(
{
::mlir::Type optionalType;
::mlir::OptionalParseResult parseResult =
parser.parseOptionalType(optionalType);
if (parseResult.has_value()) {
if (failed(*parseResult))
return ::mlir::failure();
{0}Types.push_back(optionalType);
}
}
)";
const char *const typeParserCode = R"(
{
{0} type;
if (parser.parseCustomTypeWithFallback(type))
return ::mlir::failure();
{1}RawType = type;
}
)";
const char *const qualifiedTypeParserCode = R"(
if (parser.parseType({1}RawType))
return ::mlir::failure();
)";
/// The code snippet used to generate a parser call for a functional type.
///
/// {0}: The name for the input type list.
/// {1}: The name for the result type list.
const char *const functionalTypeParserCode = R"(
::mlir::FunctionType {0}__{1}_functionType;
if (parser.parseType({0}__{1}_functionType))
return ::mlir::failure();
{0}Types = {0}__{1}_functionType.getInputs();
{1}Types = {0}__{1}_functionType.getResults();
)";
/// The code snippet used to generate a parser call to infer return types.
///
/// {0}: The operation class name
const char *const inferReturnTypesParserCode = R"(
::llvm::SmallVector<::mlir::Type> inferredReturnTypes;
if (::mlir::failed({0}::inferReturnTypes(parser.getContext(),
result.location, result.operands,
result.attributes.getDictionary(parser.getContext()),
result.getRawProperties(),
result.regions, inferredReturnTypes)))
return ::mlir::failure();
result.addTypes(inferredReturnTypes);
)";
/// The code snippet used to generate a parser call for a region list.
///
/// {0}: The name for the region list.
const char *regionListParserCode = R"(
{
std::unique_ptr<::mlir::Region> region;
auto firstRegionResult = parser.parseOptionalRegion(region);
if (firstRegionResult.has_value()) {
if (failed(*firstRegionResult))
return ::mlir::failure();
{0}Regions.emplace_back(std::move(region));
// Parse any trailing regions.
while (succeeded(parser.parseOptionalComma())) {
region = std::make_unique<::mlir::Region>();
if (parser.parseRegion(*region))
return ::mlir::failure();
{0}Regions.emplace_back(std::move(region));
}
}
}
)";
/// The code snippet used to ensure a list of regions have terminators.
///
/// {0}: The name of the region list.
const char *regionListEnsureTerminatorParserCode = R"(
for (auto ®ion : {0}Regions)
ensureTerminator(*region, parser.getBuilder(), result.location);
)";
/// The code snippet used to ensure a list of regions have a block.
///
/// {0}: The name of the region list.
const char *regionListEnsureSingleBlockParserCode = R"(
for (auto ®ion : {0}Regions)
if (region->empty()) region->emplaceBlock();
)";
/// The code snippet used to generate a parser call for an optional region.
///
/// {0}: The name of the region.
const char *optionalRegionParserCode = R"(
{
auto parseResult = parser.parseOptionalRegion(*{0}Region);
if (parseResult.has_value() && failed(*parseResult))
return ::mlir::failure();
}
)";
/// The code snippet used to generate a parser call for a region.
///
/// {0}: The name of the region.
const char *regionParserCode = R"(
if (parser.parseRegion(*{0}Region))
return ::mlir::failure();
)";
/// The code snippet used to ensure a region has a terminator.
///
/// {0}: The name of the region.
const char *regionEnsureTerminatorParserCode = R"(
ensureTerminator(*{0}Region, parser.getBuilder(), result.location);
)";
/// The code snippet used to ensure a region has a block.
///
/// {0}: The name of the region.
const char *regionEnsureSingleBlockParserCode = R"(
if ({0}Region->empty()) {0}Region->emplaceBlock();
)";
/// The code snippet used to generate a parser call for a successor list.
///
/// {0}: The name for the successor list.
const char *successorListParserCode = R"(
{
::mlir::Block *succ;
auto firstSucc = parser.parseOptionalSuccessor(succ);
if (firstSucc.has_value()) {
if (failed(*firstSucc))
return ::mlir::failure();
{0}Successors.emplace_back(succ);
// Parse any trailing successors.
while (succeeded(parser.parseOptionalComma())) {
if (parser.parseSuccessor(succ))
return ::mlir::failure();
{0}Successors.emplace_back(succ);
}
}
}
)";
/// The code snippet used to generate a parser call for a successor.
///
/// {0}: The name of the successor.
const char *successorParserCode = R"(
if (parser.parseSuccessor({0}Successor))
return ::mlir::failure();
)";
/// The code snippet used to generate a parser for OIList
///
/// {0}: literal keyword corresponding to a case for oilist
const char *oilistParserCode = R"(
if ({0}Clause) {
return parser.emitError(parser.getNameLoc())
<< "`{0}` clause can appear at most once in the expansion of the "
"oilist directive";
}
{0}Clause = true;
)";
namespace {
/// The type of length for a given parse argument.
enum class ArgumentLengthKind {
/// The argument is a variadic of a variadic, and may contain 0->N range
/// elements.
VariadicOfVariadic,
/// The argument is variadic, and may contain 0->N elements.
Variadic,
/// The argument is optional, and may contain 0 or 1 elements.
Optional,
/// The argument is a single element, i.e. always represents 1 element.
Single
};
} // namespace
/// Get the length kind for the given constraint.
static ArgumentLengthKind
getArgumentLengthKind(const NamedTypeConstraint *var) {
if (var->isOptional())
return ArgumentLengthKind::Optional;
if (var->isVariadicOfVariadic())
return ArgumentLengthKind::VariadicOfVariadic;
if (var->isVariadic())
return ArgumentLengthKind::Variadic;
return ArgumentLengthKind::Single;
}
/// Get the name used for the type list for the given type directive operand.
/// 'lengthKind' to the corresponding kind for the given argument.
static StringRef getTypeListName(FormatElement *arg,
ArgumentLengthKind &lengthKind) {
if (auto *operand = dyn_cast<OperandVariable>(arg)) {
lengthKind = getArgumentLengthKind(operand->getVar());
return operand->getVar()->name;
}
if (auto *result = dyn_cast<ResultVariable>(arg)) {
lengthKind = getArgumentLengthKind(result->getVar());
return result->getVar()->name;
}
lengthKind = ArgumentLengthKind::Variadic;
if (isa<OperandsDirective>(arg))
return "allOperand";
if (isa<ResultsDirective>(arg))
return "allResult";
llvm_unreachable("unknown 'type' directive argument");
}
/// Generate the parser for a literal value.
static void genLiteralParser(StringRef value, MethodBody &body) {
// Handle the case of a keyword/identifier.
if (value.front() == '_' || isalpha(value.front())) {
body << "Keyword(\"" << value << "\")";
return;
}
body << (StringRef)StringSwitch<StringRef>(value)
.Case("->", "Arrow()")
.Case(":", "Colon()")
.Case(",", "Comma()")
.Case("=", "Equal()")
.Case("<", "Less()")
.Case(">", "Greater()")
.Case("{", "LBrace()")
.Case("}", "RBrace()")
.Case("(", "LParen()")
.Case(")", "RParen()")
.Case("[", "LSquare()")
.Case("]", "RSquare()")
.Case("?", "Question()")
.Case("+", "Plus()")
.Case("*", "Star()")
.Case("...", "Ellipsis()");
}
/// Generate the storage code required for parsing the given element.
static void genElementParserStorage(FormatElement *element, const Operator &op,
MethodBody &body) {
if (auto *optional = dyn_cast<OptionalElement>(element)) {
ArrayRef<FormatElement *> elements = optional->getThenElements();
// If the anchor is a unit attribute, it won't be parsed directly so elide
// it.
auto *anchor = dyn_cast<AttributeLikeVariable>(optional->getAnchor());
FormatElement *elidedAnchorElement = nullptr;
if (anchor && anchor != elements.front() && anchor->isUnit())
elidedAnchorElement = anchor;
for (FormatElement *childElement : elements)
if (childElement != elidedAnchorElement)
genElementParserStorage(childElement, op, body);
for (FormatElement *childElement : optional->getElseElements())
genElementParserStorage(childElement, op, body);
} else if (auto *oilist = dyn_cast<OIListElement>(element)) {
for (ArrayRef<FormatElement *> pelement : oilist->getParsingElements()) {
if (!oilist->getUnitVariableParsingElement(pelement))
for (FormatElement *element : pelement)
genElementParserStorage(element, op, body);
}
} else if (auto *custom = dyn_cast<CustomDirective>(element)) {
for (FormatElement *paramElement : custom->getArguments())
genElementParserStorage(paramElement, op, body);
} else if (isa<OperandsDirective>(element)) {
body << " ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> "
"allOperands;\n";
} else if (isa<RegionsDirective>(element)) {
body << " ::llvm::SmallVector<std::unique_ptr<::mlir::Region>, 2> "
"fullRegions;\n";
} else if (isa<SuccessorsDirective>(element)) {
body << " ::llvm::SmallVector<::mlir::Block *, 2> fullSuccessors;\n";
} else if (auto *attr = dyn_cast<AttributeVariable>(element)) {
const NamedAttribute *var = attr->getVar();
body << formatv(" {0} {1}Attr;\n", var->attr.getStorageType(), var->name);
} else if (auto *operand = dyn_cast<OperandVariable>(element)) {
StringRef name = operand->getVar()->name;
if (operand->getVar()->isVariableLength()) {
body
<< " ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> "
<< name << "Operands;\n";
if (operand->getVar()->isVariadicOfVariadic()) {
body << " llvm::SmallVector<int32_t> " << name
<< "OperandGroupSizes;\n";
}
} else {
body << " ::mlir::OpAsmParser::UnresolvedOperand " << name
<< "RawOperand{};\n"
<< " ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> "
<< name << "Operands(&" << name << "RawOperand, 1);";
}
body << formatv(" ::llvm::SMLoc {0}OperandsLoc;\n"
" (void){0}OperandsLoc;\n",
name);
} else if (auto *region = dyn_cast<RegionVariable>(element)) {
StringRef name = region->getVar()->name;
if (region->getVar()->isVariadic()) {
body << formatv(
" ::llvm::SmallVector<std::unique_ptr<::mlir::Region>, 2> "
"{0}Regions;\n",
name);
} else {
body << formatv(" std::unique_ptr<::mlir::Region> {0}Region = "
"std::make_unique<::mlir::Region>();\n",
name);
}
} else if (auto *successor = dyn_cast<SuccessorVariable>(element)) {
StringRef name = successor->getVar()->name;
if (successor->getVar()->isVariadic()) {
body << formatv(" ::llvm::SmallVector<::mlir::Block *, 2> "
"{0}Successors;\n",
name);
} else {
body << formatv(" ::mlir::Block *{0}Successor = nullptr;\n", name);
}
} else if (auto *dir = dyn_cast<TypeDirective>(element)) {
ArgumentLengthKind lengthKind;
StringRef name = getTypeListName(dir->getArg(), lengthKind);
if (lengthKind != ArgumentLengthKind::Single)
body << " ::llvm::SmallVector<::mlir::Type, 1> " << name << "Types;\n";
else
body
<< formatv(" ::mlir::Type {0}RawType{{};\n", name)
<< formatv(
" ::llvm::ArrayRef<::mlir::Type> {0}Types(&{0}RawType, 1);\n",
name);
} else if (auto *dir = dyn_cast<FunctionalTypeDirective>(element)) {
ArgumentLengthKind ignored;
body << " ::llvm::ArrayRef<::mlir::Type> "
<< getTypeListName(dir->getInputs(), ignored) << "Types;\n";
body << " ::llvm::ArrayRef<::mlir::Type> "
<< getTypeListName(dir->getResults(), ignored) << "Types;\n";
}
}
/// Generate the parser for a parameter to a custom directive.
static void genCustomParameterParser(FormatElement *param, MethodBody &body) {
if (auto *attr = dyn_cast<AttributeVariable>(param)) {
body << attr->getVar()->name << "Attr";
} else if (isa<AttrDictDirective>(param)) {
body << "result.attributes";
} else if (isa<PropDictDirective>(param)) {
body << "result";
} else if (auto *operand = dyn_cast<OperandVariable>(param)) {
StringRef name = operand->getVar()->name;
ArgumentLengthKind lengthKind = getArgumentLengthKind(operand->getVar());
if (lengthKind == ArgumentLengthKind::VariadicOfVariadic)
body << formatv("{0}OperandGroups", name);
else if (lengthKind == ArgumentLengthKind::Variadic)
body << formatv("{0}Operands", name);
else if (lengthKind == ArgumentLengthKind::Optional)
body << formatv("{0}Operand", name);
else
body << formatv("{0}RawOperand", name);
} else if (auto *region = dyn_cast<RegionVariable>(param)) {
StringRef name = region->getVar()->name;
if (region->getVar()->isVariadic())
body << formatv("{0}Regions", name);
else
body << formatv("*{0}Region", name);
} else if (auto *successor = dyn_cast<SuccessorVariable>(param)) {
StringRef name = successor->getVar()->name;
if (successor->getVar()->isVariadic())
body << formatv("{0}Successors", name);
else
body << formatv("{0}Successor", name);
} else if (auto *dir = dyn_cast<RefDirective>(param)) {
genCustomParameterParser(dir->getArg(), body);
} else if (auto *dir = dyn_cast<TypeDirective>(param)) {
ArgumentLengthKind lengthKind;