/
OpImplementation.h
1812 lines (1512 loc) · 69.7 KB
/
OpImplementation.h
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
//===- OpImplementation.h - Classes for implementing Op types ---*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This classes used by the implementation details of Op types.
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_IR_OPIMPLEMENTATION_H
#define MLIR_IR_OPIMPLEMENTATION_H
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/DialectInterface.h"
#include "mlir/IR/OpDefinition.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/SMLoc.h"
#include <optional>
namespace mlir {
class AsmParsedResourceEntry;
class AsmResourceBuilder;
class Builder;
//===----------------------------------------------------------------------===//
// AsmDialectResourceHandle
//===----------------------------------------------------------------------===//
/// This class represents an opaque handle to a dialect resource entry.
class AsmDialectResourceHandle {
public:
AsmDialectResourceHandle() = default;
AsmDialectResourceHandle(void *resource, TypeID resourceID, Dialect *dialect)
: resource(resource), opaqueID(resourceID), dialect(dialect) {}
bool operator==(const AsmDialectResourceHandle &other) const {
return resource == other.resource;
}
/// Return an opaque pointer to the referenced resource.
void *getResource() const { return resource; }
/// Return the type ID of the resource.
TypeID getTypeID() const { return opaqueID; }
/// Return the dialect that owns the resource.
Dialect *getDialect() const { return dialect; }
private:
/// The opaque handle to the dialect resource.
void *resource = nullptr;
/// The type of the resource referenced.
TypeID opaqueID;
/// The dialect owning the given resource.
Dialect *dialect;
};
/// This class represents a CRTP base class for dialect resource handles. It
/// abstracts away various utilities necessary for defined derived resource
/// handles.
template <typename DerivedT, typename ResourceT, typename DialectT>
class AsmDialectResourceHandleBase : public AsmDialectResourceHandle {
public:
using Dialect = DialectT;
/// Construct a handle from a pointer to the resource. The given pointer
/// should be guaranteed to live beyond the life of this handle.
AsmDialectResourceHandleBase(ResourceT *resource, DialectT *dialect)
: AsmDialectResourceHandle(resource, TypeID::get<DerivedT>(), dialect) {}
AsmDialectResourceHandleBase(AsmDialectResourceHandle handle)
: AsmDialectResourceHandle(handle) {
assert(handle.getTypeID() == TypeID::get<DerivedT>());
}
/// Return the resource referenced by this handle.
ResourceT *getResource() {
return static_cast<ResourceT *>(AsmDialectResourceHandle::getResource());
}
const ResourceT *getResource() const {
return const_cast<AsmDialectResourceHandleBase *>(this)->getResource();
}
/// Return the dialect that owns the resource.
DialectT *getDialect() const {
return static_cast<DialectT *>(AsmDialectResourceHandle::getDialect());
}
/// Support llvm style casting.
static bool classof(const AsmDialectResourceHandle *handle) {
return handle->getTypeID() == TypeID::get<DerivedT>();
}
};
inline llvm::hash_code hash_value(const AsmDialectResourceHandle ¶m) {
return llvm::hash_value(param.getResource());
}
//===----------------------------------------------------------------------===//
// AsmPrinter
//===----------------------------------------------------------------------===//
/// This base class exposes generic asm printer hooks, usable across the various
/// derived printers.
class AsmPrinter {
public:
/// This class contains the internal default implementation of the base
/// printer methods.
class Impl;
/// Initialize the printer with the given internal implementation.
AsmPrinter(Impl &impl) : impl(&impl) {}
virtual ~AsmPrinter();
/// Return the raw output stream used by this printer.
virtual raw_ostream &getStream() const;
/// Print the given floating point value in a stabilized form that can be
/// roundtripped through the IR. This is the companion to the 'parseFloat'
/// hook on the AsmParser.
virtual void printFloat(const APFloat &value);
virtual void printType(Type type);
virtual void printAttribute(Attribute attr);
/// Trait to check if `AttrType` provides a `print` method.
template <typename AttrOrType>
using has_print_method =
decltype(std::declval<AttrOrType>().print(std::declval<AsmPrinter &>()));
template <typename AttrOrType>
using detect_has_print_method =
llvm::is_detected<has_print_method, AttrOrType>;
/// Print the provided attribute in the context of an operation custom
/// printer/parser: this will invoke directly the print method on the
/// attribute class and skip the `#dialect.mnemonic` prefix in most cases.
template <typename AttrOrType,
std::enable_if_t<detect_has_print_method<AttrOrType>::value>
*sfinae = nullptr>
void printStrippedAttrOrType(AttrOrType attrOrType) {
if (succeeded(printAlias(attrOrType)))
return;
raw_ostream &os = getStream();
uint64_t posPrior = os.tell();
attrOrType.print(*this);
if (posPrior != os.tell())
return;
// Fallback to printing with prefix if the above failed to write anything
// to the output stream.
*this << attrOrType;
}
/// Print the provided array of attributes or types in the context of an
/// operation custom printer/parser: this will invoke directly the print
/// method on the attribute class and skip the `#dialect.mnemonic` prefix in
/// most cases.
template <typename AttrOrType,
std::enable_if_t<detect_has_print_method<AttrOrType>::value>
*sfinae = nullptr>
void printStrippedAttrOrType(ArrayRef<AttrOrType> attrOrTypes) {
llvm::interleaveComma(
attrOrTypes, getStream(),
[this](AttrOrType attrOrType) { printStrippedAttrOrType(attrOrType); });
}
/// SFINAE for printing the provided attribute in the context of an operation
/// custom printer in the case where the attribute does not define a print
/// method.
template <typename AttrOrType,
std::enable_if_t<!detect_has_print_method<AttrOrType>::value>
*sfinae = nullptr>
void printStrippedAttrOrType(AttrOrType attrOrType) {
*this << attrOrType;
}
/// Print the given attribute without its type. The corresponding parser must
/// provide a valid type for the attribute.
virtual void printAttributeWithoutType(Attribute attr);
/// Print the alias for the given attribute, return failure if no alias could
/// be printed.
virtual LogicalResult printAlias(Attribute attr);
/// Print the alias for the given type, return failure if no alias could
/// be printed.
virtual LogicalResult printAlias(Type type);
/// Print the given string as a keyword, or a quoted and escaped string if it
/// has any special or non-printable characters in it.
virtual void printKeywordOrString(StringRef keyword);
/// Print the given string as a quoted string, escaping any special or
/// non-printable characters in it.
virtual void printString(StringRef string);
/// Print the given string as a symbol reference, i.e. a form representable by
/// a SymbolRefAttr. A symbol reference is represented as a string prefixed
/// with '@'. The reference is surrounded with ""'s and escaped if it has any
/// special or non-printable characters in it.
virtual void printSymbolName(StringRef symbolRef);
/// Print a handle to the given dialect resource.
virtual void printResourceHandle(const AsmDialectResourceHandle &resource);
/// Print an optional arrow followed by a type list.
template <typename TypeRange>
void printOptionalArrowTypeList(TypeRange &&types) {
if (types.begin() != types.end())
printArrowTypeList(types);
}
template <typename TypeRange>
void printArrowTypeList(TypeRange &&types) {
auto &os = getStream() << " -> ";
bool wrapped = !llvm::hasSingleElement(types) ||
llvm::isa<FunctionType>((*types.begin()));
if (wrapped)
os << '(';
llvm::interleaveComma(types, *this);
if (wrapped)
os << ')';
}
/// Print the two given type ranges in a functional form.
template <typename InputRangeT, typename ResultRangeT>
void printFunctionalType(InputRangeT &&inputs, ResultRangeT &&results) {
auto &os = getStream();
os << '(';
llvm::interleaveComma(inputs, *this);
os << ')';
printArrowTypeList(results);
}
void printDimensionList(ArrayRef<int64_t> shape);
/// Class used to automatically end a cyclic region on destruction.
class CyclicPrintReset {
public:
explicit CyclicPrintReset(AsmPrinter *printer) : printer(printer) {}
~CyclicPrintReset() {
if (printer)
printer->popCyclicPrinting();
}
CyclicPrintReset(const CyclicPrintReset &) = delete;
CyclicPrintReset &operator=(const CyclicPrintReset &) = delete;
CyclicPrintReset(CyclicPrintReset &&rhs)
: printer(std::exchange(rhs.printer, nullptr)) {}
CyclicPrintReset &operator=(CyclicPrintReset &&rhs) {
printer = std::exchange(rhs.printer, nullptr);
return *this;
}
private:
AsmPrinter *printer;
};
/// Attempts to start a cyclic printing region for `attrOrType`.
/// A cyclic printing region starts with this call and ends with the
/// destruction of the returned `CyclicPrintReset`. During this time,
/// calling `tryStartCyclicPrint` with the same attribute in any printer
/// will lead to returning failure.
///
/// This makes it possible to break infinite recursions when trying to print
/// cyclic attributes or types by printing only immutable parameters if nested
/// within itself.
template <class AttrOrTypeT>
FailureOr<CyclicPrintReset> tryStartCyclicPrint(AttrOrTypeT attrOrType) {
static_assert(
std::is_base_of_v<AttributeTrait::IsMutable<AttrOrTypeT>,
AttrOrTypeT> ||
std::is_base_of_v<TypeTrait::IsMutable<AttrOrTypeT>, AttrOrTypeT>,
"Only mutable attributes or types can be cyclic");
if (failed(pushCyclicPrinting(attrOrType.getAsOpaquePointer())))
return failure();
return CyclicPrintReset(this);
}
protected:
/// Initialize the printer with no internal implementation. In this case, all
/// virtual methods of this class must be overriden.
AsmPrinter() = default;
/// Pushes a new attribute or type in the form of a type erased pointer
/// into an internal set.
/// Returns success if the type or attribute was inserted in the set or
/// failure if it was already contained.
virtual LogicalResult pushCyclicPrinting(const void *opaquePointer);
/// Removes the element that was last inserted with a successful call to
/// `pushCyclicPrinting`. There must be exactly one `popCyclicPrinting` call
/// in reverse order of all successful `pushCyclicPrinting`.
virtual void popCyclicPrinting();
private:
AsmPrinter(const AsmPrinter &) = delete;
void operator=(const AsmPrinter &) = delete;
/// The internal implementation of the printer.
Impl *impl{nullptr};
};
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, Type type) {
p.printType(type);
return p;
}
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, Attribute attr) {
p.printAttribute(attr);
return p;
}
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, const APFloat &value) {
p.printFloat(value);
return p;
}
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, float value) {
return p << APFloat(value);
}
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, double value) {
return p << APFloat(value);
}
// Support printing anything that isn't convertible to one of the other
// streamable types, even if it isn't exactly one of them. For example, we want
// to print FunctionType with the Type version above, not have it match this.
template <typename AsmPrinterT, typename T,
std::enable_if_t<!std::is_convertible<T &, Value &>::value &&
!std::is_convertible<T &, Type &>::value &&
!std::is_convertible<T &, Attribute &>::value &&
!std::is_convertible<T &, ValueRange>::value &&
!std::is_convertible<T &, APFloat &>::value &&
!llvm::is_one_of<T, bool, float, double>::value,
T> * = nullptr>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, const T &other) {
p.getStream() << other;
return p;
}
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, bool value) {
return p << (value ? StringRef("true") : "false");
}
template <typename AsmPrinterT, typename ValueRangeT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, const ValueTypeRange<ValueRangeT> &types) {
llvm::interleaveComma(types, p);
return p;
}
template <typename AsmPrinterT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, const TypeRange &types) {
llvm::interleaveComma(types, p);
return p;
}
// Prevent matching the TypeRange version above for ValueRange
// printing through base AsmPrinter. This is needed so that the
// ValueRange printing behaviour does not change from printing
// the SSA values to printing the types for the operands when
// using AsmPrinter instead of OpAsmPrinter.
template <typename AsmPrinterT, typename T>
inline std::enable_if_t<std::is_same<AsmPrinter, AsmPrinterT>::value &&
std::is_convertible<T &, ValueRange>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, const T &other) = delete;
template <typename AsmPrinterT, typename ElementT>
inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
AsmPrinterT &>
operator<<(AsmPrinterT &p, ArrayRef<ElementT> types) {
llvm::interleaveComma(types, p);
return p;
}
//===----------------------------------------------------------------------===//
// OpAsmPrinter
//===----------------------------------------------------------------------===//
/// This is a pure-virtual base class that exposes the asmprinter hooks
/// necessary to implement a custom print() method.
class OpAsmPrinter : public AsmPrinter {
public:
using AsmPrinter::AsmPrinter;
~OpAsmPrinter() override;
/// Print a loc(...) specifier if printing debug info is enabled.
virtual void printOptionalLocationSpecifier(Location loc) = 0;
/// Print a newline and indent the printer to the start of the current
/// operation.
virtual void printNewline() = 0;
/// Increase indentation.
virtual void increaseIndent() = 0;
/// Decrease indentation.
virtual void decreaseIndent() = 0;
/// Print a block argument in the usual format of:
/// %ssaName : type {attr1=42} loc("here")
/// where location printing is controlled by the standard internal option.
/// You may pass omitType=true to not print a type, and pass an empty
/// attribute list if you don't care for attributes.
virtual void printRegionArgument(BlockArgument arg,
ArrayRef<NamedAttribute> argAttrs = {},
bool omitType = false) = 0;
/// Print implementations for various things an operation contains.
virtual void printOperand(Value value) = 0;
virtual void printOperand(Value value, raw_ostream &os) = 0;
/// Print a comma separated list of operands.
template <typename ContainerType>
void printOperands(const ContainerType &container) {
printOperands(container.begin(), container.end());
}
/// Print a comma separated list of operands.
template <typename IteratorType>
void printOperands(IteratorType it, IteratorType end) {
llvm::interleaveComma(llvm::make_range(it, end), getStream(),
[this](Value value) { printOperand(value); });
}
/// Print the given successor.
virtual void printSuccessor(Block *successor) = 0;
/// Print the successor and its operands.
virtual void printSuccessorAndUseList(Block *successor,
ValueRange succOperands) = 0;
/// If the specified operation has attributes, print out an attribute
/// dictionary with their values. elidedAttrs allows the client to ignore
/// specific well known attributes, commonly used if the attribute value is
/// printed some other way (like as a fixed operand).
virtual void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
ArrayRef<StringRef> elidedAttrs = {}) = 0;
/// If the specified operation has attributes, print out an attribute
/// dictionary prefixed with 'attributes'.
virtual void
printOptionalAttrDictWithKeyword(ArrayRef<NamedAttribute> attrs,
ArrayRef<StringRef> elidedAttrs = {}) = 0;
/// Prints the entire operation with the custom assembly form, if available,
/// or the generic assembly form, otherwise.
virtual void printCustomOrGenericOp(Operation *op) = 0;
/// Print the entire operation with the default generic assembly form.
/// If `printOpName` is true, then the operation name is printed (the default)
/// otherwise it is omitted and the print will start with the operand list.
virtual void printGenericOp(Operation *op, bool printOpName = true) = 0;
/// Prints a region.
/// If 'printEntryBlockArgs' is false, the arguments of the
/// block are not printed. If 'printBlockTerminator' is false, the terminator
/// operation of the block is not printed. If printEmptyBlock is true, then
/// the block header is printed even if the block is empty.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs = true,
bool printBlockTerminators = true,
bool printEmptyBlock = false) = 0;
/// Renumber the arguments for the specified region to the same names as the
/// SSA values in namesToUse. This may only be used for IsolatedFromAbove
/// operations. If any entry in namesToUse is null, the corresponding
/// argument name is left alone.
virtual void shadowRegionArgs(Region ®ion, ValueRange namesToUse) = 0;
/// Prints an affine map of SSA ids, where SSA id names are used in place
/// of dims/symbols.
/// Operand values must come from single-result sources, and be valid
/// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr,
ValueRange operands) = 0;
/// Prints an affine expression of SSA ids with SSA id names used instead of
/// dims and symbols.
/// Operand values must come from single-result sources, and be valid
/// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands,
ValueRange symOperands) = 0;
/// Print the complete type of an operation in functional form.
void printFunctionalType(Operation *op);
using AsmPrinter::printFunctionalType;
};
// Make the implementations convenient to use.
inline OpAsmPrinter &operator<<(OpAsmPrinter &p, Value value) {
p.printOperand(value);
return p;
}
template <typename T,
std::enable_if_t<std::is_convertible<T &, ValueRange>::value &&
!std::is_convertible<T &, Value &>::value,
T> * = nullptr>
inline OpAsmPrinter &operator<<(OpAsmPrinter &p, const T &values) {
p.printOperands(values);
return p;
}
inline OpAsmPrinter &operator<<(OpAsmPrinter &p, Block *value) {
p.printSuccessor(value);
return p;
}
//===----------------------------------------------------------------------===//
// AsmParser
//===----------------------------------------------------------------------===//
/// This base class exposes generic asm parser hooks, usable across the various
/// derived parsers.
class AsmParser {
public:
AsmParser() = default;
virtual ~AsmParser();
MLIRContext *getContext() const;
/// Return the location of the original name token.
virtual SMLoc getNameLoc() const = 0;
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
/// Emit a diagnostic at the specified location and return failure.
virtual InFlightDiagnostic emitError(SMLoc loc,
const Twine &message = {}) = 0;
/// Return a builder which provides useful access to MLIRContext, global
/// objects like types and attributes.
virtual Builder &getBuilder() const = 0;
/// Get the location of the next token and store it into the argument. This
/// always succeeds.
virtual SMLoc getCurrentLocation() = 0;
ParseResult getCurrentLocation(SMLoc *loc) {
*loc = getCurrentLocation();
return success();
}
/// Re-encode the given source location as an MLIR location and return it.
/// Note: This method should only be used when a `Location` is necessary, as
/// the encoding process is not efficient.
virtual Location getEncodedSourceLoc(SMLoc loc) = 0;
//===--------------------------------------------------------------------===//
// Token Parsing
//===--------------------------------------------------------------------===//
/// Parse a '->' token.
virtual ParseResult parseArrow() = 0;
/// Parse a '->' token if present
virtual ParseResult parseOptionalArrow() = 0;
/// Parse a `{` token.
virtual ParseResult parseLBrace() = 0;
/// Parse a `{` token if present.
virtual ParseResult parseOptionalLBrace() = 0;
/// Parse a `}` token.
virtual ParseResult parseRBrace() = 0;
/// Parse a `}` token if present.
virtual ParseResult parseOptionalRBrace() = 0;
/// Parse a `:` token.
virtual ParseResult parseColon() = 0;
/// Parse a `:` token if present.
virtual ParseResult parseOptionalColon() = 0;
/// Parse a `,` token.
virtual ParseResult parseComma() = 0;
/// Parse a `,` token if present.
virtual ParseResult parseOptionalComma() = 0;
/// Parse a `=` token.
virtual ParseResult parseEqual() = 0;
/// Parse a `=` token if present.
virtual ParseResult parseOptionalEqual() = 0;
/// Parse a '<' token.
virtual ParseResult parseLess() = 0;
/// Parse a '<' token if present.
virtual ParseResult parseOptionalLess() = 0;
/// Parse a '>' token.
virtual ParseResult parseGreater() = 0;
/// Parse a '>' token if present.
virtual ParseResult parseOptionalGreater() = 0;
/// Parse a '?' token.
virtual ParseResult parseQuestion() = 0;
/// Parse a '?' token if present.
virtual ParseResult parseOptionalQuestion() = 0;
/// Parse a '+' token.
virtual ParseResult parsePlus() = 0;
/// Parse a '+' token if present.
virtual ParseResult parseOptionalPlus() = 0;
/// Parse a '*' token.
virtual ParseResult parseStar() = 0;
/// Parse a '*' token if present.
virtual ParseResult parseOptionalStar() = 0;
/// Parse a '|' token.
virtual ParseResult parseVerticalBar() = 0;
/// Parse a '|' token if present.
virtual ParseResult parseOptionalVerticalBar() = 0;
/// Parse a quoted string token.
ParseResult parseString(std::string *string) {
auto loc = getCurrentLocation();
if (parseOptionalString(string))
return emitError(loc, "expected string");
return success();
}
/// Parse a quoted string token if present.
virtual ParseResult parseOptionalString(std::string *string) = 0;
/// Parses a Base64 encoded string of bytes.
virtual ParseResult parseBase64Bytes(std::vector<char> *bytes) = 0;
/// Parse a `(` token.
virtual ParseResult parseLParen() = 0;
/// Parse a `(` token if present.
virtual ParseResult parseOptionalLParen() = 0;
/// Parse a `)` token.
virtual ParseResult parseRParen() = 0;
/// Parse a `)` token if present.
virtual ParseResult parseOptionalRParen() = 0;
/// Parse a `[` token.
virtual ParseResult parseLSquare() = 0;
/// Parse a `[` token if present.
virtual ParseResult parseOptionalLSquare() = 0;
/// Parse a `]` token.
virtual ParseResult parseRSquare() = 0;
/// Parse a `]` token if present.
virtual ParseResult parseOptionalRSquare() = 0;
/// Parse a `...` token.
virtual ParseResult parseEllipsis() = 0;
/// Parse a `...` token if present;
virtual ParseResult parseOptionalEllipsis() = 0;
/// Parse a floating point value from the stream.
virtual ParseResult parseFloat(double &result) = 0;
/// Parse a floating point value into APFloat from the stream.
virtual ParseResult parseFloat(const llvm::fltSemantics &semantics,
APFloat &result) = 0;
/// Parse an integer value from the stream.
template <typename IntT>
ParseResult parseInteger(IntT &result) {
auto loc = getCurrentLocation();
OptionalParseResult parseResult = parseOptionalInteger(result);
if (!parseResult.has_value())
return emitError(loc, "expected integer value");
return *parseResult;
}
/// Parse an optional integer value from the stream.
virtual OptionalParseResult parseOptionalInteger(APInt &result) = 0;
template <typename IntT>
OptionalParseResult parseOptionalInteger(IntT &result) {
auto loc = getCurrentLocation();
// Parse the unsigned variant.
APInt uintResult;
OptionalParseResult parseResult = parseOptionalInteger(uintResult);
if (!parseResult.has_value() || failed(*parseResult))
return parseResult;
// Try to convert to the provided integer type. sextOrTrunc is correct even
// for unsigned types because parseOptionalInteger ensures the sign bit is
// zero for non-negated integers.
result =
(IntT)uintResult.sextOrTrunc(sizeof(IntT) * CHAR_BIT).getLimitedValue();
if (APInt(uintResult.getBitWidth(), result) != uintResult)
return emitError(loc, "integer value too large");
return success();
}
/// These are the supported delimiters around operand lists and region
/// argument lists, used by parseOperandList.
enum class Delimiter {
/// Zero or more operands with no delimiters.
None,
/// Parens surrounding zero or more operands.
Paren,
/// Square brackets surrounding zero or more operands.
Square,
/// <> brackets surrounding zero or more operands.
LessGreater,
/// {} brackets surrounding zero or more operands.
Braces,
/// Parens supporting zero or more operands, or nothing.
OptionalParen,
/// Square brackets supporting zero or more ops, or nothing.
OptionalSquare,
/// <> brackets supporting zero or more ops, or nothing.
OptionalLessGreater,
/// {} brackets surrounding zero or more operands, or nothing.
OptionalBraces,
};
/// Parse a list of comma-separated items with an optional delimiter. If a
/// delimiter is provided, then an empty list is allowed. If not, then at
/// least one element will be parsed.
///
/// contextMessage is an optional message appended to "expected '('" sorts of
/// diagnostics when parsing the delimeters.
virtual ParseResult
parseCommaSeparatedList(Delimiter delimiter,
function_ref<ParseResult()> parseElementFn,
StringRef contextMessage = StringRef()) = 0;
/// Parse a comma separated list of elements that must have at least one entry
/// in it.
ParseResult
parseCommaSeparatedList(function_ref<ParseResult()> parseElementFn) {
return parseCommaSeparatedList(Delimiter::None, parseElementFn);
}
//===--------------------------------------------------------------------===//
// Keyword Parsing
//===--------------------------------------------------------------------===//
/// This class represents a StringSwitch like class that is useful for parsing
/// expected keywords. On construction, unless a non-empty keyword is
/// provided, it invokes `parseKeyword` and processes each of the provided
/// cases statements until a match is hit. The provided `ResultT` must be
/// assignable from `failure()`.
template <typename ResultT = ParseResult>
class KeywordSwitch {
public:
KeywordSwitch(AsmParser &parser, StringRef *keyword = nullptr)
: parser(parser), loc(parser.getCurrentLocation()) {
if (keyword && !keyword->empty())
this->keyword = *keyword;
else if (failed(parser.parseKeywordOrCompletion(&this->keyword)))
result = failure();
}
/// Case that uses the provided value when true.
KeywordSwitch &Case(StringLiteral str, ResultT value) {
return Case(str, [&](StringRef, SMLoc) { return std::move(value); });
}
KeywordSwitch &Default(ResultT value) {
return Default([&](StringRef, SMLoc) { return std::move(value); });
}
/// Case that invokes the provided functor when true. The parameters passed
/// to the functor are the keyword, and the location of the keyword (in case
/// any errors need to be emitted).
template <typename FnT>
std::enable_if_t<!std::is_convertible<FnT, ResultT>::value, KeywordSwitch &>
Case(StringLiteral str, FnT &&fn) {
if (result)
return *this;
// If the word was empty, record this as a completion.
if (keyword.empty())
parser.codeCompleteExpectedTokens(str);
else if (keyword == str)
result.emplace(std::move(fn(keyword, loc)));
return *this;
}
template <typename FnT>
std::enable_if_t<!std::is_convertible<FnT, ResultT>::value, KeywordSwitch &>
Default(FnT &&fn) {
if (!result)
result.emplace(fn(keyword, loc));
return *this;
}
/// Returns true if this switch has a value yet.
bool hasValue() const { return result.has_value(); }
/// Return the result of the switch.
[[nodiscard]] operator ResultT() {
if (!result)
return parser.emitError(loc, "unexpected keyword: ") << keyword;
return std::move(*result);
}
private:
/// The parser used to construct this switch.
AsmParser &parser;
/// The location of the keyword, used to emit errors as necessary.
SMLoc loc;
/// The parsed keyword itself.
StringRef keyword;
/// The result of the switch statement or std::nullopt if currently unknown.
std::optional<ResultT> result;
};
/// Parse a given keyword.
ParseResult parseKeyword(StringRef keyword) {
return parseKeyword(keyword, "");
}
virtual ParseResult parseKeyword(StringRef keyword, const Twine &msg) = 0;
/// Parse a keyword into 'keyword'.
ParseResult parseKeyword(StringRef *keyword) {
auto loc = getCurrentLocation();
if (parseOptionalKeyword(keyword))
return emitError(loc, "expected valid keyword");
return success();
}
/// Parse the given keyword if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword) = 0;
/// Parse a keyword, if present, into 'keyword'.
virtual ParseResult parseOptionalKeyword(StringRef *keyword) = 0;
/// Parse a keyword, if present, and if one of the 'allowedValues',
/// into 'keyword'
virtual ParseResult
parseOptionalKeyword(StringRef *keyword,
ArrayRef<StringRef> allowedValues) = 0;
/// Parse a keyword or a quoted string.
ParseResult parseKeywordOrString(std::string *result) {
if (failed(parseOptionalKeywordOrString(result)))
return emitError(getCurrentLocation())
<< "expected valid keyword or string";
return success();
}
/// Parse an optional keyword or string.
virtual ParseResult parseOptionalKeywordOrString(std::string *result) = 0;
//===--------------------------------------------------------------------===//
// Attribute/Type Parsing
//===--------------------------------------------------------------------===//
/// Invoke the `getChecked` method of the given Attribute or Type class, using
/// the provided location to emit errors in the case of failure. Note that
/// unlike `OpBuilder::getType`, this method does not implicitly insert a
/// context parameter.
template <typename T, typename... ParamsT>
auto getChecked(SMLoc loc, ParamsT &&...params) {
return T::getChecked([&] { return emitError(loc); },
std::forward<ParamsT>(params)...);
}
/// A variant of `getChecked` that uses the result of `getNameLoc` to emit
/// errors.
template <typename T, typename... ParamsT>
auto getChecked(ParamsT &&...params) {
return T::getChecked([&] { return emitError(getNameLoc()); },
std::forward<ParamsT>(params)...);
}
//===--------------------------------------------------------------------===//
// Attribute Parsing
//===--------------------------------------------------------------------===//
/// Parse an arbitrary attribute of a given type and return it in result.
virtual ParseResult parseAttribute(Attribute &result, Type type = {}) = 0;
/// Parse a custom attribute with the provided callback, unless the next
/// token is `#`, in which case the generic parser is invoked.
virtual ParseResult parseCustomAttributeWithFallback(
Attribute &result, Type type,
function_ref<ParseResult(Attribute &result, Type type)>
parseAttribute) = 0;
/// Parse an attribute of a specific kind and type.
template <typename AttrType>
ParseResult parseAttribute(AttrType &result, Type type = {}) {
SMLoc loc = getCurrentLocation();
// Parse any kind of attribute.
Attribute attr;
if (parseAttribute(attr, type))
return failure();
// Check for the right kind of attribute.
if (!(result = llvm::dyn_cast<AttrType>(attr)))
return emitError(loc, "invalid kind of attribute specified");
return success();
}
/// Parse an arbitrary attribute and return it in result. This also adds the
/// attribute to the specified attribute list with the specified name.
ParseResult parseAttribute(Attribute &result, StringRef attrName,
NamedAttrList &attrs) {
return parseAttribute(result, Type(), attrName, attrs);
}
/// Parse an attribute of a specific kind and type.
template <typename AttrType>
ParseResult parseAttribute(AttrType &result, StringRef attrName,
NamedAttrList &attrs) {
return parseAttribute(result, Type(), attrName, attrs);
}
/// Parse an arbitrary attribute of a given type and populate it in `result`.
/// This also adds the attribute to the specified attribute list with the
/// specified name.
template <typename AttrType>
ParseResult parseAttribute(AttrType &result, Type type, StringRef attrName,
NamedAttrList &attrs) {
SMLoc loc = getCurrentLocation();
// Parse any kind of attribute.
Attribute attr;
if (parseAttribute(attr, type))
return failure();
// Check for the right kind of attribute.
result = llvm::dyn_cast<AttrType>(attr);
if (!result)
return emitError(loc, "invalid kind of attribute specified");
attrs.append(attrName, result);
return success();
}
/// Trait to check if `AttrType` provides a `parse` method.
template <typename AttrType>
using has_parse_method = decltype(AttrType::parse(std::declval<AsmParser &>(),
std::declval<Type>()));
template <typename AttrType>
using detect_has_parse_method = llvm::is_detected<has_parse_method, AttrType>;
/// Parse a custom attribute of a given type unless the next token is `#`, in
/// which case the generic parser is invoked. The parsed attribute is
/// populated in `result` and also added to the specified attribute list with
/// the specified name.
template <typename AttrType>
std::enable_if_t<detect_has_parse_method<AttrType>::value, ParseResult>
parseCustomAttributeWithFallback(AttrType &result, Type type,
StringRef attrName, NamedAttrList &attrs) {
SMLoc loc = getCurrentLocation();
// Parse any kind of attribute.
Attribute attr;
if (parseCustomAttributeWithFallback(
attr, type, [&](Attribute &result, Type type) -> ParseResult {