MLIR 24.0.0git
OpImplementation.h
Go to the documentation of this file.
1//===- OpImplementation.h - Classes for implementing Op types ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This classes used by the implementation details of Op types.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_OPIMPLEMENTATION_H
14#define MLIR_IR_OPIMPLEMENTATION_H
15
19#include "llvm/ADT/Twine.h"
20#include "llvm/Support/Compiler.h"
21#include "llvm/Support/SMLoc.h"
22#include <cstddef>
23#include <optional>
24
25namespace {
26// reference https://stackoverflow.com/a/16000226
27template <typename T, typename = void>
28struct HasStaticName : std::false_type {};
29
30template <typename T>
31struct HasStaticName<T,
32 typename std::enable_if<
33 std::is_same<::llvm::StringLiteral,
34 std::decay_t<decltype(T::name)>>::value,
35 void>::type> : std::true_type {};
36} // namespace
37
38namespace mlir {
41class Builder;
42
43//===----------------------------------------------------------------------===//
44// AsmDialectResourceHandle
45//===----------------------------------------------------------------------===//
46
47/// This class represents an opaque handle to a dialect resource entry.
49public:
51 AsmDialectResourceHandle(void *resource, TypeID resourceID, Dialect *dialect)
52 : resource(resource), opaqueID(resourceID), dialect(dialect) {}
53 bool operator==(const AsmDialectResourceHandle &other) const {
54 return resource == other.resource;
55 }
56
57 /// Return an opaque pointer to the referenced resource.
58 void *getResource() const { return resource; }
59
60 /// Return the type ID of the resource.
61 TypeID getTypeID() const { return opaqueID; }
62
63 /// Return the dialect that owns the resource.
64 Dialect *getDialect() const { return dialect; }
65
66private:
67 /// The opaque handle to the dialect resource.
68 void *resource = nullptr;
69 /// The type of the resource referenced.
70 TypeID opaqueID;
71 /// The dialect owning the given resource.
72 Dialect *dialect = nullptr;
73};
74
75/// This class represents a CRTP base class for dialect resource handles. It
76/// abstracts away various utilities necessary for defined derived resource
77/// handles.
78template <typename DerivedT, typename ResourceT, typename DialectT>
80public:
81 using Dialect = DialectT;
82
83 /// Construct a handle from a pointer to the resource. The given pointer
84 /// should be guaranteed to live beyond the life of this handle.
85 AsmDialectResourceHandleBase(ResourceT *resource, DialectT *dialect)
86 : AsmDialectResourceHandle(resource, TypeID::get<DerivedT>(), dialect) {}
88 : AsmDialectResourceHandle(handle) {
89 assert(handle.getTypeID() == TypeID::get<DerivedT>());
90 }
91
92 /// Return the resource referenced by this handle.
93 ResourceT *getResource() {
94 return static_cast<ResourceT *>(AsmDialectResourceHandle::getResource());
95 }
96 const ResourceT *getResource() const {
97 return const_cast<AsmDialectResourceHandleBase *>(this)->getResource();
98 }
99
100 /// Return the dialect that owns the resource.
101 DialectT *getDialect() const {
102 return static_cast<DialectT *>(AsmDialectResourceHandle::getDialect());
103 }
104
105 /// Support llvm style casting.
106 static bool classof(const AsmDialectResourceHandle *handle) {
107 return handle->getTypeID() == TypeID::get<DerivedT>();
108 }
109};
110
111inline llvm::hash_code hash_value(const AsmDialectResourceHandle &param) {
112 return llvm::hash_value(param.getResource());
113}
114
115//===----------------------------------------------------------------------===//
116// AsmPrinter
117//===----------------------------------------------------------------------===//
118
119/// This base class exposes generic asm printer hooks, usable across the various
120/// derived printers.
122public:
123 /// This class contains the internal default implementation of the base
124 /// printer methods.
125 class Impl;
126
127 /// Initialize the printer with the given internal implementation.
129 virtual ~AsmPrinter();
130
131 /// Return the raw output stream used by this printer.
132 virtual raw_ostream &getStream() const;
133
134 /// Print a newline and indent the printer to the start of the current
135 /// operation/attribute/type.
136 /// Note: For attributes and types this method should only be used in
137 /// custom dialects. Usage in upstream MLIR dialects is currently disallowed.
138 virtual void printNewline();
139
140 /// Increase indentation.
141 virtual void increaseIndent();
142
143 /// Decrease indentation.
144 virtual void decreaseIndent();
145
146 /// Print the given floating point value in a stabilized form that can be
147 /// roundtripped through the IR. This is the companion to the 'parseFloat'
148 /// hook on the AsmParser.
149 virtual void printFloat(const APFloat &value);
150
151 /// Print the given integer value. This is useful to force a uint8_t/int8_t to
152 /// be printed as an integer instead of a char.
153 template <typename IntT,
154 typename = std::enable_if_t<std::is_integral_v<IntT>>>
155 void printInteger(IntT value) {
156 // Handle int8_t/uint8_t specially to avoid printing as char
157 if constexpr (std::is_same_v<IntT, int8_t> ||
158 std::is_same_v<IntT, uint8_t>) {
159 getStream() << static_cast<int>(value);
160 } else {
161 getStream() << value;
162 }
163 }
164
165 virtual void printType(Type type);
166 virtual void printAttribute(Attribute attr);
167
168 /// Trait to check if `AttrType` provides a `print` method.
169 template <typename AttrOrType>
171 decltype(std::declval<AttrOrType>().print(std::declval<AsmPrinter &>()));
172 template <typename AttrOrType>
174 llvm::is_detected<has_print_method, AttrOrType>;
175
176 /// Print the provided attribute in the context of an operation custom
177 /// printer/parser: this will invoke directly the print method on the
178 /// attribute class and skip the `#dialect.mnemonic` prefix in most cases.
179 template <typename AttrOrType,
180 std::enable_if_t<detect_has_print_method<AttrOrType>::value>
181 *sfinae = nullptr>
182 void printStrippedAttrOrType(AttrOrType attrOrType) {
183 if (succeeded(printAlias(attrOrType)))
184 return;
185
186 raw_ostream &os = getStream();
187 uint64_t posPrior = os.tell();
188 attrOrType.print(*this);
189 if (posPrior != os.tell())
190 return;
191
192 // Fallback to printing with prefix if the above failed to write anything
193 // to the output stream.
194 *this << attrOrType;
195 }
196
197 /// Print the provided array of attributes or types in the context of an
198 /// operation custom printer/parser: this will invoke directly the print
199 /// method on the attribute class and skip the `#dialect.mnemonic` prefix in
200 /// most cases.
201 template <typename AttrOrType,
202 std::enable_if_t<detect_has_print_method<AttrOrType>::value>
203 *sfinae = nullptr>
205 llvm::interleaveComma(
206 attrOrTypes, getStream(),
207 [this](AttrOrType attrOrType) { printStrippedAttrOrType(attrOrType); });
208 }
209
210 /// SFINAE for printing the provided attribute in the context of an operation
211 /// custom printer in the case where the attribute does not define a print
212 /// method.
213 template <typename AttrOrType,
214 std::enable_if_t<!detect_has_print_method<AttrOrType>::value>
215 *sfinae = nullptr>
216 void printStrippedAttrOrType(AttrOrType attrOrType) {
217 *this << attrOrType;
218 }
219
220 /// Print a plain `char` parameter as a bare keyword for identifier characters
221 /// (e.g. `A`) or as a quoted+escaped string for everything else, so that all
222 /// 256 byte values round-trip correctly.
223 void printStrippedAttrOrType(char value) {
224 printKeywordOrString(StringRef(&value, 1));
225 }
226
227 /// Print an array of plain `char` parameters element-wise with the `char`
228 /// overload above, matching the element-wise `FieldParser<char>` used to
229 /// parse them.
231 llvm::interleaveComma(values, getStream(), [this](char value) {
233 });
234 }
235
236 /// Print a present optional integer parameter through the overloads for its
237 /// underlying type, mirroring `FieldParser<std::optional<IntT>>`.
238 template <typename IntT,
239 std::enable_if_t<std::is_integral_v<IntT> &&
240 !std::is_same_v<IntT, bool>> *sfinae = nullptr>
241 void printStrippedAttrOrType(std::optional<IntT> value) {
242 if (value)
244 }
245
246 /// Print the given attribute without its type. The corresponding parser must
247 /// provide a valid type for the attribute.
248 virtual void printAttributeWithoutType(Attribute attr);
249
250 /// Print the given named attribute.
251 virtual void printNamedAttribute(NamedAttribute attr);
252
253 /// Print the alias for the given attribute, return failure if no alias could
254 /// be printed.
255 virtual LogicalResult printAlias(Attribute attr);
256
257 /// Print the alias for the given type, return failure if no alias could
258 /// be printed.
259 virtual LogicalResult printAlias(Type type);
260
261 /// Print the given string as a keyword, or a quoted and escaped string if it
262 /// has any special or non-printable characters in it.
263 virtual void printKeywordOrString(StringRef keyword);
264
265 /// Print the given string as a quoted string, escaping any special or
266 /// non-printable characters in it.
267 virtual void printString(StringRef string);
268
269 /// Print the given string as a symbol reference, i.e. a form representable by
270 /// a SymbolRefAttr. A symbol reference is represented as a string prefixed
271 /// with '@'. The reference is surrounded with ""'s and escaped if it has any
272 /// special or non-printable characters in it.
273 virtual void printSymbolName(StringRef symbolRef);
274
275 /// Print a handle to the given dialect resource. The handle key is quoted and
276 /// escaped if it has any special or non-printable characters in it.
277 virtual void printResourceHandle(const AsmDialectResourceHandle &resource);
278
279 /// Print an optional arrow followed by a type list.
280 template <typename TypeRange>
282 if (types.begin() != types.end())
283 printArrowTypeList(types);
284 }
285 template <typename TypeRange>
287 auto &os = getStream() << " -> ";
288
289 bool wrapped = !llvm::hasSingleElement(types) ||
290 llvm::isa<FunctionType>((*types.begin()));
291 if (wrapped)
292 os << '(';
293 llvm::interleaveComma(types, *this);
294 if (wrapped)
295 os << ')';
296 }
297
298 /// Print the two given type ranges in a functional form.
299 template <typename InputRangeT, typename ResultRangeT>
300 void printFunctionalType(InputRangeT &&inputs, ResultRangeT &&results) {
301 auto &os = getStream();
302 os << '(';
303 llvm::interleaveComma(inputs, *this);
304 os << ')';
305 printArrowTypeList(results);
306 }
307
309
310 /// Class used to automatically end a cyclic region on destruction.
312 public:
313 explicit CyclicPrintReset(AsmPrinter *printer) : printer(printer) {}
314
316 if (printer)
317 printer->popCyclicPrinting();
318 }
319
321
323
325 : printer(std::exchange(rhs.printer, nullptr)) {}
326
328 printer = std::exchange(rhs.printer, nullptr);
329 return *this;
330 }
331
332 private:
333 AsmPrinter *printer;
334 };
335
336 /// Attempts to start a cyclic printing region for `attrOrType`.
337 /// A cyclic printing region starts with this call and ends with the
338 /// destruction of the returned `CyclicPrintReset`. During this time,
339 /// calling `tryStartCyclicPrint` with the same attribute in any printer
340 /// will lead to returning failure.
341 ///
342 /// This makes it possible to break infinite recursions when trying to print
343 /// cyclic attributes or types by printing only immutable parameters if nested
344 /// within itself.
345 template <class AttrOrTypeT>
346 FailureOr<CyclicPrintReset> tryStartCyclicPrint(AttrOrTypeT attrOrType) {
347 static_assert(
348 std::is_base_of_v<AttributeTrait::IsMutable<AttrOrTypeT>,
349 AttrOrTypeT> ||
350 std::is_base_of_v<TypeTrait::IsMutable<AttrOrTypeT>, AttrOrTypeT>,
351 "Only mutable attributes or types can be cyclic");
352 if (failed(pushCyclicPrinting(attrOrType.getAsOpaquePointer())))
353 return failure();
354 return CyclicPrintReset(this);
355 }
356
357protected:
358 /// Initialize the printer with no internal implementation. In this case, all
359 /// virtual methods of this class must be overriden.
360 AsmPrinter() = default;
361
362 /// Pushes a new attribute or type in the form of a type erased pointer
363 /// into an internal set.
364 /// Returns success if the type or attribute was inserted in the set or
365 /// failure if it was already contained.
366 virtual LogicalResult pushCyclicPrinting(const void *opaquePointer);
367
368 /// Removes the element that was last inserted with a successful call to
369 /// `pushCyclicPrinting`. There must be exactly one `popCyclicPrinting` call
370 /// in reverse order of all successful `pushCyclicPrinting`.
371 virtual void popCyclicPrinting();
372
373private:
374 AsmPrinter(const AsmPrinter &) = delete;
375 void operator=(const AsmPrinter &) = delete;
376
377 /// The internal implementation of the printer.
378 Impl *impl{nullptr};
379};
380
381template <typename AsmPrinterT,
382 typename =
383 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
384inline AsmPrinterT &operator<<(AsmPrinterT &p, Type type) {
385 p.printType(type);
386 return p;
387}
388
389template <typename AsmPrinterT,
390 typename =
391 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
392inline AsmPrinterT &operator<<(AsmPrinterT &p, Attribute attr) {
393 p.printAttribute(attr);
394 return p;
395}
396
397template <typename AsmPrinterT,
398 typename =
399 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
400inline AsmPrinterT &operator<<(AsmPrinterT &p, const APFloat &value) {
401 p.printFloat(value);
402 return p;
403}
404template <typename AsmPrinterT,
405 typename =
406 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
407inline AsmPrinterT &operator<<(AsmPrinterT &p, float value) {
408 return p << APFloat(value);
409}
410template <typename AsmPrinterT,
411 typename =
412 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
413inline AsmPrinterT &operator<<(AsmPrinterT &p, double value) {
414 return p << APFloat(value);
415}
416
417// Print `int8_t`/`uint8_t` numerically instead of reaching `raw_ostream`'s
418// character overloads. Plain `char` is still printed as a character.
419template <typename AsmPrinterT,
420 typename =
421 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
422inline AsmPrinterT &operator<<(AsmPrinterT &p, int8_t value) {
423 p.printInteger(value);
424 return p;
425}
426template <typename AsmPrinterT,
427 typename =
428 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
429inline AsmPrinterT &operator<<(AsmPrinterT &p, uint8_t value) {
430 p.printInteger(value);
431 return p;
432}
433
434// Support printing anything that isn't convertible to one of the other
435// streamable types, even if it isn't exactly one of them. For example, we want
436// to print FunctionType with the Type version above, not have it match this.
437template <typename AsmPrinterT, typename T,
438 std::enable_if_t<!std::is_convertible<T &, Value &>::value &&
439 !std::is_convertible<T &, Type &>::value &&
440 !std::is_convertible<T &, Attribute &>::value &&
441 !std::is_convertible<T &, ValueRange>::value &&
442 !std::is_convertible<T &, APFloat &>::value &&
443 !llvm::is_one_of<T, bool, float, double, int8_t,
444 uint8_t>::value,
445 T> * = nullptr,
446 typename =
447 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
448inline AsmPrinterT &operator<<(AsmPrinterT &p, const T &other) {
449 p.getStream() << other;
450 return p;
451}
452
453template <typename AsmPrinterT,
454 typename =
455 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
456inline AsmPrinterT &operator<<(AsmPrinterT &p, bool value) {
457 return p << (value ? StringRef("true") : "false");
458}
459
460template <typename AsmPrinterT, typename ValueRangeT,
461 typename =
462 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
463inline AsmPrinterT &operator<<(AsmPrinterT &p,
464 const ValueTypeRange<ValueRangeT> &types) {
465 llvm::interleaveComma(types, p);
466 return p;
467}
468
469template <typename AsmPrinterT,
470 typename =
471 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
472inline AsmPrinterT &operator<<(AsmPrinterT &p, const TypeRange &types) {
473 llvm::interleaveComma(types, p);
474 return p;
475}
476
477// Prevent matching the TypeRange version above for ValueRange
478// printing through base AsmPrinter. This is needed so that the
479// ValueRange printing behaviour does not change from printing
480// the SSA values to printing the types for the operands when
481// using AsmPrinter instead of OpAsmPrinter.
482template <
483 typename AsmPrinterT, typename T,
484 typename = std::enable_if_t<std::is_same<AsmPrinter, AsmPrinterT>::value &&
485 std::is_convertible<T &, ValueRange>::value>>
486inline AsmPrinterT &operator<<(AsmPrinterT &p, const T &other) = delete;
487
488template <typename AsmPrinterT, typename ElementT,
489 typename =
490 std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value>>
491inline AsmPrinterT &operator<<(AsmPrinterT &p, ArrayRef<ElementT> types) {
492 llvm::interleaveComma(types, p);
493 return p;
494}
495
496//===----------------------------------------------------------------------===//
497// OpAsmPrinter
498//===----------------------------------------------------------------------===//
499
500/// This is a pure-virtual base class that exposes the asmprinter hooks
501/// necessary to implement a custom print() method.
502class OpAsmPrinter : public AsmPrinter {
503public:
505 ~OpAsmPrinter() override;
506
507 /// Print a loc(...) specifier if printing debug info is enabled.
509
510 /// Print a block argument in the usual format of:
511 /// %ssaName : type {attr1=42} loc("here")
512 /// where location printing is controlled by the standard internal option.
513 /// You may pass omitType=true to not print a type, and pass an empty
514 /// attribute list if you don't care for attributes.
516 ArrayRef<NamedAttribute> argAttrs = {},
517 bool omitType = false) = 0;
518
519 /// Print implementations for various things an operation contains.
520 virtual void printOperand(Value value) = 0;
521 virtual void printOperand(Value value, raw_ostream &os) = 0;
522
523 /// Print a comma separated range of operation operands out of line to avoid
524 /// instantiating the range iteration in every generated operation printer.
525 void printOperands(OperandRange operands);
526
527 /// Print the types of a comma separated range of operation operands.
529
530 /// Print a comma separated list of operands.
531 template <typename ContainerType>
532 void printOperands(const ContainerType &container) {
533 printOperands(container.begin(), container.end());
534 }
535
536 /// Print a comma separated list of operands.
537 template <typename IteratorType>
538 void printOperands(IteratorType it, IteratorType end) {
539 llvm::interleaveComma(llvm::make_range(it, end), getStream(),
540 [this](Value value) { printOperand(value); });
541 }
542
543 /// Print the given successor.
544 virtual void printSuccessor(Block *successor) = 0;
545
546 /// Print the successor and its operands.
547 virtual void printSuccessorAndUseList(Block *successor,
548 ValueRange succOperands) = 0;
549
550 /// If the specified operation has attributes, print out an attribute
551 /// dictionary with their values. elidedAttrs allows the client to ignore
552 /// specific well known attributes, commonly used if the attribute value is
553 /// printed some other way (like as a fixed operand).
555 ArrayRef<StringRef> elidedAttrs = {}) = 0;
556
557 void printOptionalAttrDict(DictionaryAttr attrs,
558 ArrayRef<StringRef> elidedAttrs = {}) {
559 printOptionalAttrDict(attrs.getValue(), elidedAttrs);
560 }
561
562 /// If the specified operation has attributes, print out an attribute
563 /// dictionary prefixed with 'attributes'.
564 virtual void
566 ArrayRef<StringRef> elidedAttrs = {}) = 0;
567
568 /// Prints the entire operation with the custom assembly form, if available,
569 /// or the generic assembly form, otherwise.
570 virtual void printCustomOrGenericOp(Operation *op) = 0;
571
572 /// Print the entire operation with the default generic assembly form.
573 /// If `printOpName` is true, then the operation name is printed (the default)
574 /// otherwise it is omitted and the print will start with the operand list.
575 virtual void printGenericOp(Operation *op, bool printOpName = true) = 0;
576
577 /// Prints a region.
578 /// If 'printEntryBlockArgs' is false, the arguments of the
579 /// block are not printed. If 'printBlockTerminator' is false, the terminator
580 /// operation of the block is not printed. If printEmptyBlock is true, then
581 /// the block header is printed even if the block is empty.
582 virtual void printRegion(Region &blocks, bool printEntryBlockArgs = true,
583 bool printBlockTerminators = true,
584 bool printEmptyBlock = false) = 0;
585
586 /// Renumber the arguments for the specified region to the same names as the
587 /// SSA values in namesToUse. This may only be used for IsolatedFromAbove
588 /// operations. If any entry in namesToUse is null, the corresponding
589 /// argument name is left alone.
590 virtual void shadowRegionArgs(Region &region, ValueRange namesToUse) = 0;
591
592 /// Prints an affine map of SSA ids, where SSA id names are used in place
593 /// of dims/symbols.
594 /// Operand values must come from single-result sources, and be valid
595 /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
596 virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr,
597 ValueRange operands) = 0;
598
599 /// Prints an affine expression of SSA ids with SSA id names used instead of
600 /// dims and symbols.
601 /// Operand values must come from single-result sources, and be valid
602 /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
603 virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands,
604 ValueRange symOperands) = 0;
605
606 /// Print the complete type of an operation in functional form.
609};
610
611// Make the implementations convenient to use.
613 p.printOperand(value);
614 return p;
615}
616
618 p.printOperands(values);
619 return p;
620}
621
624 p.printOperandTypes(types);
625 return p;
626}
627
628template <typename T,
629 std::enable_if_t<std::is_convertible<T &, ValueRange>::value &&
630 !std::is_convertible<T &, Value &>::value,
631 T> * = nullptr>
632inline OpAsmPrinter &operator<<(OpAsmPrinter &p, const T &values) {
633 p.printOperands(values);
634 return p;
635}
636
638 p.printSuccessor(value);
639 return p;
640}
641
642//===----------------------------------------------------------------------===//
643// AsmParser
644//===----------------------------------------------------------------------===//
645
646/// This base class exposes generic asm parser hooks, usable across the various
647/// derived parsers.
649public:
650 AsmParser() = default;
651 virtual ~AsmParser();
652
653 MLIRContext *getContext() const;
654
655 /// Return the location of the original name token.
656 virtual SMLoc getNameLoc() const = 0;
657
658 //===--------------------------------------------------------------------===//
659 // Utilities
660 //===--------------------------------------------------------------------===//
661
662 /// Emit a diagnostic at the specified location and return failure.
663 virtual InFlightDiagnostic emitError(SMLoc loc,
664 const Twine &message = {}) = 0;
665
666 /// Return a builder which provides useful access to MLIRContext, global
667 /// objects like types and attributes.
668 virtual Builder &getBuilder() const = 0;
669
670 /// Get the location of the next token and store it into the argument. This
671 /// always succeeds.
672 virtual SMLoc getCurrentLocation() = 0;
673 ParseResult getCurrentLocation(SMLoc *loc) {
674 *loc = getCurrentLocation();
675 return success();
676 }
677
678 /// Re-encode the given source location as an MLIR location and return it.
679 /// Note: This method should only be used when a `Location` is necessary, as
680 /// the encoding process is not efficient.
681 virtual Location getEncodedSourceLoc(SMLoc loc) = 0;
682
683 //===--------------------------------------------------------------------===//
684 // Token Parsing
685 //===--------------------------------------------------------------------===//
686
687 /// Parse a '->' token.
688 virtual ParseResult parseArrow() = 0;
689
690 /// Parse a '->' token if present
691 virtual ParseResult parseOptionalArrow() = 0;
692
693 /// Parse a `{` token.
694 virtual ParseResult parseLBrace() = 0;
695
696 /// Parse a `{` token if present.
697 virtual ParseResult parseOptionalLBrace() = 0;
698
699 /// Parse a `}` token.
700 virtual ParseResult parseRBrace() = 0;
701
702 /// Parse a `}` token if present.
703 virtual ParseResult parseOptionalRBrace() = 0;
704
705 /// Parse a `:` token.
706 virtual ParseResult parseColon() = 0;
707
708 /// Parse a `:` token if present.
709 virtual ParseResult parseOptionalColon() = 0;
710
711 /// Parse a `,` token.
712 virtual ParseResult parseComma() = 0;
713
714 /// Parse a `,` token if present.
715 virtual ParseResult parseOptionalComma() = 0;
716
717 /// Parse a `=` token.
718 virtual ParseResult parseEqual() = 0;
719
720 /// Parse a `=` token if present.
721 virtual ParseResult parseOptionalEqual() = 0;
722
723 /// Parse a '<' token.
724 virtual ParseResult parseLess() = 0;
725
726 /// Parse a '<' token if present.
727 virtual ParseResult parseOptionalLess() = 0;
728
729 /// Parse a '>' token.
730 virtual ParseResult parseGreater() = 0;
731
732 /// Parse a '>' token if present.
733 virtual ParseResult parseOptionalGreater() = 0;
734
735 /// Parse a '?' token.
736 virtual ParseResult parseQuestion() = 0;
737
738 /// Parse a '?' token if present.
739 virtual ParseResult parseOptionalQuestion() = 0;
740
741 /// Parse a '+' token.
742 virtual ParseResult parsePlus() = 0;
743
744 /// Parse a '+' token if present.
745 virtual ParseResult parseOptionalPlus() = 0;
746
747 /// Parse a '/' token.
748 virtual ParseResult parseSlash() = 0;
749
750 /// Parse a '/' token if present.
751 virtual ParseResult parseOptionalSlash() = 0;
752
753 /// Parse a '-' token.
754 virtual ParseResult parseMinus() = 0;
755
756 /// Parse a '-' token if present.
757 virtual ParseResult parseOptionalMinus() = 0;
758
759 /// Parse a '*' token.
760 virtual ParseResult parseStar() = 0;
761
762 /// Parse a '*' token if present.
763 virtual ParseResult parseOptionalStar() = 0;
764
765 /// Parse a '|' token.
766 virtual ParseResult parseVerticalBar() = 0;
767
768 /// Parse a '|' token if present.
769 virtual ParseResult parseOptionalVerticalBar() = 0;
770
771 /// Parse a quoted string token.
772 ParseResult parseString(std::string *string) {
773 auto loc = getCurrentLocation();
774 if (parseOptionalString(string))
775 return emitError(loc, "expected string");
776 return success();
777 }
778
779 /// Parse a quoted string token if present.
780 virtual ParseResult parseOptionalString(std::string *string) = 0;
781
782 /// Parses a Base64 encoded string of bytes.
783 virtual ParseResult parseBase64Bytes(std::vector<char> *bytes) = 0;
784
785 /// Parse a `(` token.
786 virtual ParseResult parseLParen() = 0;
787
788 /// Parse a `(` token if present.
789 virtual ParseResult parseOptionalLParen() = 0;
790
791 /// Parse a `)` token.
792 virtual ParseResult parseRParen() = 0;
793
794 /// Parse a `)` token if present.
795 virtual ParseResult parseOptionalRParen() = 0;
796
797 /// Parse a `[` token.
798 virtual ParseResult parseLSquare() = 0;
799
800 /// Parse a `[` token if present.
801 virtual ParseResult parseOptionalLSquare() = 0;
802
803 /// Parse a `]` token.
804 virtual ParseResult parseRSquare() = 0;
805
806 /// Parse a `]` token if present.
807 virtual ParseResult parseOptionalRSquare() = 0;
808
809 /// Parse a `...` token.
810 virtual ParseResult parseEllipsis() = 0;
811
812 /// Parse a `...` token if present;
813 virtual ParseResult parseOptionalEllipsis() = 0;
814
815 /// Parse a floating point value from the stream.
816 virtual ParseResult parseFloat(double &result) = 0;
817
818 /// Parse a floating point value into APFloat from the stream.
819 virtual ParseResult parseFloat(const llvm::fltSemantics &semantics,
820 APFloat &result) = 0;
821
822 /// Parse an integer value from the stream.
823 template <typename IntT>
824 ParseResult parseInteger(IntT &result) {
825 auto loc = getCurrentLocation();
827 if (!parseResult.has_value())
828 return emitError(loc, "expected integer value");
829 return *parseResult;
830 }
831
832 /// Parse a decimal integer value from the stream.
833 template <typename IntT>
834 ParseResult parseDecimalInteger(IntT &result) {
835 auto loc = getCurrentLocation();
837 if (!parseResult.has_value())
838 return emitError(loc, "expected decimal integer value");
839 return *parseResult;
840 }
841
842 /// Parse an optional integer value from the stream.
845
846private:
847 template <typename IntT, typename ParseFn>
848 OptionalParseResult parseOptionalIntegerAndCheck(IntT &result,
849 ParseFn &&parseFn) {
850 auto loc = getCurrentLocation();
851 APInt uintResult;
852 OptionalParseResult parseResult = parseFn(uintResult);
853 if (!parseResult.has_value() || failed(*parseResult))
854 return parseResult;
855
856 // Try to convert to the provided integer type. sextOrTrunc is correct even
857 // for unsigned types because parseOptionalInteger ensures the sign bit is
858 // zero for non-negated integers.
859 result =
860 (IntT)uintResult.sextOrTrunc(sizeof(IntT) * CHAR_BIT).getLimitedValue();
861 if (APInt(uintResult.getBitWidth(), result,
862 /*isSigned=*/std::is_signed_v<IntT>,
863 /*implicitTrunc=*/true) != uintResult)
864 return emitError(loc, "integer value too large");
865 return success();
866 }
867
868public:
869 template <typename IntT>
871 return parseOptionalIntegerAndCheck(
872 result, [&](APInt &result) { return parseOptionalInteger(result); });
873 }
874
875 template <typename IntT>
877 return parseOptionalIntegerAndCheck(result, [&](APInt &result) {
879 });
880 }
881
882 /// These are the supported delimiters around operand lists and region
883 /// argument lists, used by parseOperandList.
884 enum class Delimiter {
885 /// Zero or more operands with no delimiters.
887 /// Parens surrounding zero or more operands.
889 /// Square brackets surrounding zero or more operands.
891 /// <> brackets surrounding zero or more operands.
893 /// {} brackets surrounding zero or more operands.
895 /// Parens supporting zero or more operands, or nothing.
897 /// Square brackets supporting zero or more ops, or nothing.
899 /// <> brackets supporting zero or more ops, or nothing.
901 /// {} brackets surrounding zero or more operands, or nothing.
903 };
904
905 /// Parse a list of comma-separated items with an optional delimiter. If a
906 /// delimiter is provided, then an empty list is allowed. If not, then at
907 /// least one element will be parsed.
908 ///
909 /// contextMessage is an optional message appended to "expected '('" sorts of
910 /// diagnostics when parsing the delimeters.
911 virtual ParseResult
913 function_ref<ParseResult()> parseElementFn,
914 StringRef contextMessage = StringRef()) = 0;
915
916 /// Parse a comma separated list of elements that must have at least one entry
917 /// in it.
918 ParseResult
919 parseCommaSeparatedList(function_ref<ParseResult()> parseElementFn) {
920 return parseCommaSeparatedList(Delimiter::None, parseElementFn);
921 }
922
923 //===--------------------------------------------------------------------===//
924 // Keyword Parsing
925 //===--------------------------------------------------------------------===//
926
927 /// This class represents a StringSwitch like class that is useful for parsing
928 /// expected keywords. On construction, unless a non-empty keyword is
929 /// provided, it invokes `parseKeyword` and processes each of the provided
930 /// cases statements until a match is hit. The provided `ResultT` must be
931 /// assignable from `failure()`.
932 template <typename ResultT = ParseResult>
934 public:
935 KeywordSwitch(AsmParser &parser, StringRef *keyword = nullptr)
936 : parser(parser), loc(parser.getCurrentLocation()) {
937 if (keyword && !keyword->empty())
938 this->keyword = *keyword;
939 else if (failed(parser.parseKeywordOrCompletion(&this->keyword)))
940 result = failure();
941 }
942 /// Case that uses the provided value when true.
943 KeywordSwitch &Case(StringLiteral str, ResultT value) {
944 return Case(str, [&](StringRef, SMLoc) { return std::move(value); });
945 }
946 KeywordSwitch &Default(ResultT value) {
947 return Default([&](StringRef, SMLoc) { return std::move(value); });
948 }
949 /// Case that invokes the provided functor when true. The parameters passed
950 /// to the functor are the keyword, and the location of the keyword (in case
951 /// any errors need to be emitted).
952 template <typename FnT, typename = std::enable_if_t<
953 !std::is_convertible<FnT, ResultT>::value>>
954 KeywordSwitch &Case(StringLiteral str, FnT &&fn) {
955 if (result)
956 return *this;
957
958 // If the word was empty, record this as a completion.
959 if (keyword.empty())
960 parser.codeCompleteExpectedTokens(str);
961 else if (keyword == str)
962 result.emplace(std::move(fn(keyword, loc)));
963 return *this;
964 }
965 template <typename FnT, typename = std::enable_if_t<
966 !std::is_convertible<FnT, ResultT>::value>>
968 if (!result)
969 result.emplace(fn(keyword, loc));
970 return *this;
971 }
972
973 /// Returns true if this switch has a value yet.
974 bool hasValue() const { return result.has_value(); }
975
976 /// Return the result of the switch.
977 [[nodiscard]] operator ResultT() {
978 if (!result)
979 return parser.emitError(loc, "unexpected keyword: ") << keyword;
980 return std::move(*result);
981 }
982
983 private:
984 /// The parser used to construct this switch.
985 AsmParser &parser;
986
987 /// The location of the keyword, used to emit errors as necessary.
988 SMLoc loc;
989
990 /// The parsed keyword itself.
991 StringRef keyword;
992
993 /// The result of the switch statement or std::nullopt if currently unknown.
994 std::optional<ResultT> result;
995 };
996
997 /// Parse a given keyword.
998 ParseResult parseKeyword(StringRef keyword) {
999 return parseKeyword(keyword, "");
1000 }
1001 virtual ParseResult parseKeyword(StringRef keyword, const Twine &msg) = 0;
1002
1003 /// Parse a keyword into 'keyword'.
1004 ParseResult parseKeyword(StringRef *keyword) {
1005 auto loc = getCurrentLocation();
1006 if (parseOptionalKeyword(keyword))
1007 return emitError(loc, "expected valid keyword");
1008 return success();
1009 }
1010
1011 /// Parse the given keyword if present.
1012 virtual ParseResult parseOptionalKeyword(StringRef keyword) = 0;
1013
1014 /// Parse a keyword, if present, into 'keyword'.
1015 virtual ParseResult parseOptionalKeyword(StringRef *keyword) = 0;
1016
1017 /// Parse a keyword, if present, and if one of the 'allowedValues',
1018 /// into 'keyword'
1019 virtual ParseResult
1020 parseOptionalKeyword(StringRef *keyword,
1021 ArrayRef<StringRef> allowedValues) = 0;
1022
1023 /// Parse a string into 'string' if it is present and one of the
1024 /// 'allowedValues'.
1025 virtual ParseResult
1026 parseOptionalString(std::string *string,
1027 ArrayRef<StringRef> allowedValues) = 0;
1028
1029 /// Parse a keyword or a quoted string.
1030 ParseResult parseKeywordOrString(std::string *result) {
1033 << "expected valid keyword or string";
1034 return success();
1035 }
1036
1037 /// Parse an optional keyword or string.
1038 virtual ParseResult parseOptionalKeywordOrString(std::string *result) = 0;
1039
1040 /// Parse an optional keyword or string into `result` if it is present and one
1041 /// of the 'allowedValues'.
1042 virtual ParseResult
1044 ArrayRef<StringRef> allowedValues) = 0;
1045
1046 //===--------------------------------------------------------------------===//
1047 // Attribute/Type Parsing
1048 //===--------------------------------------------------------------------===//
1049
1050 /// Invoke the `getChecked` method of the given Attribute or Type class, using
1051 /// the provided location to emit errors in the case of failure. Note that
1052 /// unlike `OpBuilder::getType`, this method does not implicitly insert a
1053 /// context parameter.
1054 template <typename T, typename... ParamsT>
1055 auto getChecked(SMLoc loc, ParamsT &&...params) {
1056 return T::getChecked([&] { return emitError(loc); },
1057 std::forward<ParamsT>(params)...);
1058 }
1059 /// A variant of `getChecked` that uses the result of `getNameLoc` to emit
1060 /// errors.
1061 template <typename T, typename... ParamsT>
1062 auto getChecked(ParamsT &&...params) {
1063 return T::getChecked([&] { return emitError(getNameLoc()); },
1064 std::forward<ParamsT>(params)...);
1065 }
1066
1067 //===--------------------------------------------------------------------===//
1068 // Attribute Parsing
1069 //===--------------------------------------------------------------------===//
1070
1071 /// Parse an arbitrary attribute of a given type and return it in result.
1072 virtual ParseResult parseAttribute(Attribute &result, Type type = {}) = 0;
1073
1074 /// Parse a custom attribute with the provided callback, unless the next
1075 /// token is `#`, in which case the generic parser is invoked.
1077 Attribute &result, Type type,
1078 function_ref<ParseResult(Attribute &result, Type type)>
1079 parseAttribute) = 0;
1080
1081 /// Parse an attribute of a specific kind and type.
1082 template <typename AttrType>
1083 ParseResult parseAttribute(AttrType &result, Type type = {}) {
1084 SMLoc loc = getCurrentLocation();
1085
1086 // Parse any kind of attribute.
1087 Attribute attr;
1088 if (parseAttribute(attr, type))
1089 return failure();
1090
1091 // Check for the right kind of attribute.
1092 if (!(result = llvm::dyn_cast<AttrType>(attr)))
1093 return emitError(loc, "invalid kind of attribute specified");
1094
1095 return success();
1096 }
1097
1098 /// Parse an arbitrary attribute and return it in result. This also adds the
1099 /// attribute to the specified attribute list with the specified name.
1100 ParseResult parseAttribute(Attribute &result, StringRef attrName,
1101 NamedAttrList &attrs) {
1102 return parseAttribute(result, Type(), attrName, attrs);
1103 }
1104
1105 /// Parse an attribute of a specific kind and type.
1106 template <typename AttrType>
1107 ParseResult parseAttribute(AttrType &result, StringRef attrName,
1108 NamedAttrList &attrs) {
1109 return parseAttribute(result, Type(), attrName, attrs);
1110 }
1111
1112 /// Parse an arbitrary attribute of a given type and populate it in `result`.
1113 /// This also adds the attribute to the specified attribute list with the
1114 /// specified name.
1115 template <typename AttrType>
1116 ParseResult parseAttribute(AttrType &result, Type type, StringRef attrName,
1117 NamedAttrList &attrs) {
1118 SMLoc loc = getCurrentLocation();
1119
1120 // Parse any kind of attribute.
1121 Attribute attr;
1122 if (parseAttribute(attr, type))
1123 return failure();
1124
1125 // Check for the right kind of attribute.
1126 result = llvm::dyn_cast<AttrType>(attr);
1127 if (!result)
1128 return emitError(loc, "invalid kind of attribute specified");
1129
1130 attrs.append(attrName, result);
1131 return success();
1132 }
1133
1134 /// Trait to check if `AttrType` provides a `parse` method.
1135 template <typename AttrType>
1136 using has_parse_method = decltype(AttrType::parse(std::declval<AsmParser &>(),
1137 std::declval<Type>()));
1138 template <typename AttrType>
1139 using detect_has_parse_method = llvm::is_detected<has_parse_method, AttrType>;
1140
1141 /// Parse a custom attribute of a given type unless the next token is `#`, in
1142 /// which case the generic parser is invoked. The parsed attribute is
1143 /// populated in `result` and also added to the specified attribute list with
1144 /// the specified name.
1145 template <typename AttrType>
1146 std::enable_if_t<detect_has_parse_method<AttrType>::value, ParseResult>
1148 StringRef attrName, NamedAttrList &attrs) {
1149 SMLoc loc = getCurrentLocation();
1150
1151 // Parse any kind of attribute.
1152 Attribute attr;
1154 attr, type, [&](Attribute &result, Type type) -> ParseResult {
1155 result = AttrType::parse(*this, type);
1156 if (!result)
1157 return failure();
1158 return success();
1159 }))
1160 return failure();
1161
1162 // Check for the right kind of attribute.
1163 result = llvm::dyn_cast<AttrType>(attr);
1164 if (!result)
1165 return emitError(loc, "invalid kind of attribute specified");
1166
1167 attrs.append(attrName, result);
1168 return success();
1169 }
1170
1171 /// SFINAE parsing method for Attribute that don't implement a parse method.
1172 template <typename AttrType>
1173 std::enable_if_t<!detect_has_parse_method<AttrType>::value, ParseResult>
1175 StringRef attrName, NamedAttrList &attrs) {
1176 return parseAttribute(result, type, attrName, attrs);
1177 }
1178
1179 /// Parse a custom attribute of a given type unless the next token is `#`, in
1180 /// which case the generic parser is invoked. The parsed attribute is
1181 /// populated in `result`.
1182 template <typename AttrType>
1183 std::enable_if_t<detect_has_parse_method<AttrType>::value, ParseResult>
1185 SMLoc loc = getCurrentLocation();
1186
1187 // Parse any kind of attribute.
1188 Attribute attr;
1190 attr, type, [&](Attribute &result, Type type) -> ParseResult {
1191 result = AttrType::parse(*this, type);
1192 return success(!!result);
1193 }))
1194 return failure();
1195
1196 // Check for the right kind of attribute.
1197 result = llvm::dyn_cast<AttrType>(attr);
1198 if (!result)
1199 return emitError(loc, "invalid kind of attribute specified");
1200 return success();
1201 }
1202
1203 /// SFINAE parsing method for Attribute that don't implement a parse method.
1204 template <typename AttrType>
1205 std::enable_if_t<!detect_has_parse_method<AttrType>::value, ParseResult>
1207 return parseAttribute(result, type);
1208 }
1209
1210 /// Parse an arbitrary optional attribute of a given type and return it in
1211 /// result.
1213 Type type = {}) = 0;
1214
1215 /// Parse an optional array attribute and return it in result.
1217 Type type = {}) = 0;
1218
1219 /// Parse an optional string attribute and return it in result.
1221 Type type = {}) = 0;
1222
1223 /// Parse an optional symbol ref attribute and return it in result.
1225 Type type = {}) = 0;
1226
1227 /// Parse an optional attribute of a specific typed result. This overload
1228 /// handles concrete attribute types (e.g. FloatAttr) that are not covered by
1229 /// a dedicated virtual overload. It parses any attribute and then validates
1230 /// that the result is of the expected type, emitting an error if not.
1231 template <
1232 typename AttrType,
1233 typename = std::enable_if_t<!llvm::is_one_of<
1234 AttrType, Attribute, ArrayAttr, StringAttr, SymbolRefAttr>::value>>
1236 llvm::SMLoc loc = getCurrentLocation();
1237 Attribute attr;
1238 OptionalParseResult parseResult = parseOptionalAttribute(attr, type);
1239 if (!parseResult.has_value() || failed(*parseResult))
1240 return parseResult;
1241 result = dyn_cast<AttrType>(attr);
1242 if (!result) {
1244 emitError(loc, "invalid kind of attribute specified");
1245 if constexpr (HasStaticName<AttrType>::value)
1246 diag << ": expected " << AttrType::name << ", but found " << attr;
1247 return diag;
1248 }
1249 return success();
1250 }
1251
1252 /// Parse an optional attribute of a specific type and add it to the list with
1253 /// the specified name.
1254 template <typename AttrType>
1256 StringRef attrName,
1257 NamedAttrList &attrs) {
1258 return parseOptionalAttribute(result, Type(), attrName, attrs);
1259 }
1260
1261 /// Parse an optional attribute of a specific type and add it to the list with
1262 /// the specified name.
1263 template <typename AttrType>
1265 StringRef attrName,
1266 NamedAttrList &attrs) {
1268 if (parseResult.has_value() && succeeded(*parseResult))
1269 attrs.append(attrName, result);
1270 return parseResult;
1271 }
1272
1273 /// Parse a named dictionary into 'result' if it is present.
1274 virtual ParseResult parseOptionalAttrDict(NamedAttrList &result) = 0;
1275
1276 /// Parse a named dictionary into 'result' if the `attributes` keyword is
1277 /// present.
1278 virtual ParseResult
1280
1281 /// Parse an affine map instance into 'map'.
1282 virtual ParseResult parseAffineMap(AffineMap &map) = 0;
1283
1284 /// Parse an affine expr instance into 'expr' using the already computed
1285 /// mapping from symbols to affine expressions in 'symbolSet'.
1286 virtual ParseResult
1287 parseAffineExpr(ArrayRef<std::pair<StringRef, AffineExpr>> symbolSet,
1288 AffineExpr &expr) = 0;
1289
1290 /// Parse an integer set instance into 'set'.
1291 virtual ParseResult parseIntegerSet(IntegerSet &set) = 0;
1292
1293 //===--------------------------------------------------------------------===//
1294 // Identifier Parsing
1295 //===--------------------------------------------------------------------===//
1296
1297 /// Parse an @-identifier and store it (without the '@' symbol) in a string
1298 /// attribute.
1299 ParseResult parseSymbolName(StringAttr &result) {
1300 if (failed(parseOptionalSymbolName(result)))
1302 << "expected valid '@'-identifier for symbol name";
1303 return success();
1304 }
1305
1306 /// Parse an @-identifier and store it (without the '@' symbol) in a string
1307 /// attribute named 'attrName'.
1308 ParseResult parseSymbolName(StringAttr &result, StringRef attrName,
1309 NamedAttrList &attrs) {
1311 return failure();
1312 attrs.append(attrName, result);
1313 return success();
1314 }
1315
1316 /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1317 /// string attribute.
1318 virtual ParseResult parseOptionalSymbolName(StringAttr &result) = 0;
1319
1320 /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1321 /// string attribute named 'attrName'.
1322 ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName,
1323 NamedAttrList &attrs) {
1324 if (succeeded(parseOptionalSymbolName(result))) {
1325 attrs.append(attrName, result);
1326 return success();
1327 }
1328 return failure();
1329 }
1330
1331 //===--------------------------------------------------------------------===//
1332 // Resource Parsing
1333 //===--------------------------------------------------------------------===//
1334
1335 /// Parse a handle to a resource within the assembly format.
1336 template <typename ResourceT>
1337 FailureOr<ResourceT> parseResourceHandle() {
1338 SMLoc handleLoc = getCurrentLocation();
1339
1340 // Try to load the dialect that owns the handle.
1341 auto *dialect =
1342 getContext()->getOrLoadDialect<typename ResourceT::Dialect>();
1343 if (!dialect) {
1344 return emitError(handleLoc)
1345 << "dialect '" << ResourceT::Dialect::getDialectNamespace()
1346 << "' is unknown";
1347 }
1348
1349 FailureOr<AsmDialectResourceHandle> handle = parseResourceHandle(dialect);
1350 if (failed(handle))
1351 return failure();
1352 if (auto *result = dyn_cast<ResourceT>(&*handle))
1353 return std::move(*result);
1354 return emitError(handleLoc) << "provided resource handle differs from the "
1355 "expected resource type";
1356 }
1357
1358 //===--------------------------------------------------------------------===//
1359 // Type Parsing
1360 //===--------------------------------------------------------------------===//
1361
1362 /// Parse a type.
1363 virtual ParseResult parseType(Type &result) = 0;
1364
1365 /// Parse a custom type with the provided callback, unless the next
1366 /// token is `#`, in which case the generic parser is invoked.
1367 virtual ParseResult parseCustomTypeWithFallback(
1368 Type &result, function_ref<ParseResult(Type &result)> parseType) = 0;
1369
1370 /// Parse an optional type.
1372
1373 /// Parse a type of a specific type.
1374 template <typename TypeT>
1375 ParseResult parseType(TypeT &result) {
1376 SMLoc loc = getCurrentLocation();
1377
1378 // Parse any kind of type.
1379 Type type;
1380 if (parseType(type))
1381 return failure();
1382
1383 // Check for the right kind of type.
1384 result = llvm::dyn_cast<TypeT>(type);
1385 if (!result) {
1387 emitError(loc, "invalid kind of type specified");
1388 if constexpr (HasStaticName<TypeT>::value)
1389 diag << ": expected " << TypeT::name << ", but found " << type;
1390 return diag;
1391 }
1392
1393 return success();
1394 }
1395
1396 /// Trait to check if `TypeT` provides a `parse` method.
1397 template <typename TypeT>
1399 decltype(TypeT::parse(std::declval<AsmParser &>()));
1400 template <typename TypeT>
1402 llvm::is_detected<type_has_parse_method, TypeT>;
1403
1404 /// Parse a custom Type of a given type unless the next token is `#`, in
1405 /// which case the generic parser is invoked. The parsed Type is
1406 /// populated in `result`.
1407 template <typename TypeT>
1408 std::enable_if_t<detect_type_has_parse_method<TypeT>::value, ParseResult>
1410 SMLoc loc = getCurrentLocation();
1411
1412 // Parse any kind of Type.
1413 Type type;
1414 if (parseCustomTypeWithFallback(type, [&](Type &result) -> ParseResult {
1415 result = TypeT::parse(*this);
1416 return success(!!result);
1417 }))
1418 return failure();
1419
1420 // Check for the right kind of Type.
1421 result = llvm::dyn_cast<TypeT>(type);
1422 if (!result) {
1424 emitError(loc, "invalid kind of type specified");
1425 if constexpr (HasStaticName<TypeT>::value)
1426 diag << ": expected " << TypeT::name << ", but found " << type;
1427 return diag;
1428 }
1429 return success();
1430 }
1431
1432 /// SFINAE parsing method for Type that don't implement a parse method.
1433 template <typename TypeT>
1434 std::enable_if_t<!detect_type_has_parse_method<TypeT>::value, ParseResult>
1436 return parseType(result);
1437 }
1438
1439 /// Parse a type list.
1441
1442 /// Parse an arrow followed by a type list.
1444
1445 /// Parse an optional arrow followed by a type list.
1446 virtual ParseResult
1448
1449 /// Parse a colon followed by a type.
1450 virtual ParseResult parseColonType(Type &result) = 0;
1451
1452 /// Parse a colon followed by a type of a specific kind, e.g. a FunctionType.
1453 template <typename TypeType>
1454 ParseResult parseColonType(TypeType &result) {
1455 SMLoc loc = getCurrentLocation();
1456
1457 // Parse any kind of type.
1458 Type type;
1459 if (parseColonType(type))
1460 return failure();
1461
1462 // Check for the right kind of type.
1463 result = llvm::dyn_cast<TypeType>(type);
1464 if (!result) {
1466 emitError(loc, "invalid kind of type specified");
1467 if constexpr (HasStaticName<TypeType>::value)
1468 diag << ": expected " << TypeType::name << ", but found " << type;
1469 return diag;
1470 }
1471
1472 return success();
1473 }
1474
1475 /// Parse a colon followed by a type list, which must have at least one type.
1477
1478 /// Parse an optional colon followed by a type list, which if present must
1479 /// have at least one type.
1480 virtual ParseResult
1482
1483 /// Parse a keyword followed by a type.
1484 ParseResult parseKeywordType(const char *keyword, Type &result) {
1485 return failure(parseKeyword(keyword) || parseType(result));
1486 }
1487
1488 /// Add the specified type to the end of the specified type list and return
1489 /// success. This is a helper designed to allow parse methods to be simple
1490 /// and chain through || operators.
1492 result.push_back(type);
1493 return success();
1494 }
1495
1496 /// Add the specified types to the end of the specified type list and return
1497 /// success. This is a helper designed to allow parse methods to be simple
1498 /// and chain through || operators.
1501 result.append(types.begin(), types.end());
1502 return success();
1503 }
1504
1505 /// Parse a dimension list of a tensor or memref type. This populates the
1506 /// dimension list, using ShapedType::kDynamic for the `?` dimensions if
1507 /// `allowDynamic` is set and errors out on `?` otherwise. Parsing the
1508 /// trailing `x` is configurable.
1509 ///
1510 /// dimension-list ::= eps | dimension (`x` dimension)*
1511 /// dimension-list-with-trailing-x ::= (dimension `x`)*
1512 /// dimension ::= `?` | decimal-literal
1513 ///
1514 /// When `allowDynamic` is not set, this is used to parse:
1515 ///
1516 /// static-dimension-list ::= eps | decimal-literal (`x` decimal-literal)*
1517 /// static-dimension-list-with-trailing-x ::= (dimension `x`)*
1518 virtual ParseResult parseDimensionList(SmallVectorImpl<int64_t> &dimensions,
1519 bool allowDynamic = true,
1520 bool withTrailingX = true) = 0;
1521
1522 /// Parse an 'x' token in a dimension list, handling the case where the x is
1523 /// juxtaposed with an element type, as in "xf32", leaving the "f32" as the
1524 /// next token.
1525 virtual ParseResult parseXInDimensionList() = 0;
1526
1527 /// Class used to automatically end a cyclic region on destruction.
1529 public:
1530 explicit CyclicParseReset(AsmParser *parser) : parser(parser) {}
1531
1533 if (parser)
1534 parser->popCyclicParsing();
1535 }
1536
1540 : parser(std::exchange(rhs.parser, nullptr)) {}
1542 parser = std::exchange(rhs.parser, nullptr);
1543 return *this;
1544 }
1545
1546 private:
1547 AsmParser *parser;
1548 };
1549
1550 /// Attempts to start a cyclic parsing region for `attrOrType`.
1551 /// A cyclic parsing region starts with this call and ends with the
1552 /// destruction of the returned `CyclicParseReset`. During this time,
1553 /// calling `tryStartCyclicParse` with the same attribute in any parser
1554 /// will lead to returning failure.
1555 ///
1556 /// This makes it possible to parse cyclic attributes or types by parsing a
1557 /// short from if nested within itself.
1558 template <class AttrOrTypeT>
1559 FailureOr<CyclicParseReset> tryStartCyclicParse(AttrOrTypeT attrOrType) {
1560 static_assert(
1561 std::is_base_of_v<AttributeTrait::IsMutable<AttrOrTypeT>,
1562 AttrOrTypeT> ||
1563 std::is_base_of_v<TypeTrait::IsMutable<AttrOrTypeT>, AttrOrTypeT>,
1564 "Only mutable attributes or types can be cyclic");
1565 if (failed(pushCyclicParsing(attrOrType.getAsOpaquePointer())))
1566 return failure();
1567
1568 return CyclicParseReset(this);
1569 }
1570
1571protected:
1572 /// Parse a handle to a resource within the assembly format for the given
1573 /// dialect.
1574 virtual FailureOr<AsmDialectResourceHandle>
1576
1577 /// Pushes a new attribute or type in the form of a type erased pointer
1578 /// into an internal set.
1579 /// Returns success if the type or attribute was inserted in the set or
1580 /// failure if it was already contained.
1581 virtual LogicalResult pushCyclicParsing(const void *opaquePointer) = 0;
1582
1583 /// Removes the element that was last inserted with a successful call to
1584 /// `pushCyclicParsing`. There must be exactly one `popCyclicParsing` call
1585 /// in reverse order of all successful `pushCyclicParsing`.
1586 virtual void popCyclicParsing() = 0;
1587
1588 //===--------------------------------------------------------------------===//
1589 // Code Completion
1590 //===--------------------------------------------------------------------===//
1591
1592 /// Parse a keyword, or an empty string if the current location signals a code
1593 /// completion.
1594 virtual ParseResult parseKeywordOrCompletion(StringRef *keyword) = 0;
1595
1596 /// Signal the code completion of a set of expected tokens.
1598
1599private:
1600 AsmParser(const AsmParser &) = delete;
1601 void operator=(const AsmParser &) = delete;
1602};
1603
1604//===----------------------------------------------------------------------===//
1605// OpAsmParser
1606//===----------------------------------------------------------------------===//
1607
1608/// The OpAsmParser has methods for interacting with the asm parser: parsing
1609/// things from it, emitting errors etc. It has an intentionally high-level API
1610/// that is designed to reduce/constrain syntax innovation in individual
1611/// operations.
1612///
1613/// For example, consider an op like this:
1614///
1615/// %x = load %p[%1, %2] : memref<...>
1616///
1617/// The "%x = load" tokens are already parsed and therefore invisible to the
1618/// custom op parser. This can be supported by calling `parseOperandList` to
1619/// parse the %p, then calling `parseOperandList` with a `SquareDelimiter` to
1620/// parse the indices, then calling `parseColonTypeList` to parse the result
1621/// type.
1622///
1623class OpAsmParser : public AsmParser {
1624public:
1626 ~OpAsmParser() override;
1627
1628 /// Parse a loc(...) specifier if present, filling in result if so.
1629 /// Location for BlockArgument and Operation may be deferred with an alias, in
1630 /// which case an OpaqueLoc is set and will be resolved when parsing
1631 /// completes.
1632 virtual ParseResult
1633 parseOptionalLocationSpecifier(std::optional<Location> &result) = 0;
1634
1635 /// Return the name of the specified result in the specified syntax, as well
1636 /// as the sub-element in the name. It returns an empty string and ~0U for
1637 /// invalid result numbers. For example, in this operation:
1638 ///
1639 /// %x, %y:2, %z = foo.op
1640 ///
1641 /// getResultName(0) == {"x", 0 }
1642 /// getResultName(1) == {"y", 0 }
1643 /// getResultName(2) == {"y", 1 }
1644 /// getResultName(3) == {"z", 0 }
1645 /// getResultName(4) == {"", ~0U }
1646 virtual std::pair<StringRef, unsigned>
1647 getResultName(unsigned resultNo) const = 0;
1648
1649 /// Return the number of declared SSA results. This returns 4 for the foo.op
1650 /// example in the comment for `getResultName`.
1651 virtual size_t getNumResults() const = 0;
1652
1653 // These methods emit an error and return failure or success. This allows
1654 // these to be chained together into a linear sequence of || expressions in
1655 // many cases.
1656
1657 /// Parse an operation in its generic form.
1658 /// The parsed operation is parsed in the current context and inserted in the
1659 /// provided block and insertion point. The results produced by this operation
1660 /// aren't mapped to any named value in the parser. Returns nullptr on
1661 /// failure.
1663 Block::iterator insertPt) = 0;
1664
1665 /// Parse the name of an operation, in the custom form. On success, return a
1666 /// an object of type 'OperationName'. Otherwise, failure is returned.
1667 virtual FailureOr<OperationName> parseCustomOperationName() = 0;
1668
1669 //===--------------------------------------------------------------------===//
1670 // Operand Parsing
1671 //===--------------------------------------------------------------------===//
1672
1673 /// This is the representation of an operand reference.
1675 SMLoc location; // Location of the token.
1676 StringRef name; // Value name, e.g. %42 or %abc
1677 unsigned number; // Number, e.g. 12 for an operand like %xyz#12
1678 };
1679
1680 /// Parse different components, viz., use-info of operand(s), successor(s),
1681 /// region(s), attribute(s) and function-type, of the generic form of an
1682 /// operation instance and populate the input operation-state 'result' with
1683 /// those components. If any of the components is explicitly provided, then
1684 /// skip parsing that component.
1687 std::optional<ArrayRef<UnresolvedOperand>> parsedOperandType =
1688 std::nullopt,
1689 std::optional<ArrayRef<Block *>> parsedSuccessors = std::nullopt,
1690 std::optional<MutableArrayRef<std::unique_ptr<Region>>> parsedRegions =
1691 std::nullopt,
1692 std::optional<ArrayRef<NamedAttribute>> parsedAttributes = std::nullopt,
1693 std::optional<Attribute> parsedPropertiesAttribute = std::nullopt,
1694 std::optional<FunctionType> parsedFnType = std::nullopt) = 0;
1695
1696 /// Parse a single SSA value operand name along with a result number if
1697 /// `allowResultNumber` is true.
1699 bool allowResultNumber = true) = 0;
1700
1701 /// Parse a single operand if present.
1702 virtual OptionalParseResult
1704 bool allowResultNumber = true) = 0;
1705
1706 /// Parse zero or more SSA comma-separated operand references with a specified
1707 /// surrounding delimiter, and an optional required operand count.
1708 virtual ParseResult
1710 Delimiter delimiter = Delimiter::None,
1711 bool allowResultNumber = true,
1712 int requiredOperandCount = -1) = 0;
1713
1714 /// Parse a specified number of comma separated operands.
1716 int requiredOperandCount,
1717 Delimiter delimiter = Delimiter::None) {
1718 return parseOperandList(result, delimiter,
1719 /*allowResultNumber=*/true, requiredOperandCount);
1720 }
1721
1722 /// Parse zero or more trailing SSA comma-separated trailing operand
1723 /// references with a specified surrounding delimiter, and an optional
1724 /// required operand count. A leading comma is expected before the
1725 /// operands.
1726 ParseResult
1728 Delimiter delimiter = Delimiter::None) {
1729 if (failed(parseOptionalComma()))
1730 return success(); // The comma is optional.
1731 return parseOperandList(result, delimiter);
1732 }
1733
1734 /// Resolve an operand to an SSA value, emitting an error on failure.
1735 virtual ParseResult resolveOperand(const UnresolvedOperand &operand,
1736 Type type,
1738
1739 /// Resolve a list of operands to SSA values, emitting an error on failure, or
1740 /// appending the results to the list on success. This method should be used
1741 /// when all operands have the same type.
1742 template <typename Operands = ArrayRef<UnresolvedOperand>>
1743 ParseResult resolveOperands(Operands &&operands, Type type,
1745 for (const UnresolvedOperand &operand : operands)
1746 if (resolveOperand(operand, type, result))
1747 return failure();
1748 return success();
1749 }
1750 template <typename Operands = ArrayRef<UnresolvedOperand>>
1751 ParseResult resolveOperands(Operands &&operands, Type type, SMLoc loc,
1753 return resolveOperands(std::forward<Operands>(operands), type, result);
1754 }
1755
1756 /// Resolve a list of operands and a list of operand types to SSA values,
1757 /// emitting an error and returning failure, or appending the results
1758 /// to the list on success.
1759 template <
1760 typename Operands = ArrayRef<UnresolvedOperand>,
1761 typename Types = ArrayRef<Type>,
1762 typename = std::enable_if_t<!std::is_convertible<Types, Type>::value>>
1763 ParseResult resolveOperands(Operands &&operands, Types &&types, SMLoc loc,
1765 size_t operandSize = llvm::range_size(operands);
1766 size_t typeSize = llvm::range_size(types);
1767 if (operandSize != typeSize) {
1768 // If no location was provided, report errors at the beginning of the op.
1769 return emitError(loc.isValid() ? loc : getNameLoc())
1770 << "number of operands and types do not match: got " << operandSize
1771 << " operands and " << typeSize << " types";
1772 }
1773
1774 for (auto [operand, type] : llvm::zip_equal(operands, types))
1775 if (resolveOperand(operand, type, result))
1776 return failure();
1777 return success();
1778 }
1779
1780 /// Parses an affine map attribute where dims and symbols are SSA operands.
1781 /// Operand values must come from single-result sources, and be valid
1782 /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
1783 virtual ParseResult
1785 Attribute &map, StringRef attrName,
1786 NamedAttrList &attrs,
1787 Delimiter delimiter = Delimiter::Square) = 0;
1788
1789 /// Parses an affine expression where dims and symbols are SSA operands.
1790 /// Operand values must come from single-result sources, and be valid
1791 /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
1792 virtual ParseResult
1795 AffineExpr &expr) = 0;
1796
1797 //===--------------------------------------------------------------------===//
1798 // Argument Parsing
1799 //===--------------------------------------------------------------------===//
1800
1801 struct Argument {
1802 UnresolvedOperand ssaName; // SourceLoc, SSA name, result #.
1803 Type type; // Type.
1804 DictionaryAttr attrs; // Attributes if present.
1805 std::optional<Location> sourceLoc; // Source location specifier if present.
1806 };
1807
1808 /// Parse a single argument with the following syntax:
1809 ///
1810 /// `%ssaName : !type { optionalAttrDict} loc(optionalSourceLoc)`
1811 ///
1812 /// If `allowType` is false or `allowAttrs` are false then the respective
1813 /// parts of the grammar are not parsed.
1814 virtual ParseResult parseArgument(Argument &result, bool allowType = false,
1815 bool allowAttrs = false) = 0;
1816
1817 /// Parse a single argument if present.
1818 virtual OptionalParseResult
1819 parseOptionalArgument(Argument &result, bool allowType = false,
1820 bool allowAttrs = false) = 0;
1821
1822 /// Parse zero or more arguments with a specified surrounding delimiter.
1824 Delimiter delimiter = Delimiter::None,
1825 bool allowType = false,
1826 bool allowAttrs = false) = 0;
1827
1828 //===--------------------------------------------------------------------===//
1829 // Region Parsing
1830 //===--------------------------------------------------------------------===//
1831
1832 /// Parses a region. Any parsed blocks are appended to 'region' and must be
1833 /// moved to the op regions after the op is created. The first block of the
1834 /// region takes 'arguments'.
1835 ///
1836 /// If 'enableNameShadowing' is set to true, the argument names are allowed to
1837 /// shadow the names of other existing SSA values defined above the region
1838 /// scope. 'enableNameShadowing' can only be set to true for regions attached
1839 /// to operations that are 'IsolatedFromAbove'.
1840 virtual ParseResult parseRegion(Region &region,
1841 ArrayRef<Argument> arguments = {},
1842 bool enableNameShadowing = false) = 0;
1843
1844 /// Parses a region if present.
1845 virtual OptionalParseResult
1847 bool enableNameShadowing = false) = 0;
1848
1849 /// Parses a region if present. If the region is present, a new region is
1850 /// allocated and placed in `region`. If no region is present or on failure,
1851 /// `region` remains untouched.
1852 virtual OptionalParseResult
1853 parseOptionalRegion(std::unique_ptr<Region> &region,
1854 ArrayRef<Argument> arguments = {},
1855 bool enableNameShadowing = false) = 0;
1856
1857 //===--------------------------------------------------------------------===//
1858 // Successor Parsing
1859 //===--------------------------------------------------------------------===//
1860
1861 /// Parse a single operation successor.
1862 virtual ParseResult parseSuccessor(Block *&dest) = 0;
1863
1864 /// Parse an optional operation successor.
1866
1867 /// Parse a single operation successor and its operand list.
1868 virtual ParseResult
1870
1871 //===--------------------------------------------------------------------===//
1872 // Type Parsing
1873 //===--------------------------------------------------------------------===//
1874
1875 /// Parse a list of assignments of the form
1876 /// (%x1 = %y1, %x2 = %y2, ...)
1880 if (!result.has_value())
1881 return emitError(getCurrentLocation(), "expected '('");
1882 return result.value();
1883 }
1884
1885 virtual OptionalParseResult
1888};
1889
1890namespace detail {
1891/// Parse an optional operand or type into a generated parser's storage.
1892ParseResult parseOptionalOperandInto(
1893 OpAsmParser &parser,
1895ParseResult parseOptionalTypeInto(AsmParser &parser,
1896 SmallVectorImpl<Type> &types);
1897
1898/// Keep the cleanup of multiple generated parser operand groups out of each
1899/// parser's early-return paths. The storage is shared across operations with
1900/// the same number of groups.
1901template <size_t N>
1903public:
1905
1906 LLVM_ATTRIBUTE_NOINLINE OperandParserStorage() {}
1907 LLVM_ATTRIBUTE_NOINLINE ~OperandParserStorage() {}
1908
1909 Group &operator[](size_t index) { return groups[index]; }
1910
1911private:
1912 Group groups[N];
1913};
1914
1915} // namespace detail
1916
1917//===--------------------------------------------------------------------===//
1918// Custom printers and parsers.
1919//===--------------------------------------------------------------------===//
1920
1921// Handles custom<DimensionList>(...) in TableGen.
1922void printDimensionList(OpAsmPrinter &printer, Operation *op,
1923 ArrayRef<int64_t> dimensions);
1924ParseResult parseDimensionList(OpAsmParser &parser,
1925 DenseI64ArrayAttr &dimensions);
1926
1927} // namespace mlir
1928
1929//===--------------------------------------------------------------------===//
1930// Operation OpAsm interface.
1931//===--------------------------------------------------------------------===//
1932
1933/// The OpAsmOpInterface, see OpAsmInterface.td for more details.
1934#include "mlir/IR/OpAsmOpInterface.h.inc"
1935
1936//===--------------------------------------------------------------------===//
1937// Dialect OpAsm interface.
1938//===--------------------------------------------------------------------===//
1939
1940/// The OpAsmDialectInterface, see OpAsmDialectInterface.td
1941#include "mlir/IR/OpAsmDialectInterface.h.inc"
1942
1943namespace llvm {
1944template <>
1945struct DenseMapInfo<mlir::AsmDialectResourceHandle> {
1946 static unsigned getHashValue(const mlir::AsmDialectResourceHandle &handle) {
1947 return DenseMapInfo<void *>::getHashValue(handle.getResource());
1948 }
1950 const mlir::AsmDialectResourceHandle &rhs) {
1951 return lhs.getResource() == rhs.getResource();
1952 }
1953};
1954} // namespace llvm
1955
1956#endif
return success()
return MutableOperandRange * this
ArrayAttr()
if(!isCopyOut)
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
AsmDialectResourceHandleBase(AsmDialectResourceHandle handle)
const ResourceT * getResource() const
static bool classof(const AsmDialectResourceHandle *handle)
Support llvm style casting.
AsmDialectResourceHandleBase(ResourceT *resource, DialectT *dialect)
Construct a handle from a pointer to the resource.
ResourceT * getResource()
Return the resource referenced by this handle.
DialectT * getDialect() const
Return the dialect that owns the resource.
This class represents an opaque handle to a dialect resource entry.
TypeID getTypeID() const
Return the type ID of the resource.
Dialect * getDialect() const
Return the dialect that owns the resource.
void * getResource() const
Return an opaque pointer to the referenced resource.
bool operator==(const AsmDialectResourceHandle &other) const
AsmDialectResourceHandle(void *resource, TypeID resourceID, Dialect *dialect)
This class represents a single parsed resource entry.
Definition AsmState.h:291
Class used to automatically end a cyclic region on destruction.
CyclicParseReset & operator=(CyclicParseReset &&rhs)
CyclicParseReset(const CyclicParseReset &)=delete
CyclicParseReset & operator=(const CyclicParseReset &)=delete
CyclicParseReset(CyclicParseReset &&rhs)
bool hasValue() const
Returns true if this switch has a value yet.
KeywordSwitch & Default(FnT &&fn)
KeywordSwitch & Case(StringLiteral str, FnT &&fn)
Case that invokes the provided functor when true.
KeywordSwitch & Default(ResultT value)
KeywordSwitch & Case(StringLiteral str, ResultT value)
Case that uses the provided value when true.
KeywordSwitch(AsmParser &parser, StringRef *keyword=nullptr)
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseMinus()=0
Parse a '-' token.
llvm::is_detected< has_parse_method, AttrType > detect_has_parse_method
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
std::enable_if_t< detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type={})
Parse a custom attribute of a given type unless the next token is #, in which case the generic parser...
virtual ParseResult parseLBrace()=0
Parse a { token.
Delimiter
These are the supported delimiters around operand lists and region argument lists,...
@ Paren
Parens surrounding zero or more operands.
@ None
Zero or more operands with no delimiters.
@ OptionalLessGreater
<> brackets supporting zero or more ops, or nothing.
@ Braces
{} brackets surrounding zero or more operands.
@ OptionalBraces
{} brackets surrounding zero or more operands, or nothing.
@ OptionalParen
Parens supporting zero or more operands, or nothing.
@ Square
Square brackets surrounding zero or more operands.
@ LessGreater
<> brackets surrounding zero or more operands.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
decltype(TypeT::parse(std::declval< AsmParser & >())) type_has_parse_method
Trait to check if TypeT provides a parse method.
virtual OptionalParseResult parseOptionalInteger(APInt &result)=0
Parse an optional integer value from the stream.
AsmParser()=default
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual ParseResult parseIntegerSet(IntegerSet &set)=0
Parse an integer set instance into 'set'.
virtual ParseResult parseOptionalKeywordOrString(std::string *result)=0
Parse an optional keyword or string.
virtual ParseResult parseOptionalSymbolName(StringAttr &result)=0
Parse an optional -identifier and store it (without the '@' symbol) in a string attribute.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalRBrace()=0
Parse a } token if present.
ParseResult parseDecimalInteger(IntT &result)
Parse a decimal integer value from the stream.
virtual ParseResult parseOptionalMinus()=0
Parse a '-' token if present.
virtual ParseResult parsePlus()=0
Parse a '+' token.
ParseResult parseKeyword(StringRef *keyword)
Parse a keyword into 'keyword'.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual void popCyclicParsing()=0
Removes the element that was last inserted with a successful call to pushCyclicParsing.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
decltype(AttrType::parse(std::declval< AsmParser & >(), std::declval< Type >())) has_parse_method
Trait to check if AttrType provides a parse method.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
virtual OptionalParseResult parseOptionalType(Type &result)=0
Parse an optional type.
MLIRContext * getContext() const
virtual Location getEncodedSourceLoc(SMLoc loc)=0
Re-encode the given source location as an MLIR location and return it.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
virtual ParseResult parseOptionalColonTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional colon followed by a type list, which if present must have at least one type.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalArrow()=0
Parse a '->' token if present.
ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName, NamedAttrList &attrs)
Parse an optional -identifier and store it (without the '@' symbol) in a string attribute named 'attr...
virtual OptionalParseResult parseOptionalDecimalInteger(APInt &result)=0
ParseResult parseAttribute(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
Parse an arbitrary attribute of a given type and populate it in result.
ParseResult parseAttribute(AttrType &result, Type type={})
Parse an attribute of a specific kind and type.
ParseResult parseKeywordOrString(std::string *result)
Parse a keyword or a quoted string.
virtual void codeCompleteExpectedTokens(ArrayRef< StringRef > tokens)=0
Signal the code completion of a set of expected tokens.
virtual ParseResult parseRBrace()=0
Parse a } token.
virtual ParseResult parseAffineMap(AffineMap &map)=0
Parse an affine map instance into 'map'.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseOptionalKeywordOrString(std::string *result, ArrayRef< StringRef > allowedValues)=0
Parse an optional keyword or string into result if it is present and one of the 'allowedValues'.
virtual ParseResult parseOptionalRParen()=0
Parse a ) token if present.
virtual ParseResult parseCustomAttributeWithFallback(Attribute &result, Type type, function_ref< ParseResult(Attribute &result, Type type)> parseAttribute)=0
Parse a custom attribute with the provided callback, unless the next token is #, in which case the ge...
OptionalParseResult parseOptionalAttribute(AttrType &result, Type type={})
Parse an optional attribute of a specific typed result.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
ParseResult parseString(std::string *string)
Parse a quoted string token.
virtual ParseResult parseOptionalPlus()=0
Parse a '+' token if present.
virtual ParseResult parseOptionalKeyword(StringRef *keyword, ArrayRef< StringRef > allowedValues)=0
Parse a keyword, if present, and if one of the 'allowedValues', into 'keyword'.
virtual ParseResult parseOptionalGreater()=0
Parse a '>' token if present.
std::enable_if_t<!detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type={})
SFINAE parsing method for Attribute that don't implement a parse method.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseCustomTypeWithFallback(Type &result, function_ref< ParseResult(Type &result)> parseType)=0
Parse a custom type with the provided callback, unless the next token is #, in which case the generic...
virtual ParseResult parseFloat(const llvm::fltSemantics &semantics, APFloat &result)=0
Parse a floating point value into APFloat from the stream.
virtual OptionalParseResult parseOptionalAttribute(ArrayAttr &result, Type type={})=0
Parse an optional array attribute and return it in result.
virtual ParseResult parseStar()=0
Parse a '*' token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual OptionalParseResult parseOptionalAttribute(Attribute &result, Type type={})=0
Parse an arbitrary optional attribute of a given type and return it in result.
virtual ParseResult parseSlash()=0
Parse a '/' token.
ParseResult parseCommaSeparatedList(function_ref< ParseResult()> parseElementFn)
Parse a comma separated list of elements that must have at least one entry in it.
virtual ParseResult parseVerticalBar()=0
Parse a '|' token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
std::enable_if_t<!detect_type_has_parse_method< TypeT >::value, ParseResult > parseCustomTypeWithFallback(TypeT &result)
SFINAE parsing method for Type that don't implement a parse method.
OptionalParseResult parseOptionalAttribute(AttrType &result, StringRef attrName, NamedAttrList &attrs)
Parse an optional attribute of a specific type and add it to the list with the specified name.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
std::enable_if_t< detect_type_has_parse_method< TypeT >::value, ParseResult > parseCustomTypeWithFallback(TypeT &result)
Parse a custom Type of a given type unless the next token is #, in which case the generic parser is i...
virtual ParseResult parseColon()=0
Parse a : token.
ParseResult addTypesToList(ArrayRef< Type > types, SmallVectorImpl< Type > &result)
Add the specified types to the end of the specified type list and return success.
ParseResult parseAttribute(Attribute &result, StringRef attrName, NamedAttrList &attrs)
Parse an arbitrary attribute and return it in result.
FailureOr< ResourceT > parseResourceHandle()
Parse a handle to a resource within the assembly format.
virtual OptionalParseResult parseOptionalAttribute(StringAttr &result, Type type={})=0
Parse an optional string attribute and return it in result.
llvm::is_detected< type_has_parse_method, TypeT > detect_type_has_parse_method
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalString(std::string *string)=0
Parse a quoted string token if present.
std::enable_if_t< detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
Parse a custom attribute of a given type unless the next token is #, in which case the generic parser...
OptionalParseResult parseOptionalInteger(IntT &result)
ParseResult getCurrentLocation(SMLoc *loc)
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseOptionalStar()=0
Parse a '*' token if present.
OptionalParseResult parseOptionalAttribute(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
Parse an optional attribute of a specific type and add it to the list with the specified name.
virtual OptionalParseResult parseOptionalAttribute(SymbolRefAttr &result, Type type={})=0
Parse an optional symbol ref attribute and return it in result.
virtual ParseResult parseOptionalString(std::string *string, ArrayRef< StringRef > allowedValues)=0
Parse a string into 'string' if it is present and one of the 'allowedValues'.
virtual ParseResult parseQuestion()=0
Parse a '?' token.
virtual ParseResult parseOptionalSlash()=0
Parse a '/' token if present.
ParseResult parseType(TypeT &result)
Parse a type of a specific type.
FailureOr< CyclicParseReset > tryStartCyclicParse(AttrOrTypeT attrOrType)
Attempts to start a cyclic parsing region for attrOrType.
virtual ParseResult parseOptionalRSquare()=0
Parse a ] token if present.
virtual ParseResult parseArrow()=0
Parse a '->' token.
ParseResult parseColonType(TypeType &result)
Parse a colon followed by a type of a specific kind, e.g. a FunctionType.
virtual ParseResult parseGreater()=0
Parse a '>' token.
OptionalParseResult parseOptionalDecimalInteger(IntT &result)
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseOptionalEllipsis()=0
Parse a ... token if present;.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseAttribute(AttrType &result, StringRef attrName, NamedAttrList &attrs)
Parse an attribute of a specific kind and type.
virtual FailureOr< AsmDialectResourceHandle > parseResourceHandle(Dialect *dialect)=0
Parse a handle to a resource within the assembly format for the given dialect.
virtual ParseResult parseEllipsis()=0
Parse a ... token.
auto getChecked(ParamsT &&...params)
A variant of getChecked that uses the result of getNameLoc to emit errors.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeywordType(const char *keyword, Type &result)
Parse a keyword followed by a type.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
virtual ~AsmParser()
virtual ParseResult parseOptionalVerticalBar()=0
Parse a '|' token if present.
ParseResult parseTypeList(SmallVectorImpl< Type > &result)
Parse a type list.
virtual ParseResult parseBase64Bytes(std::vector< char > *bytes)=0
Parses a Base64 encoded string of bytes.
virtual ParseResult parseAffineExpr(ArrayRef< std::pair< StringRef, AffineExpr > > symbolSet, AffineExpr &expr)=0
Parse an affine expr instance into 'expr' using the already computed mapping from symbols to affine e...
virtual ParseResult parseKeywordOrCompletion(StringRef *keyword)=0
Parse a keyword, or an empty string if the current location signals a code completion.
virtual ParseResult parseFloat(double &result)=0
Parse a floating point value from the stream.
ParseResult parseSymbolName(StringAttr &result, StringRef attrName, NamedAttrList &attrs)
Parse an -identifier and store it (without the '@' symbol) in a string attribute named 'attrName'.
virtual ParseResult parseOptionalKeyword(StringRef *keyword)=0
Parse a keyword, if present, into 'keyword'.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
virtual LogicalResult pushCyclicParsing(const void *opaquePointer)=0
Pushes a new attribute or type in the form of a type erased pointer into an internal set.
std::enable_if_t<!detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
SFINAE parsing method for Attribute that don't implement a parse method.
virtual ParseResult parseOptionalQuestion()=0
Parse a '?' token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual ParseResult parseXInDimensionList()=0
Parse an 'x' token in a dimension list, handling the case where the x is juxtaposed with an element t...
virtual ParseResult parseOptionalLBrace()=0
Parse a { token if present.
virtual ParseResult parseKeyword(StringRef keyword, const Twine &msg)=0
Class used to automatically end a cyclic region on destruction.
CyclicPrintReset & operator=(CyclicPrintReset &&rhs)
CyclicPrintReset & operator=(const CyclicPrintReset &)=delete
CyclicPrintReset(const CyclicPrintReset &)=delete
CyclicPrintReset(CyclicPrintReset &&rhs)
void printStrippedAttrOrType(char value)
Print a plain char parameter as a bare keyword for identifier characters (e.g.
void printStrippedAttrOrType(ArrayRef< AttrOrType > attrOrTypes)
Print the provided array of attributes or types in the context of an operation custom printer/parser:...
virtual void decreaseIndent()
Decrease indentation.
decltype(std::declval< AttrOrType >().print(std::declval< AsmPrinter & >())) has_print_method
Trait to check if AttrType provides a print method.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual LogicalResult printAlias(Attribute attr)
Print the alias for the given attribute, return failure if no alias could be printed.
virtual void popCyclicPrinting()
Removes the element that was last inserted with a successful call to pushCyclicPrinting.
AsmPrinter()=default
Initialize the printer with no internal implementation.
virtual void increaseIndent()
Increase indentation.
void printFunctionalType(InputRangeT &&inputs, ResultRangeT &&results)
Print the two given type ranges in a functional form.
void printStrippedAttrOrType(ArrayRef< char > values)
Print an array of plain char parameters element-wise with the char overload above,...
virtual LogicalResult pushCyclicPrinting(const void *opaquePointer)
Pushes a new attribute or type in the form of a type erased pointer into an internal set.
virtual void printType(Type type)
virtual void printKeywordOrString(StringRef keyword)
Print the given string as a keyword, or a quoted and escaped string if it has any special or non-prin...
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
virtual void printString(StringRef string)
Print the given string as a quoted string, escaping any special or non-printable characters in it.
FailureOr< CyclicPrintReset > tryStartCyclicPrint(AttrOrTypeT attrOrType)
Attempts to start a cyclic printing region for attrOrType.
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
llvm::is_detected< has_print_method, AttrOrType > detect_has_print_method
virtual void printAttribute(Attribute attr)
void printDimensionList(ArrayRef< int64_t > shape)
void printArrowTypeList(TypeRange &&types)
void printInteger(IntT value)
Print the given integer value.
virtual ~AsmPrinter()
virtual raw_ostream & getStream() const
Return the raw output stream used by this printer.
virtual void printResourceHandle(const AsmDialectResourceHandle &resource)
Print a handle to the given dialect resource.
virtual void printFloat(const APFloat &value)
Print the given floating point value in a stabilized form that can be roundtripped through the IR.
virtual void printNamedAttribute(NamedAttribute attr)
Print the given named attribute.
virtual void printNewline()
Print a newline and indent the printer to the start of the current operation/attribute/type.
void printStrippedAttrOrType(std::optional< IntT > value)
Print a present optional integer parameter through the overloads for its underlying type,...
void printStrippedAttrOrType(AttrOrType attrOrType)
Print the provided attribute in the context of an operation custom printer/parser: this will invoke d...
AsmPrinter(Impl &impl)
Initialize the printer with the given internal implementation.
This class is used to build resource entries for use by the printer.
Definition AsmState.h:247
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType::iterator iterator
Definition Block.h:165
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
This class represents a diagnostic that is inflight and set to be reported.
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition IntegerSet.h:44
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual size_t getNumResults() const =0
Return the number of declared SSA results.
AsmParser()=default
virtual OptionalParseResult parseOptionalAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)=0
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
~OpAsmParser() override
virtual ParseResult parseSuccessor(Block *&dest)=0
Parse a single operation successor.
virtual std::pair< StringRef, unsigned > getResultName(unsigned resultNo) const =0
Return the name of the specified result in the specified syntax, as well as the sub-element in the na...
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
ParseResult parseTrailingOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None)
Parse zero or more trailing SSA comma-separated trailing operand references with a specified surround...
ParseResult resolveOperands(Operands &&operands, Type type, SMLoc loc, SmallVectorImpl< Value > &result)
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult parseAffineMapOfSSAIds(SmallVectorImpl< UnresolvedOperand > &operands, Attribute &map, StringRef attrName, NamedAttrList &attrs, Delimiter delimiter=Delimiter::Square)=0
Parses an affine map attribute where dims and symbols are SSA operands.
ParseResult resolveOperands(Operands &&operands, Types &&types, SMLoc loc, SmallVectorImpl< Value > &result)
Resolve a list of operands and a list of operand types to SSA values, emitting an error and returning...
virtual OptionalParseResult parseOptionalArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument if present.
virtual ParseResult parseOptionalLocationSpecifier(std::optional< Location > &result)=0
Parse a loc(...) specifier if present, filling in result if so.
ParseResult parseAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)
Parse a list of assignments of the form (x1 = y1, x2 = y2, ...)
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
virtual OptionalParseResult parseOptionalOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single operand if present.
virtual FailureOr< OperationName > parseCustomOperationName()=0
Parse the name of an operation, in the custom form.
virtual ParseResult parseSuccessorAndUseList(Block *&dest, SmallVectorImpl< Value > &operands)=0
Parse a single operation successor and its operand list.
virtual OptionalParseResult parseOptionalRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual Operation * parseGenericOperation(Block *insertBlock, Block::iterator insertPt)=0
Parse an operation in its generic form.
ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, int requiredOperandCount, Delimiter delimiter=Delimiter::None)
Parse a specified number of comma separated operands.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseAffineExprOfSSAIds(SmallVectorImpl< UnresolvedOperand > &dimOperands, SmallVectorImpl< UnresolvedOperand > &symbOperands, AffineExpr &expr)=0
Parses an affine expression where dims and symbols are SSA operands.
virtual OptionalParseResult parseOptionalSuccessor(Block *&dest)=0
Parse an optional operation successor.
virtual ParseResult parseGenericOperationAfterOpName(OperationState &result, std::optional< ArrayRef< UnresolvedOperand > > parsedOperandType=std::nullopt, std::optional< ArrayRef< Block * > > parsedSuccessors=std::nullopt, std::optional< MutableArrayRef< std::unique_ptr< Region > > > parsedRegions=std::nullopt, std::optional< ArrayRef< NamedAttribute > > parsedAttributes=std::nullopt, std::optional< Attribute > parsedPropertiesAttribute=std::nullopt, std::optional< FunctionType > parsedFnType=std::nullopt)=0
Parse different components, viz., use-info of operand(s), successor(s), region(s),...
virtual OptionalParseResult parseOptionalRegion(std::unique_ptr< Region > &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
void printOperands(IteratorType it, IteratorType end)
Print a comma separated list of operands.
virtual void shadowRegionArgs(Region &region, ValueRange namesToUse)=0
Renumber the arguments for the specified region to the same names as the SSA values in namesToUse.
virtual void printSuccessorAndUseList(Block *successor, ValueRange succOperands)=0
Print the successor and its operands.
void printOperands(const ContainerType &container)
Print a comma separated list of operands.
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
void printOptionalAttrDict(DictionaryAttr attrs, ArrayRef< StringRef > elidedAttrs={})
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printOptionalLocationSpecifier(Location loc)=0
Print a loc(...) specifier if printing debug info is enabled.
virtual void printCustomOrGenericOp(Operation *op)=0
Prints the entire operation with the custom assembly form, if available, or the generic assembly form...
void printOperandTypes(ValueTypeRange< OperandRange > types)
Print the types of a comma separated range of operation operands.
virtual void printOperand(Value value, raw_ostream &os)=0
virtual void printSuccessor(Block *successor)=0
Print the given successor.
virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands, ValueRange symOperands)=0
Prints an affine expression of SSA ids with SSA id names used instead of dims and symbols.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr, ValueRange operands)=0
Prints an affine map of SSA ids, where SSA id names are used in place of dims/symbols.
virtual void printGenericOp(Operation *op, bool printOpName=true)=0
Print the entire operation with the default generic assembly form.
~OpAsmPrinter() override
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
virtual void printRegionArgument(BlockArgument arg, ArrayRef< NamedAttribute > argAttrs={}, bool omitType=false)=0
Print a block argument in the usual format of: ssaName : type {attr1=42} loc("here") where location p...
virtual void printOperand(Value value)=0
Print implementations for various things an operation contains.
AsmPrinter(Impl &impl)
Initialize the printer with the given internal implementation.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
static TypeID get()
Construct a type info object for the given type T.
Definition TypeID.h:245
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class implements iteration on the types of a given range of values.
Definition TypeRange.h:147
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
LLVM_ATTRIBUTE_NOINLINE OperandParserStorage()
llvm::SmallVector< OpAsmParser::UnresolvedOperand, 4 > Group
LLVM_ATTRIBUTE_NOINLINE ~OperandParserStorage()
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
AttrTypeReplacer.
ParseResult parseOptionalTypeInto(AsmParser &parser, SmallVectorImpl< Type > &types)
ParseResult parseOptionalOperandInto(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &operands)
Parse an optional operand or type into a generated parser's storage.
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
ParseResult parseDimensionList(OpAsmParser &parser, DenseI64ArrayAttr &dimensions)
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
void printDimensionList(OpAsmPrinter &printer, Operation *op, ArrayRef< int64_t > dimensions)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
inline ::llvm::hash_code hash_value(AffineExpr arg)
Make AffineExpr hashable.
Definition AffineExpr.h:249
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
static unsigned getHashValue(const mlir::AsmDialectResourceHandle &handle)
static bool isEqual(const mlir::AsmDialectResourceHandle &lhs, const mlir::AsmDialectResourceHandle &rhs)
std::optional< Location > sourceLoc
This is the representation of an operand reference.
This represents an operation in an abstracted form, suitable for use with the builder APIs.